public static void Output(AttackState attackState) { if (attackState.cmdComplete) { printPrompt(attackState); } int currentCusorPos = Console.CursorTop; string prompt = createPrompt(attackState); Console.SetCursorPosition(prompt.Length, attackState.promptPos); Console.Write(new string(' ', Console.WindowWidth)); int cursorDiff = currentCusorPos - attackState.promptPos; while (cursorDiff > 0) { Console.SetCursorPosition(0, attackState.promptPos + cursorDiff); Console.Write(new string(' ', Console.WindowWidth)); cursorDiff -= 1; } Console.SetCursorPosition(prompt.Length, attackState.promptPos); Console.Write(attackState.displayCmd); int consoleWrapCount = attackState.consoleWrapCount(); int relativeCursorPos = attackState.relativeCursorPos(); if (attackState.cursorPos >= Console.WindowWidth) { attackState.cursorPos = attackState.cursorPos - Console.WindowWidth * consoleWrapCount; } Console.SetCursorPosition(attackState.cursorPos, attackState.promptPos + consoleWrapCount); }
public static void Output(AttackState attackState) { if (attackState.cmdComplete) { printPrompt(attackState); } int currentCusorPos = Console.CursorTop; string prompt = createPrompt(attackState); // This is where we juggle things to make sure the cursor ends up where // it's expected to be. I'm sure this could be improved on. // Clear out typed text after prompt Console.SetCursorPosition(prompt.Length, attackState.promptPos); Console.Write(new string(' ', Console.WindowWidth)); // Clear out any lines below the prompt int cursorDiff = attackState.consoleWrapCount(); while (cursorDiff > 0) { Console.SetCursorPosition(0, attackState.promptPos + cursorDiff); Console.Write(new string(' ', Console.WindowWidth)); cursorDiff -= 1; } Console.SetCursorPosition(prompt.Length, attackState.promptPos); // Re-print the command Console.Write(attackState.displayCmd); List<int> cursorXY = attackState.getCursorXY(); Console.SetCursorPosition(cursorXY[0], cursorXY[1]); }
public static void printPrompt(AttackState attackState) { attackState.promptPos = Console.CursorTop; string prompt = createPrompt(attackState); Console.ForegroundColor = PSColors.prompt; Console.Write(prompt); Console.ForegroundColor = PSColors.inputText; attackState.cursorPos = prompt.Length; }
public static void ImportModules(AttackState attackState, Stream moduleStream) { try { MemoryStream decMem = CryptoUtils.DecryptFile(moduleStream); attackState.cmd = Encoding.Unicode.GetString(decMem.ToArray()); Processing.PSExec(attackState); } catch (Exception e) { ConsoleColor origColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Write(Strings.moduleLoadError, e.Message); Console.ForegroundColor = origColor; } }
public static void ImportModules(AttackState attackState, Stream moduleStream) { Assembly assembly = Assembly.GetExecutingAssembly(); StreamReader keyReader = new StreamReader(assembly.GetManifestResourceStream("PSAttack.Modules.key.txt")); string key = keyReader.ReadToEnd(); try { MemoryStream decMem = CryptoUtils.DecryptFile(moduleStream); attackState.cmd = Encoding.Unicode.GetString(decMem.ToArray()); Processing.PSExec(attackState); } catch (Exception e) { ConsoleColor origColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Write(Strings.moduleLoadError, e.Message); Console.ForegroundColor = origColor; } }
public static void Exception(AttackState attackState, string errorMsg) { Console.ForegroundColor = PSColors.errorText; Console.WriteLine("ERROR: {0}\n", errorMsg); }
// COMMAND AUTOCOMPLETE static AttackState cmdAutoComplete(AttackState attackState) { attackState.cmd = "Get-Command " + attackState.cmdComponents[attackState.cmdComponentsIndex].Contents + "*"; attackState = Processing.PSExec(attackState); return(attackState); }
public static string createPrompt(AttackState attackState) { string prompt = attackState.runspace.SessionStateProxy.Path.CurrentLocation + " #> "; return prompt; }
// PATH AUTOCOMPLETE static AttackState pathAutoComplete(AttackState attackState) { string pathSeed = attackState.cmdComponents[attackState.cmdComponentsIndex].Contents.Replace("\"",""); attackState.cmd = "Get-ChildItem \"" + pathSeed.Trim() + "*\""; Console.WriteLine(attackState.cmd); attackState = Processing.PSExec(attackState); return attackState; }
// VARIABLE AUTOCOMPLETE static AttackState variableAutoComplete(AttackState attackState) { string variableSeed = attackState.cmdComponents[attackState.cmdComponentsIndex].Contents.Replace("$", ""); attackState.cmd = "Get-Variable " + variableSeed + "*"; attackState = Processing.PSExec(attackState); return attackState; }
public static AttackState Process(AttackState attackState) { if (attackState.loopType == null) { attackState.cmdComponents = dislayCmdComponents(attackState); // route to appropriate autcomplete handler DisplayCmdComponent cmdSeed = attackState.cmdComponents[attackState.cmdComponentsIndex]; attackState.loopType = cmdSeed.Type; switch (cmdSeed.Type) { case "param": attackState = paramAutoComplete(attackState); break; case "variable": attackState = variableAutoComplete(attackState); break; case "path": attackState = pathAutoComplete(attackState); break; default: attackState = cmdAutoComplete(attackState); break; } } // If we're already in an autocomplete loop, increment loopPos appropriately else if (attackState.loopType != null) { if (attackState.keyInfo.Modifiers == ConsoleModifiers.Shift) { attackState.loopPos -= 1; // loop around if we're at the beginning if (attackState.loopPos < 0) { attackState.loopPos = attackState.results.Count - 1; } } else { attackState.loopPos += 1; // loop around if we reach the end if (attackState.loopPos >= attackState.results.Count) { attackState.loopPos = 0; } } } // if we have results, format them and return them if (attackState.results.Count > 0) { string seperator = " "; string result; switch (attackState.loopType) { case "param": seperator = " -"; result = attackState.results[attackState.loopPos].ToString(); break; case "variable": seperator = " $"; result = attackState.results[attackState.loopPos].Members["Name"].Value.ToString(); break; case "path": seperator = " "; result = "\"" + attackState.results[attackState.loopPos].Members["FullName"].Value.ToString() + "\""; break; default: result = attackState.results[attackState.loopPos].BaseObject.ToString(); break; } // reconstruct display cmd from components string completedCmd = ""; int i = 0; int cursorPos = attackState.promptLength; while (i < attackState.cmdComponents.Count()) { if (i == attackState.cmdComponentsIndex) { completedCmd += seperator + result; cursorPos += completedCmd.TrimStart().Length; } else { completedCmd += attackState.cmdComponents[i].Contents; } i++; } attackState.displayCmd = completedCmd.TrimStart(); attackState.cursorPos = cursorPos; } return attackState; }
// PARAMETER AUTOCOMPLETE static AttackState paramAutoComplete(AttackState attackState) { int index = attackState.cmdComponentsIndex; string paramSeed = attackState.cmdComponents[index].Contents.Replace(" -", ""); string result = ""; while (result != "cmd") { index -= 1; result = attackState.cmdComponents[index].Type; } string paramCmd = attackState.cmdComponents[index].Contents; attackState.cmd = "(Get-Command " + paramCmd + ").Parameters.Keys | Where{$_ -like '" + paramSeed + "*'}"; attackState = Processing.PSExec(attackState); return attackState; }
// COMMAND AUTOCOMPLETE static AttackState cmdAutoComplete(AttackState attackState) { attackState.cmd = "Get-Command " + attackState.cmdComponents[attackState.cmdComponentsIndex].Contents + "*"; attackState = Processing.PSExec(attackState); return attackState; }
// This function splits text on the command line up and identifies each component static List<DisplayCmdComponent> dislayCmdComponents(AttackState attackState) { List<DisplayCmdComponent> results = new List<DisplayCmdComponent>(); String[] displayCmdItemList = Regex.Split(attackState.displayCmd, @"(?=[\s])"); int index = 0; int cmdLength = attackState.promptLength + 1; foreach (string item in displayCmdItemList) { string itemType = seedIdentification(item); DisplayCmdComponent itemSeed = new DisplayCmdComponent(); itemSeed.Index = index; itemSeed.Contents = item; itemSeed.Type = itemType; cmdLength += item.Length; if ((cmdLength > attackState.cursorPos) && (attackState.cmdComponentsIndex == -1)) { attackState.cmdComponentsIndex = index; } if (itemType == "path" || itemType == "unknown") { if (results.Last().Type == "path") { results.Last().Contents += itemSeed.Contents; } else { results.Add(itemSeed); index++; } } else { results.Add(itemSeed); index++; } } return results; }
public static AttackState Process(AttackState attackState) { if (attackState.loopType == null) { int lastSpace = attackState.displayCmd.LastIndexOf(" "); if (lastSpace > 0) { // get the command that we're autocompleting for by looking for the last space and pipe // anything after the last space we're going to try and autocomplete. Anything between the // last pipe and last space we assume is a command. int lastPipe = attackState.displayCmd.Substring(0, lastSpace + 1).LastIndexOf("|"); attackState.autocompleteSeed = attackState.displayCmd.Substring(lastSpace); if (lastSpace - lastPipe > 2) { attackState.displayCmdSeed = attackState.displayCmd.Substring(lastPipe + 1, (lastSpace - lastPipe)); } else { attackState.displayCmdSeed = attackState.displayCmd.Substring(0, lastSpace); } // trim leading space from command in the event of "cmd | cmd" if (attackState.displayCmdSeed.IndexOf(" ").Equals(0)) { attackState.displayCmdSeed = attackState.displayCmd.Substring(1, lastSpace); } } else { attackState.autocompleteSeed = attackState.displayCmd; attackState.displayCmdSeed = ""; } if (attackState.autocompleteSeed.Length == 0) { return(attackState); } // route to appropriate autcomplete handler attackState.loopType = seedIdentification(attackState.autocompleteSeed); switch (attackState.loopType) { case "param": attackState = paramAutoComplete(attackState); break; case "variable": attackState = variableAutoComplete(attackState); break; case "path": attackState = pathAutoComplete(attackState); break; default: attackState = cmdAutoComplete(attackState); break; } } // If we're already in an autocomplete loop, increment loopPos appropriately else if (attackState.loopType != null) { if (attackState.keyInfo.Modifiers == ConsoleModifiers.Shift) { attackState.loopPos -= 1; // loop around if we're at the beginning if (attackState.loopPos < 0) { attackState.loopPos = attackState.results.Count - 1; } } else { attackState.loopPos += 1; // loop around if we reach the end if (attackState.loopPos >= attackState.results.Count) { attackState.loopPos = 0; } } } // if we have results, format them and return them if (attackState.results.Count > 0) { string seperator = ""; string result; switch (attackState.loopType) { case "param": seperator = "-"; result = attackState.results[attackState.loopPos].ToString(); break; case "variable": seperator = "$"; result = attackState.results[attackState.loopPos].Members["Name"].Value.ToString(); break; case "path": result = "\"" + attackState.results[attackState.loopPos].Members["FullName"].Value.ToString() + "\""; break; default: result = attackState.results[attackState.loopPos].BaseObject.ToString(); break; } attackState.displayCmd = attackState.displayCmdSeed + seperator + result; attackState.cursorPos = attackState.endOfDisplayCmdPos(); } return(attackState); }
public static AttackState Process(AttackState attackState) { if (attackState.loopType == null) { attackState.cmdComponents = dislayCmdComponents(attackState); // route to appropriate autcomplete handler DisplayCmdComponent cmdSeed = attackState.cmdComponents[attackState.cmdComponentsIndex]; attackState.loopType = cmdSeed.Type; switch (cmdSeed.Type) { case "param": attackState = paramAutoComplete(attackState); break; case "variable": attackState = variableAutoComplete(attackState); break; case "path": attackState = pathAutoComplete(attackState); break; default: attackState = cmdAutoComplete(attackState); break; } } // If we're already in an autocomplete loop, increment loopPos appropriately else if (attackState.loopType != null) { if (attackState.keyInfo.Modifiers == ConsoleModifiers.Shift) { attackState.loopPos -= 1; // loop around if we're at the beginning if (attackState.loopPos < 0) { attackState.loopPos = attackState.results.Count - 1; } } else { attackState.loopPos += 1; // loop around if we reach the end if (attackState.loopPos >= attackState.results.Count) { attackState.loopPos = 0; } } } // if we have results, format them and return them if (attackState.results.Count > 0) { string seperator = " "; string result; switch (attackState.loopType) { case "param": seperator = " -"; result = attackState.results[attackState.loopPos].ToString(); break; case "variable": seperator = " $"; result = attackState.results[attackState.loopPos].Members["Name"].Value.ToString(); break; case "path": seperator = " "; result = "\"" + attackState.results[attackState.loopPos].Members["FullName"].Value.ToString() + "\""; break; default: result = attackState.results[attackState.loopPos].BaseObject.ToString(); break; } // reconstruct display cmd from components string completedCmd = ""; int i = 0; int cursorPos = attackState.promptLength; while (i < attackState.cmdComponents.Count()) { if (i == attackState.cmdComponentsIndex) { completedCmd += seperator + result; cursorPos += completedCmd.TrimStart().Length; } else { completedCmd += attackState.cmdComponents[i].Contents; } i++; } attackState.displayCmd = completedCmd.TrimStart(); attackState.cursorPos = cursorPos; } return(attackState); }
static AttackState PSInit() { // Display Loading Message Console.ForegroundColor = PSColors.logoText; Random random = new Random(); int pspLogoInt = random.Next(Strings.psaLogos.Count); Console.WriteLine(Strings.psaLogos[pspLogoInt]); Console.WriteLine("Loading..."); // create attackState AttackState attackState = new AttackState(); attackState.cursorPos = attackState.promptLength; // Get Encrypted Values Assembly assembly = Assembly.GetExecutingAssembly(); Stream valueStream = assembly.GetManifestResourceStream("PSAttack.Resources." + Properties.Settings.Default.valueStore); MemoryStream valueStore = CryptoUtils.DecryptFile(valueStream); string valueStoreStr = Encoding.Unicode.GetString(valueStore.ToArray()); string[] valuePairs = valueStoreStr.Replace("\r","").Split('\n'); foreach (string value in valuePairs) { if (value != "") { string[] entry = value.Split('|'); attackState.decryptedStore.Add(entry[0], entry[1]); } } // amsi bypass (thanks matt!!) if (Environment.OSVersion.Version.Major > 9) { try { attackState.cmd = attackState.decryptedStore["amsiBypass"]; Processing.PSExec(attackState); } catch { Console.WriteLine("Could not run AMSI bypass."); } } // Decrypt modules string[] resources = assembly.GetManifestResourceNames(); foreach (string resource in resources) { if (resource.Contains("PSAttack.Modules.")) { string fileName = resource.Replace("PSAttack.Modules.", ""); string decFilename = CryptoUtils.DecryptString(fileName); Console.ForegroundColor = PSColors.loadingText; Console.WriteLine("Decrypting: {0}", decFilename); Stream moduleStream = assembly.GetManifestResourceStream(resource); PSAUtils.ImportModules(attackState, moduleStream); } } // Setup PS env attackState.cmd = attackState.decryptedStore["setExecutionPolicy"]; Processing.PSExec(attackState); // check for admin Boolean isAdmin = false; Boolean debugProc = false; if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { isAdmin = true; try { System.Diagnostics.Process.EnterDebugMode(); debugProc = true; } catch { Console.Write("Could not grab debug rights for process."); } } // Setup Console Console.Title = Strings.windowTitle; Console.BufferHeight = Int16.MaxValue - 10; Console.BackgroundColor = PSColors.background; Console.TreatControlCAsInput = true; Console.Clear(); // get build info string buildString; Boolean builtWithBuildTool = true; DateTime storedBuildDate = new DateTime(); try { storedBuildDate = Convert.ToDateTime(attackState.decryptedStore["buildDate"]); } catch { } DateTime textBuildDate = new DateTime(); try { string buildDate = new StreamReader(assembly.GetManifestResourceStream("PSAttack.Resources.BuildDate.txt")).ReadToEnd(); textBuildDate = Convert.ToDateTime(buildDate); } catch { } if (storedBuildDate > textBuildDate) { buildString = "Build Date " + storedBuildDate + "\n\nThis is a custom baked build.\n"; } else { buildString = "Build Date " + textBuildDate + "\n\nIf you'd like a version of PS>Attack thats even harder for AV \nto detect checkout http://github.com/jaredhaight/PSAttackBuildTool \n"; builtWithBuildTool = false; } // Figure out if we're 32 or 64bit string arch = "64bit"; if (IntPtr.Size == 4) { arch = "32bit"; } // setup debug variable String debugCmd = "$debug = @{'psaVersion'='" + Strings.version + "';'osVersion'='" + Environment.OSVersion.ToString() + "';'.NET'='" + System.Environment.Version + "';'isAdmin'='"+ isAdmin + "';'builtWithBuildTool'='" + builtWithBuildTool.ToString() +"';'debugRights'='" + debugProc + "';'arch'='" + arch + "'}"; attackState.cmd = debugCmd; Processing.PSExec(attackState); // print intro Console.ForegroundColor = PSColors.introText; Console.WriteLine(Strings.welcomeMessage, Strings.version, buildString); // Display Prompt attackState.ClearLoop(); attackState.ClearIO(); Display.printPrompt(attackState); return attackState; }
// called when up or down is entered static AttackState history(AttackState attackState) { if (attackState.history.Count > 0) { if (attackState.loopType == null) { attackState.loopType = "history"; if (attackState.loopPos == 0) { attackState.loopPos = attackState.history.Count; } } if (attackState.keyInfo.Key == ConsoleKey.UpArrow && attackState.loopPos > 0) { attackState.loopPos -= 1; attackState.displayCmd = attackState.history[attackState.loopPos]; } if (attackState.keyInfo.Key == ConsoleKey.DownArrow) { if ((attackState.loopPos + 1) > (attackState.history.Count - 1)) { attackState.displayCmd = ""; } else { attackState.loopPos += 1; attackState.displayCmd = attackState.history[attackState.loopPos]; } } attackState.cursorPos = attackState.endOfDisplayCmdPos(); } return attackState; }
// This is called everytime a key is pressed. public static AttackState CommandProcessor(AttackState attackState) { attackState.output = null; int relativePos = attackState.relativeCursorPos(); int cmdLength = attackState.displayCmd.Length; ///////////////////////// // BACKSPACE OR DELETE // ///////////////////////// if (attackState.keyInfo.Key == ConsoleKey.Backspace || attackState.keyInfo.Key == ConsoleKey.Delete) { attackState.ClearLoop(); if (attackState.displayCmd != "" && attackState.relativeCursorPos() > 0) { if (attackState.keyInfo.Key == ConsoleKey.Backspace) { attackState.cursorPos -= 1; } List<char> displayCmd = attackState.displayCmd.ToList(); int relativeCursorPos = attackState.relativeCmdCursorPos(); displayCmd.RemoveAt(relativeCursorPos); attackState.displayCmd = new string(displayCmd.ToArray()); } } ///////////////////////// // BACKSPACE OR DELETE // ///////////////////////// else if (attackState.keyInfo.Key == ConsoleKey.Home || attackState.keyInfo.Key == ConsoleKey.End) { if (attackState.keyInfo.Key == ConsoleKey.Home) { attackState.cursorPos = attackState.promptLength; } else { attackState.cursorPos = attackState.promptLength + attackState.displayCmd.Length; } } //////////////// // UP OR DOWN // //////////////// else if (attackState.keyInfo.Key == ConsoleKey.UpArrow || attackState.keyInfo.Key == ConsoleKey.DownArrow) { return history(attackState); } /////////////////// // LEFT OR RIGHT // /////////////////// // TODO: Fix arrows navigating between wrapped command lines else if (attackState.keyInfo.Key == ConsoleKey.LeftArrow) { if (attackState.relativeCmdCursorPos() > 0) { attackState.cursorPos -= 1; } return attackState; } else if (attackState.keyInfo.Key == ConsoleKey.RightArrow) { if (attackState.relativeCmdCursorPos() < attackState.displayCmd.Length) { attackState.cursorPos += 1; } return attackState; } /////////// // ENTER // /////////// else if (attackState.keyInfo.Key == ConsoleKey.Enter) { Console.WriteLine("\n"); attackState.ClearLoop(); attackState.cmd = attackState.displayCmd; // don't add blank lines to history if (attackState.cmd != "") { attackState.history.Add(attackState.cmd); } if (attackState.cmd == "exit") { System.Environment.Exit(0); } else if (attackState.cmd == "clear") { Console.Clear(); attackState.displayCmd = ""; Display.printPrompt(attackState); } // TODO: Make this better. else if (attackState.cmd.Contains(".exe")) { attackState.cmd = "Start-Process -NoNewWindow -Wait " + attackState.cmd; attackState = Processing.PSExec(attackState); Display.Output(attackState); } // assume that we just want to execute whatever makes it here. else { attackState = Processing.PSExec(attackState); attackState.displayCmd = ""; Display.Output(attackState); } // clear out cmd related stuff from state attackState.ClearIO(display:true); } ///////// // TAB // ///////// else if (attackState.keyInfo.Key == ConsoleKey.Tab) { return TabExpansion.Process(attackState); } ////////// // if nothing matched, lets assume its a character and add it to displayCmd ////////// else { attackState.ClearLoop(); // figure out where to insert the typed character List<char> displayCmd = attackState.displayCmd.ToList(); int relativeCmdCursorPos = attackState.relativeCmdCursorPos(); int cmdInsertPos = attackState.cursorPos - attackState.promptLength; displayCmd.Insert(attackState.cursorPos - attackState.promptLength, attackState.keyInfo.KeyChar); attackState.displayCmd = new string(displayCmd.ToArray()); attackState.cursorPos += 1; } return attackState; }
// Here is where we execute posh code public static AttackState PSExec(AttackState attackState) { using (Pipeline pipeline = attackState.runspace.CreatePipeline()) { pipeline.Commands.AddScript(attackState.cmd); // If we're in an auto-complete loop, we want the PSObjects, not the string from the output of the command // TODO: clean this up if (attackState.loopType != null) { pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } else { pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); pipeline.Commands.Add("out-default"); } try { attackState.results = pipeline.Invoke(); } catch (Exception e) { attackState.results = null; Display.Exception(attackState, e.Message); } pipeline.Dispose(); } //Clear out command so it doesn't get echo'd out to console again. attackState.ClearIO(); if (attackState.loopType == null) { attackState.cmdComplete = true; } return attackState; }
// COMMAND AUTOCOMPLETE static AttackState cmdAutoComplete(AttackState attackState) { attackState.cmd = "Get-Command " + attackState.autocompleteSeed + "*"; attackState = Processing.PSExec(attackState); return(attackState); }
// This is called everytime a key is pressed. public static AttackState CommandProcessor(AttackState attackState) { attackState.output = null; int relativePos = attackState.relativeCursorPos(); int cmdLength = attackState.displayCmd.Length; ///////////////////////// // BACKSPACE OR DELETE // ///////////////////////// if (attackState.keyInfo.Key == ConsoleKey.Backspace || attackState.keyInfo.Key == ConsoleKey.Delete) { attackState.ClearLoop(); if (attackState.displayCmd != "" && attackState.relativeCursorPos() > 0) { if (attackState.keyInfo.Key == ConsoleKey.Backspace) { attackState.cursorPos -= 1; } List <char> displayCmd = attackState.displayCmd.ToList(); int relativeCursorPos = attackState.relativeCmdCursorPos(); displayCmd.RemoveAt(relativeCursorPos); attackState.displayCmd = new string(displayCmd.ToArray()); } } ///////////////////////// // BACKSPACE OR DELETE // ///////////////////////// else if (attackState.keyInfo.Key == ConsoleKey.Home || attackState.keyInfo.Key == ConsoleKey.End) { if (attackState.keyInfo.Key == ConsoleKey.Home) { attackState.cursorPos = attackState.promptLength; } else { attackState.cursorPos = attackState.promptLength + attackState.displayCmd.Length; } } //////////////// // UP OR DOWN // //////////////// else if (attackState.keyInfo.Key == ConsoleKey.UpArrow || attackState.keyInfo.Key == ConsoleKey.DownArrow) { return(history(attackState)); } /////////////////// // LEFT OR RIGHT // /////////////////// // TODO: Fix arrows navigating between wrapped command lines else if (attackState.keyInfo.Key == ConsoleKey.LeftArrow) { if (attackState.relativeCmdCursorPos() > 0) { attackState.ClearLoop(); attackState.cursorPos -= 1; } return(attackState); } else if (attackState.keyInfo.Key == ConsoleKey.RightArrow) { if (attackState.relativeCmdCursorPos() < attackState.displayCmd.Length) { attackState.ClearLoop(); attackState.cursorPos += 1; } return(attackState); } /////////// // ENTER // /////////// else if (attackState.keyInfo.Key == ConsoleKey.Enter) { Console.WriteLine(); attackState.ClearLoop(); attackState.cmd = attackState.displayCmd; // don't add blank lines to history if (attackState.cmd != "") { attackState.history.Add(attackState.cmd); } if (attackState.cmd == "exit") { System.Environment.Exit(0); } else if (attackState.cmd == "clear") { Console.Clear(); attackState.displayCmd = ""; Display.printPrompt(attackState); } // TODO: Make this better. //else if (attackState.cmd.Contains(".exe")) //{ // attackState.cmd = "Start-Process -NoNewWindow -Wait " + attackState.cmd; // attackState = Processing.PSExec(attackState); // Display.Output(attackState); //} // assume that we just want to execute whatever makes it here. else { attackState = Processing.PSExec(attackState); attackState.displayCmd = ""; Display.Output(attackState); } // clear out cmd related stuff from state attackState.ClearIO(display: true); } ///////// // TAB // ///////// else if (attackState.keyInfo.Key == ConsoleKey.Tab) { return(TabExpansion.Process(attackState)); } ////////// // if nothing matched, lets assume its a character and add it to displayCmd ////////// else { attackState.ClearLoop(); // figure out where to insert the typed character List <char> displayCmd = attackState.displayCmd.ToList(); int relativeCmdCursorPos = attackState.relativeCmdCursorPos(); int cmdInsertPos = attackState.cursorPos - attackState.promptLength; displayCmd.Insert(attackState.cursorPos - attackState.promptLength, attackState.keyInfo.KeyChar); attackState.displayCmd = new string(displayCmd.ToArray()); attackState.cursorPos += 1; } return(attackState); }
// Here is where we execute posh code public static AttackState PSExec(AttackState attackState) { using (Pipeline pipeline = attackState.runspace.CreatePipeline()) { //Console.WriteLine("[*] puting cmd in pipeline"); pipeline.Commands.AddScript(attackState.cmd); // If we're in an auto-complete loop, we want the PSObjects, not the string from the output of the command // TODO: clean this up if ((attackState.loopType != null) || (!attackState.console)) { //Console.WriteLine("[*] Merging results 1"); pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } else { //Console.WriteLine("[*] Merging results 2"); pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); pipeline.Commands.Add("out-default"); pipeline.Commands.Add("Write-Host"); } //try //{ //Console.WriteLine("[*] trying to evoke pipeline"); if (attackState.console) { attackState.results = pipeline.Invoke(); } else { pipeline.InvokeAsync(); while (!pipeline.Output.EndOfPipeline) { pipeline.Output.WaitHandle.WaitOne(); while (pipeline.Output.Count > 0) { PSObject psObject = pipeline.Output.Read(); // Write output object data. Console.WriteLine(psObject.ToString()); Collection <PSObject> results = new Collection <PSObject>(); results.Add(psObject); attackState.results = results; } } } //} //catch (Exception e) //{ // Console.WriteLine("[!] Exeception.."); // attackState.results = null; // Display.Exception(attackState, e.Message); //} pipeline.Dispose(); } //Clear out command so it doesn't get echo'd out to console again. attackState.ClearIO(); if (attackState.loopType == null) { attackState.cmdComplete = true; } return(attackState); }