/// <summary> /// Helper method to launch a completely detached process. (.NET Process object is not working well in our case) /// </summary> /// <param name="executablePath">Path of the executable to launch</param> /// <param name="arguments">Arguments of the executable</param> /// <param name="processId">The process id returned if launch was successfull</param> public static bool LaunchProcess(string executablePath, string arguments, out IntPtr processHandle, out int processId) { //var startInfo = new ProcessStartInfo //{ // FileName = executablePath, // Arguments = arguments, // WorkingDirectory = Path.GetDirectoryName(executablePath), // CreateNoWindow = false, // UseShellExecute = false, //}; //var process = new Process { StartInfo = startInfo }; //return process.Start(); PROCESS_INFORMATION pInfo; var lpStartupInfo = new STARTUPINFOEX { StartupInfo = { dwFlags = 0x01 } }; // Flags to enable no new window for child-process lpStartupInfo.StartupInfo.cb = Marshal.SizeOf<STARTUPINFO>(); //lpStartupInfo.StartupInfo.wShowWindow var pSec = new SECURITY_ATTRIBUTES(); var tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); var result = CreateProcessW(executablePath, "\"" + executablePath + "\" " + arguments, ref pSec, ref tSec, false, CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW | DETACHED_PROCESS, IntPtr.Zero, Path.GetDirectoryName(executablePath), ref lpStartupInfo, out pInfo); processHandle = IntPtr.Zero; processId = 0; if (result) { processHandle = pInfo.hProcess; processId = pInfo.dwProcessId; } return result; }
private static PROCESS_INFORMATION RunProcess(ref STARTUPINFOEX sInfoEx, string commandLine) { int securityAttributeSize = Marshal.SizeOf <SECURITY_ATTRIBUTES>(); var pSec = new SECURITY_ATTRIBUTES { nLength = securityAttributeSize }; var tSec = new SECURITY_ATTRIBUTES { nLength = securityAttributeSize }; PROCESS_INFORMATION pInfo; var success = CreateProcess( lpApplicationName: null, lpCommandLine: commandLine, lpProcessAttributes: ref pSec, lpThreadAttributes: ref tSec, bInheritHandles: false, dwCreationFlags: EXTENDED_STARTUPINFO_PRESENT, lpEnvironment: IntPtr.Zero, lpCurrentDirectory: null, lpStartupInfo: ref sInfoEx, lpProcessInformation: out pInfo ); if (!success) { throw new InvalidOperationException("Could not create process. " + Marshal.GetLastWin32Error()); } return(pInfo); }
private static PROCESS_INFORMATION RunProcess(ref STARTUPINFOEX sInfoEx, string commandLine, string directory, string environment) { var lpEnvironment = Marshal.StringToHGlobalAnsi(environment); int securityAttributeSize = Marshal.SizeOf <SECURITY_ATTRIBUTES>(); var pSec = new SECURITY_ATTRIBUTES { nLength = securityAttributeSize }; var tSec = new SECURITY_ATTRIBUTES { nLength = securityAttributeSize }; var success = CreateProcess( lpApplicationName: null, lpCommandLine: commandLine, lpProcessAttributes: ref pSec, lpThreadAttributes: ref tSec, bInheritHandles: false, dwCreationFlags: EXTENDED_STARTUPINFO_PRESENT, lpEnvironment: lpEnvironment, lpCurrentDirectory: directory, lpStartupInfo: ref sInfoEx, lpProcessInformation: out PROCESS_INFORMATION pInfo ); if (!success) { var errorCode = Marshal.GetLastWin32Error(); Logger.Instance.Error("RunProcess: Could not create Process. Win32 Error: {@errorCode}", errorCode); Marshal.FreeHGlobal(lpEnvironment); throw new Win32Exception(errorCode, "Could not create process."); } Marshal.FreeHGlobal(lpEnvironment); return(pInfo); }
private static PROCESS_INFORMATION CreateChildProcessWithPseudoConsole(IntPtr handlePseudoConsole, string commandLine) { STARTUPINFOEX startupInfo = ConfigureProcessThread(handlePseudoConsole, (IntPtr)PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE); PROCESS_INFORMATION processInfo = RunProcess(ref startupInfo, commandLine); return(processInfo); }
private static STARTUPINFOEX ConfigureProcessThread(IntPtr handlePseudoConsole, IntPtr attributes) { IntPtr lpSize = IntPtr.Zero; bool success = InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); if (success || lpSize == IntPtr.Zero) { throw new ConPtyShellException("Could not calculate the number of bytes for the attribute list. " + Marshal.GetLastWin32Error()); } STARTUPINFOEX startupInfo = new STARTUPINFOEX(); startupInfo.StartupInfo.cb = Marshal.SizeOf(startupInfo); startupInfo.lpAttributeList = Marshal.AllocHGlobal(lpSize); success = InitializeProcThreadAttributeList(startupInfo.lpAttributeList, 1, 0, ref lpSize); if (!success) { throw new ConPtyShellException("Could not set up attribute list. " + Marshal.GetLastWin32Error()); } success = UpdateProcThreadAttribute(startupInfo.lpAttributeList, 0, attributes, handlePseudoConsole, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); if (!success) { throw new ConPtyShellException("Could not set pseudoconsole thread attribute. " + Marshal.GetLastWin32Error()); } return(startupInfo); }
public PROCESS_INFORMATION ParentSpoofing(int parentID, string childPath) { // https://stackoverflow.com/questions/10554913/how-to-call-createprocess-with-startupinfoex-from-c-sharp-and-re-parent-the-ch const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; const int STARTF_USESTDHANDLES = 0x00000100; const int STARTF_USESHOWWINDOW = 0x00000001; const ushort SW_HIDE = 0x0000; const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000; const uint CREATE_NO_WINDOW = 0x08000000; const uint CreateSuspended = 0x00000004; var pInfo = new PROCESS_INFORMATION(); var siEx = new STARTUPINFOEX(); IntPtr lpValueProc = IntPtr.Zero; IntPtr hSourceProcessHandle = IntPtr.Zero; var lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = OpenProcess((uint)ProcessAccessRights.CreateProcess | (uint)ProcessAccessRights.DuplicateHandle, false, (uint)parentID); Console.WriteLine($"[+] Handle {parentHandle} opened for parent process id."); lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, parentHandle); UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); Console.WriteLine($"[+] Adding attributes to a list."); siEx.StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; siEx.StartupInfo.wShowWindow = SW_HIDE; var ps = new SECURITY_ATTRIBUTES(); var ts = new SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); try { bool ProcCreate = CreateProcess(childPath, null, ref ps, ref ts, true, CreateSuspended | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, IntPtr.Zero, null, ref siEx, out pInfo); if (!ProcCreate) { Console.WriteLine($"[+] Proccess failed to execute!"); } Console.WriteLine($"[+] New process with ID: {pInfo.dwProcessId} created in a suspended stated under the defined parent process."); } catch (Exception ex) { Console.WriteLine("[+] " + Marshal.GetExceptionCode()); Console.WriteLine(ex.Message); } return(pInfo); }
private static STARTUPINFOEX ConfigureProcessThread(IntPtr hPC, IntPtr attributes) { Covenant.Requires <ArgumentNullException>(hPC != IntPtr.Zero, nameof(hPC)); Covenant.Requires <ArgumentNullException>(attributes != IntPtr.Zero, nameof(attributes)); // This method implements the behavior described here: // // https://docs.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session#preparing-for-creation-of-the-child-process var lpSize = IntPtr.Zero; var success = InitializeProcThreadAttributeList( lpAttributeList: IntPtr.Zero, dwAttributeCount: 1, dwFlags: 0, lpSize: ref lpSize ); if (success || lpSize == IntPtr.Zero) // We're not expecting success here, we just want to get the calculated [lpSize]. { throw new InvalidOperationException("Could not calculate the number of bytes for the attribute list. " + Marshal.GetLastWin32Error()); } var startupInfo = new STARTUPINFOEX(); startupInfo.StartupInfo.cb = Marshal.SizeOf <STARTUPINFOEX>(); startupInfo.lpAttributeList = Marshal.AllocHGlobal(lpSize); success = InitializeProcThreadAttributeList( lpAttributeList: startupInfo.lpAttributeList, dwAttributeCount: 1, dwFlags: 0, lpSize: ref lpSize ); if (!success) { throw new InvalidOperationException("Could not set up attribute list. " + Marshal.GetLastWin32Error()); } success = UpdateProcThreadAttribute( lpAttributeList: startupInfo.lpAttributeList, dwFlags: 0, attribute: attributes, lpValue: hPC, cbSize: (IntPtr)IntPtr.Size, lpPreviousValue: IntPtr.Zero, lpReturnSize: IntPtr.Zero ); if (!success) { throw new InvalidOperationException("Could not set pseudoconsole thread attribute. " + Marshal.GetLastWin32Error()); } return(startupInfo); }
static extern bool CreateProcessWithTokenW( SafeKernelObjectHandle hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
internal static extern bool CreateProcess( string?lpApplicationName, string lpCommandLine, // LPTSTR - note: CreateProcess might insert a null somewhere in this string SECURITY_ATTRIBUTES?lpProcessAttributes, // LPSECURITY_ATTRIBUTES SECURITY_ATTRIBUTES?lpThreadAttributes, // LPSECURITY_ATTRIBUTES bool bInheritHandles, // BOOL int dwCreationFlags, // DWORD IntPtr lpEnvironment, // LPVOID string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo, // LPSTARTUPINFO out PROCESS_INFORMATION lpProcessInformation); // LPPROCESS_INFORMATION
private static STARTUPINFOEX ConfigureProcessThread(IntPtr hPC, IntPtr attributes) { // this method implements the behavior described in https://docs.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session#preparing-for-creation-of-the-child-process var lpSize = IntPtr.Zero; var success = InitializeProcThreadAttributeList( lpAttributeList: IntPtr.Zero, dwAttributeCount: 1, dwFlags: 0, lpSize: ref lpSize ); if (success || lpSize == IntPtr.Zero) // we're not expecting `success` here, we just want to get the calculated lpSize { throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not calculate the number of bytes for the attribute list."); } var startupInfo = new STARTUPINFOEX(); const int STARTF_USESTDHANDLES = 0x0000_0100; startupInfo.StartupInfo.dwFlags = STARTF_USESTDHANDLES; startupInfo.StartupInfo.hStdOutput = IntPtr.Zero; startupInfo.StartupInfo.hStdInput = IntPtr.Zero; startupInfo.StartupInfo.hStdError = IntPtr.Zero; startupInfo.StartupInfo.cb = Marshal.SizeOf <STARTUPINFOEX>(); startupInfo.lpAttributeList = Marshal.AllocHGlobal(lpSize); success = InitializeProcThreadAttributeList( lpAttributeList: startupInfo.lpAttributeList, dwAttributeCount: 1, dwFlags: 0, lpSize: ref lpSize ); if (!success) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not set up attribute list."); } success = UpdateProcThreadAttribute( lpAttributeList: startupInfo.lpAttributeList, dwFlags: 0, attribute: attributes, lpValue: hPC, cbSize: (IntPtr)IntPtr.Size, lpPreviousValue: IntPtr.Zero, lpReturnSize: IntPtr.Zero ); if (!success) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not set pseudoconsole thread attribute."); } return(startupInfo); }
static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
internal static extern unsafe bool CreateProcess( [In] string lpApplicationName, [In] StringBuilder lpCommandLine, [In] IntPtr procSecAttrs, [In] IntPtr threadSecAttrs, [In] bool bInheritHandles, [In] int dwCreationFlags, [In] char *lpEnvironment, [In] string lpCurrentDirectory, [In][Out] ref STARTUPINFOEX lpStartupInfo, [Out] out PROCESS_INFORMATION lpProcessInformation);
internal static extern bool CreateProcess( string lpApplicationName, StringBuilder lpCommandLine, ref SECURITY_ATTRIBUTES procSecAttrs, ref SECURITY_ATTRIBUTES threadSecAttrs, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation );
public NativePty(ExecutionProfile executionProfile, TerminalSize size) { SafeFileHandle stdin; SafeFileHandle stdout; CreatePipe(out stdin, out _writeHandle, IntPtr.Zero, 0); CreatePipe(out _readHandle, out stdout, IntPtr.Zero, 0); W32Throw(CreatePseudoConsole(new COORD { X = (short)size.Columns, Y = (short)size.Rows }, stdin, stdout, 0, out this._ptyHandle)); var allocSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref allocSize); if (allocSize == IntPtr.Zero) { W32Throw(0, "allocation granularity whatever."); } var startupInfo = new STARTUPINFOEX { StartupInfo = { cb = Marshal.SizeOf <STARTUPINFOEX>() }, lpAttributeList = Marshal.AllocHGlobal(allocSize) }; W32Throw(InitializeProcThreadAttributeList(startupInfo.lpAttributeList, 1, 0, ref allocSize)); W32Throw(UpdateProcThreadAttribute(startupInfo.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, _ptyHandle, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero)); var processSecurityAttr = new SECURITY_ATTRIBUTES(); var threadSecurityAttr = new SECURITY_ATTRIBUTES(); processSecurityAttr.nLength = threadSecurityAttr.nLength = Marshal.SizeOf <SECURITY_ATTRIBUTES>(); var args = executionProfile.Arguments ?? Array.Empty <string>(); var cmdline = executionProfile.EscapeArguments ? string.Join(" ", args.Select(x => $"\"{x}\"")) : string.Join(" ", args); W32Throw(CreateProcess(executionProfile.Command, cmdline, ref processSecurityAttr, ref threadSecurityAttr, false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref startupInfo, out var processInfo)); DeleteProcThreadAttributeList(startupInfo.lpAttributeList); Marshal.FreeHGlobal(startupInfo.lpAttributeList); StandardOutput = new FileStream(_readHandle, FileAccess.Read); StandardInput = new FileStream(_writeHandle, FileAccess.Write); }
private static PROCESS_INFORMATION CreateProcess(string command, string parameters, string workingDir, string pathExtension, SafePipeHandle outputPipeWritingEnd) { var startupinfoex = new STARTUPINFOEX { StartupInfo = new STARTUPINFO { hStdOutput = outputPipeWritingEnd, hStdError = outputPipeWritingEnd, dwFlags = STARTF_USESTDHANDLES, cb = Marshal.SizeOf(typeof(STARTUPINFOEX)), } }; string commandLine = command; if (!string.IsNullOrEmpty(parameters)) { commandLine += $" {parameters}"; } if (string.IsNullOrEmpty(workingDir)) { workingDir = null; } PROCESS_INFORMATION processInfo; // ReSharper disable ArgumentsStyleNamedExpression // ReSharper disable ArgumentsStyleLiteral // ReSharper disable ArgumentsStyleOther if (!CreateProcess( lpApplicationName: null, lpCommandLine: commandLine, lpProcessAttributes: null, lpThreadAttributes: null, bInheritHandles: true, dwCreationFlags: CREATE_EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED, lpEnvironment: CreateEnvironment(pathExtension), lpCurrentDirectory: workingDir, lpStartupInfo: startupinfoex, lpProcessInformation: out processInfo)) { throw new Win32Exception(Marshal.GetLastWin32Error(), $"Could not create process. Command: '{command}', parameters: '{parameters}', working dir: '{workingDir}'"); } // ReSharper restore ArgumentsStyleNamedExpression // ReSharper restore ArgumentsStyleLiteral // ReSharper restore ArgumentsStyleOther return(processInfo); }
public bool execute(uint ppid, string spawnto) { try { uint processSessionId = 0; uint parentSessionId = 0; uint currentPid = Kernel32.GetCurrentProcessId(); bool result1 = Kernel32.ProcessIdToSessionId(currentPid, out processSessionId); bool result2 = Kernel32.ProcessIdToSessionId(ppid, out parentSessionId); STARTUPINFO sInfo = new STARTUPINFO(); STARTUPINFOEX sInfoEx = new STARTUPINFOEX(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); SECURITY_ATTRIBUTES secAttr = new SECURITY_ATTRIBUTES(); secAttr.nLength = Marshal.SizeOf(secAttr); sInfo.cb = (uint)Marshal.SizeOf(sInfoEx); IntPtr lpSize = IntPtr.Zero; sInfoEx.StartupInfo = sInfo; IntPtr hSpoofParent = Kernel32.OpenProcess(0x1fffff, false, (int)ppid); IntPtr lpValue = IntPtr.Zero; lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, hSpoofParent); string currentPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); result1 = Kernel32.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); result1 = Kernel32.InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize); result1 = Kernel32.UpdateProcThreadAttribute(sInfoEx.lpAttributeList, 0, (IntPtr)0x00020000, lpValue, IntPtr.Size, IntPtr.Zero, IntPtr.Zero); return(Kernel32.CreateProcess(spawnto, string.Empty, ref secAttr, ref secAttr, false, 0x00080010, IntPtr.Zero, currentPath, ref sInfoEx, out pInfo)); } catch (Exception ex) { return(false); } //incorrect injection to parent process //IntPtr loadLibAddress = Kernel32.GetProcAddress(Kernel32.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); //IntPtr lpBaseAddress = Kernel32.VirtualAllocEx(pInfo.hProcess, IntPtr.Zero, dllPath.Length, 0x00003000, MemoryProtection.ExecuteReadWrite); //IntPtr bytesLength = IntPtr.Zero; //result1 = Kernel32.WriteProcessMemory(pInfo.hProcess, lpBaseAddress, Encoding.ASCII.GetBytes(dllPath), dllPath.Length, out bytesLength); //IntPtr handle = Kernel32.CreateRemoteThread(pInfo.hProcess, IntPtr.Zero, 0, loadLibAddress, lpBaseAddress, 0, IntPtr.Zero); }
public static bool Run(int parentProcessId, string binaryPath) { // STARTUPINFOEX members const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; // STARTUPINFO members (dwFlags and wShowWindow) const int STARTF_USESTDHANDLES = 0x00000100; const int STARTF_USESHOWWINDOW = 0x00000001; const short SW_HIDE = 0x0000; // dwCreationFlags const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000; const uint CREATE_NO_WINDOW = 0x08000000; var pInfo = new PROCESS_INFORMATION(); var siEx = new STARTUPINFOEX(); //siEx.StartupInfo.cb = Marshal.SizeOf(siEx); IntPtr lpValueProc = IntPtr.Zero; IntPtr hSourceProcessHandle = IntPtr.Zero; var lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = OpenProcess(ProcessAccessFlags.CreateProcess | ProcessAccessFlags.DuplicateHandle, false, parentProcessId); lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, parentHandle); UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); siEx.StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; siEx.StartupInfo.wShowWindow = SW_HIDE; var ps = new SECURITY_ATTRIBUTES(); var ts = new SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); bool ret = CreateProcess(binaryPath, null, ref ps, ref ts, true, EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, IntPtr.Zero, null, ref siEx, out pInfo); if (!ret) { Console.WriteLine("[!] Proccess failed to execute!"); return(false); } return(true); }
public PROCESS_INFORMATION ParentSpoofing(int parentID, string childPath) { var pInfo = new PROCESS_INFORMATION(); var siEx = new STARTUPINFOEX(); IntPtr lpValueProc = IntPtr.Zero; IntPtr hSourceProcessHandle = IntPtr.Zero; var lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = OpenProcess((uint)ProcessAccessRights.CreateProcess | (uint)ProcessAccessRights.DuplicateHandle, false, (uint)parentID); PrintInfo($"[!] Handle {parentHandle} opened for parent process id."); lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, parentHandle); UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); PrintInfo($"[!] Adding attributes to a list."); siEx.StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; siEx.StartupInfo.wShowWindow = SW_HIDE; var ps = new SECURITY_ATTRIBUTES(); var ts = new SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); try { bool ProcCreate = CreateProcess(childPath, null, ref ps, ref ts, true, CreateSuspended | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, IntPtr.Zero, null, ref siEx, out pInfo); if (!ProcCreate) { PrintError($"[-] Proccess failed to execute!"); } PrintInfo($"[!] New process with ID: {pInfo.dwProcessId} created in a suspended state under the defined parent process."); } catch (Exception ex) { PrintError("[-] " + Marshal.GetExceptionCode()); PrintError(ex.Message); } return(pInfo); }
private static void SetNewProcessParent(ref STARTUPINFOEX startupInfoEx, int parentProcessId) { const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; IntPtr handle = WinAPI.OpenProcess(ProcessAccessFlags.CreateProcess | ProcessAccessFlags.DuplicateHandle, false, parentProcessId); IntPtr lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, handle); bool success = UpdateProcThreadAttribute(startupInfoEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); if (!success) { throw new Exception(string.Format($"Error setting [{parentProcessId}] as the parent PID for the new process")); } }
private void StartCore() { if (!_attr.Sys.UseTty) { throw new Exception("Only a new process with controlled tty supported"); } _inputPipe = new Win32Pipe(); _outputPipe = new Win32Pipe(); var size = new COORD { X = DEFAULT_WIDTH, Y = DEFAULT_HEIGHT, }; var result = Kernel32.CreatePseudoConsole( size: size, hInput: _inputPipe.Read, hOutput: _outputPipe.Write, dwFlags: 0, phPC: out _ptyHandle ); if (result != 0) { throw new Win32Exception(result, "Could not create pseudo console."); } startupInfo = ConfigureProcessThread(_ptyHandle, (IntPtr)Kernel32.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE); processInfo = RunProcess(ref startupInfo, _fileName); if (_attr.RedirectStdin) { var inStream = new FileStream(_inputPipe.Write, FileAccess.Write); Stdin = new StreamWriter(inStream); } if (_attr.RedirectStdout) { var outStream = new FileStream(_outputPipe.Read, FileAccess.Read); Stdout = new StreamReader(outStream); } Pid = processInfo.dwProcessId; IsRunning = true; }
public static string InjectAPC(string[] arguments) { string targetProcess = arguments[2].Replace('+', ' '); byte[] buffer = DecGzip.DecompressGzipped(Convert.FromBase64String(arguments[1])); IntPtr lpNumberOfBytesWritten = IntPtr.Zero; IntPtr lpThreadId = IntPtr.Zero; uint oldProtect = 0; STARTUPINFOEX si = new STARTUPINFOEX(); flags.PROCESS_INFORMATION pi = new flags.PROCESS_INFORMATION(); var processSecurity = new flags.SECURITY_ATTRIBUTES(); var threadSecurity = new flags.SECURITY_ATTRIBUTES(); processSecurity.nLength = Marshal.SizeOf(processSecurity); threadSecurity.nLength = Marshal.SizeOf(threadSecurity); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr pinnedBuffer = handle.AddrOfPinnedObject(); try { bool success = Interop.CreateProcess(targetProcess, null, ref processSecurity, ref threadSecurity, false, flags.ProcessCreationFlags.EXTENDED_STARTUPINFO_PRESENT | flags.ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi); IntPtr resultPtr = Interop.VirtualAllocEx(pi.hProcess, IntPtr.Zero, buffer.Length, MEM_COMMIT, PAGE_READWRITE); IntPtr bytesWritten = IntPtr.Zero; bool resultBool = Interop.WriteProcessMemory(pi.hProcess, resultPtr, pinnedBuffer, buffer.Length, out bytesWritten); IntPtr sht = Interop.OpenThread(flags.ThreadAccess.SET_CONTEXT, false, (int)pi.dwThreadId); resultBool = Interop.VirtualProtectEx(pi.hProcess, resultPtr, buffer.Length, PAGE_EXECUTE_READ, out oldProtect); IntPtr ptr = Interop.QueueUserAPC(resultPtr, sht, IntPtr.Zero); IntPtr ThreadHandle = pi.hThread; Interop.ResumeThread(ThreadHandle); handle.Free(); } catch (Exception ex) { handle.Free(); Console.WriteLine(ex.Message); } return(null); }
private static PROCESS_INFORMATION RunProcess(ref STARTUPINFOEX sInfoEx, string commandLine) { PROCESS_INFORMATION pInfo; var pSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); var tSec = new SECURITY_ATTRIBUTES(); tSec.nLength = Marshal.SizeOf(tSec); var result = CreateProcess(null, commandLine, ref pSec, ref tSec, false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref sInfoEx, out pInfo); if (!result) { throw new InvalidOperationException("Could not create process. " + Marshal.GetLastWin32Error()); } return(pInfo); }
private static PROCESS_INFORMATION RunProcess(ref STARTUPINFOEX sInfoEx, string commandLine) { PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); int securityAttributeSize = Marshal.SizeOf <SECURITY_ATTRIBUTES>(); SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES { nLength = securityAttributeSize }; SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES { nLength = securityAttributeSize }; bool success = CreateProcess(null, commandLine, ref pSec, ref tSec, false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref sInfoEx, out pInfo); if (!success) { throw new InvalidOperationException("Could not create process. " + Marshal.GetLastWin32Error()); } return(pInfo); }
/// <summary> /// 模拟父进程打开进程 /// </summary> /// <param name="parentProcessId">父进程id</param> /// <param name="binaryPath">子程序路径</param> /// <param name="commandLine">调用传递参数</param> /// <returns>成功后返回子进程id,失败返回0</returns> public static int Run(int parentProcessId, string binaryPath, string commandLine = null) { // STARTUPINFOEX members const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; // dwCreationFlags const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000; const uint CREATE_NEW_CONSOLE = 0x00000010; var pInfo = new PROCESS_INFORMATION(); var siEx = new STARTUPINFOEX(); //siEx.StartupInfo.cb = Marshal.SizeOf(siEx); var lpSize = IntPtr.Zero; Win32Helper.InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); Win32Helper.InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = Win32Helper.OpenProcess(ProcessAccessFlags.CreateProcess | ProcessAccessFlags.DuplicateHandle, false, parentProcessId); var lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValueProc, parentHandle); Win32Helper.UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); var ps = new SECURITY_ATTRIBUTES(); var ts = new SECURITY_ATTRIBUTES(); ps.nLength = Marshal.SizeOf(ps); ts.nLength = Marshal.SizeOf(ts); bool ret = Win32Helper.CreateProcess(binaryPath, commandLine, ref ps, ref ts, true, EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_CONSOLE, IntPtr.Zero, null, ref siEx, out pInfo); if (ret) { return(pInfo.dwProcessId); } return(0); //var stringPid = pInfo.dwProcessId.ToString(); }
public static Win32Process CreateProcessAsUser(NtToken token, string application_name, string command_line, CreateProcessFlags flags, string desktop) { STARTUPINFOEX start_info = new STARTUPINFOEX(); start_info.StartupInfo.lpDesktop = desktop; PROCESS_INFORMATION proc_info = new PROCESS_INFORMATION(); if (!CreateProcessAsUser(token.Handle, application_name, command_line, IntPtr.Zero, IntPtr.Zero, false, flags, IntPtr.Zero, null, ref start_info, out proc_info)) { if (!CreateProcessWithTokenW(token.Handle, 0, application_name, command_line, flags, IntPtr.Zero, null, ref start_info, out proc_info)) { throw new SafeWin32Exception(); } } return(new Win32Process(proc_info)); }
public PROCESS_INFORMATION StartProcess(string targetProcess, int parentProcessId) { STARTUPINFOEX sInfoEx = new STARTUPINFOEX(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); sInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(sInfoEx); IntPtr lpValue = IntPtr.Zero; try { SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); uint flags = CreateSuspended | DetachedProcess | CreateNoWindow | EXTENDED_STARTUPINFO_PRESENT; IntPtr lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = Process.GetProcessById(parentProcessId).Handle; lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, parentHandle); UpdateProcThreadAttribute(sInfoEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); if (!CreateProcess(targetProcess, null, ref pSec, ref tSec, false, flags, IntPtr.Zero, null, ref sInfoEx, out pInfo)) { throw new SystemException("[x] Failed to create process!"); } return(pInfo); } finally { DeleteProcThreadAttributeList(sInfoEx.lpAttributeList); Marshal.FreeHGlobal(sInfoEx.lpAttributeList); Marshal.FreeHGlobal(lpValue); } }
public static PROCESS_INFORMATION StartProcessWOPid(string targetProcess) { STARTUPINFOEX sInfoEx = new STARTUPINFOEX(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); sInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(sInfoEx); IntPtr lpValue = IntPtr.Zero; SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); CreationFlags flags = CreationFlags.CreateSuspended | CreationFlags.DetachedProcesds | CreationFlags.CreateNoWindow; CreateProcess(targetProcess, null, ref pSec, ref tSec, false, flags, IntPtr.Zero, null, ref sInfoEx, out pInfo); return(pInfo); }
public static PROCESS_INFORMATION StartProcess(string targetProcess, int parentProcessId, string fakeCmdLine = "") { STARTUPINFOEX sInfoEx = new STARTUPINFOEX(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); sInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(sInfoEx); IntPtr lpValue = IntPtr.Zero; try { SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); CreationFlags flags = CreationFlags.CreateSuspended | CreationFlags.DetachedProcesds | CreationFlags.CreateNoWindow | CreationFlags.ExtendedStartupInfoPresent; IntPtr lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = Process.GetProcessById(parentProcessId).Handle; lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, parentHandle); UpdateProcThreadAttribute(sInfoEx.lpAttributeList, 0, (IntPtr)ProcThreadAttributeParentProcess, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); CreateProcess(targetProcess, fakeCmdLine, ref pSec, ref tSec, false, flags, IntPtr.Zero, null, ref sInfoEx, out pInfo); return(pInfo); } finally { DeleteProcThreadAttributeList(sInfoEx.lpAttributeList); Marshal.FreeHGlobal(sInfoEx.lpAttributeList); Marshal.FreeHGlobal(lpValue); } }
public static bool FindExecutableOnPath(string executablePath) { try { PROCESS_INFORMATION pInfo; var lpStartupInfo = new STARTUPINFOEX(); lpStartupInfo.StartupInfo.cb = Marshal.SizeOf <STARTUPINFO>(); bool result = CreateProcessW(null, executablePath, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref lpStartupInfo, out pInfo); if (result) { var process = Process.GetProcessById(pInfo.dwProcessId); process.Kill(); return(true); } } catch (Exception) { return(false); } return(false); }
public PROCESS_INFORMATION StartProcessWOPid(string targetProcess) { STARTUPINFOEX sInfoEx = new STARTUPINFOEX(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); sInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(sInfoEx); IntPtr lpValue = IntPtr.Zero; SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); uint flags = CreateSuspended | DetachedProcess | CreateNoWindow; if (!CreateProcess(targetProcess, null, ref pSec, ref tSec, false, flags, IntPtr.Zero, null, ref sInfoEx, out pInfo)) { throw new SystemException("[x] Failed to create process!"); } return(pInfo); }
public static Win32Process CreateProcess(NtProcess parent, string application_name, string command_line, CreateProcessFlags flags, string desktop) { STARTUPINFOEX start_info = new STARTUPINFOEX(); start_info.StartupInfo.lpDesktop = desktop; PROCESS_INFORMATION proc_info = new PROCESS_INFORMATION(); using (SafeProcThreadAttributeListBuffer buffer = new SafeProcThreadAttributeListBuffer(1)) { using (var handle_buffer = parent.Handle.DangerousGetHandle().ToBuffer()) { buffer.AddAttribute(new IntPtr(0x00020000), handle_buffer); start_info.lpAttributeList = buffer.DangerousGetHandle(); if (!CreateProcess(application_name, command_line, IntPtr.Zero, IntPtr.Zero, false, flags, IntPtr.Zero, null, ref start_info, out proc_info)) { throw new SafeWin32Exception(); } return(new Win32Process(proc_info)); } } }
static extern bool CreateProcessAsUser( SafeKernelObjectHandle hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
public static Win32Process CreateProcess(NtProcess parent, string application_name, string command_line, CreateProcessFlags flags, string desktop) { STARTUPINFOEX start_info = new STARTUPINFOEX(); start_info.StartupInfo.lpDesktop = desktop; PROCESS_INFORMATION proc_info = new PROCESS_INFORMATION(); using (SafeProcThreadAttributeListBuffer attr_list = new SafeProcThreadAttributeListBuffer(1)) { using (var handle_buffer = parent.Handle.DangerousGetHandle().ToBuffer()) { attr_list.AddAttribute(new IntPtr(0x00020000), handle_buffer); start_info.lpAttributeList = attr_list.DangerousGetHandle(); if (!CreateProcess(application_name, command_line, IntPtr.Zero, IntPtr.Zero, false, flags | CreateProcessFlags.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, start_info, out proc_info)) { throw new SafeWin32Exception(); } return new Win32Process(proc_info); } } }
public static Win32Process CreateProcessAsUser(NtToken token, string application_name, string command_line, CreateProcessFlags flags, string desktop) { STARTUPINFOEX start_info = new STARTUPINFOEX(); start_info.StartupInfo.lpDesktop = desktop; PROCESS_INFORMATION proc_info = new PROCESS_INFORMATION(); if (!CreateProcessAsUser(token.Handle, application_name, command_line, IntPtr.Zero, IntPtr.Zero, false, flags, IntPtr.Zero, null, ref start_info, out proc_info)) { if (!CreateProcessWithTokenW(token.Handle, 0, application_name, command_line, flags, IntPtr.Zero, null, ref start_info, out proc_info)) { throw new SafeWin32Exception(); } } return new Win32Process(proc_info); }
public static bool FindExecutableOnPath(string executablePath) { try { PROCESS_INFORMATION pInfo; var lpStartupInfo = new STARTUPINFOEX(); lpStartupInfo.StartupInfo.cb = Marshal.SizeOf<STARTUPINFO>(); bool result = CreateProcessW(null, executablePath, IntPtr.Zero, IntPtr.Zero, false, ProcessCreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref lpStartupInfo, out pInfo); if (result) { var process = Process.GetProcessById(pInfo.dwProcessId); process.Kill(); return true; } } catch (Exception) { return false; } return false; }