public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, SECURITY_ATTRIBUTES lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, // IntPtr because it may point to unicode or ANSI characters, based on a flag. string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
public static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION lpProcessInformation );
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)); }
static extern bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
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); }
/// <summary> /// Create process with a token. /// </summary> /// <param name="token">The token to create the process with.</param> /// <param name="application_name">The path to the executable.</param> /// <param name="command_line">The process command line.</param> /// <param name="flags">Process creation flags.</param> /// <param name="desktop">The desktop name.</param> /// <returns>The created win32 process.</returns> public static Win32Process CreateProcessAsUser(NtToken token, string application_name, string command_line, CreateProcessFlags flags, string desktop) { Win32ProcessConfig config = new Win32ProcessConfig { ApplicationName = application_name, CommandLine = command_line, CreationFlags = flags, Desktop = desktop }; return(CreateProcessAsUser(token, config)); }
public static Win32Process CreateProcessWithLogin(string username, string domain, string password, CreateProcessLogonFlags logon_flags, string application_name, string command_line, CreateProcessFlags flags, string desktop) { Win32ProcessConfig config = new Win32ProcessConfig { ApplicationName = application_name, CommandLine = command_line, CreationFlags = flags, Desktop = desktop }; return(CreateProcessWithLogin(username, domain, password, logon_flags, config)); }
public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, [In][MarshalAs(UnmanagedType.LPStr)] StringBuilder lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
public static extern IntPtr CreateProcessA(String lpApplicationName, String lpCommandLine, SecurityAttributes lpProcessAttributes, SecurityAttributes lpThreadAttributes, Boolean bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, [In] StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation );
public static unsafe extern bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, [Friendly(FriendlyFlags.Optional | FriendlyFlags.In)] SECURITY_ATTRIBUTES* lpProcessAttributes, [Friendly(FriendlyFlags.Optional | FriendlyFlags.In)] SECURITY_ATTRIBUTES* lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, CreateProcessFlags dwCreationFlags, void* lpEnvironment, // pointer because it may point to unicode or ANSI characters, based on a flag. string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
static void Main(string[] args) { Win32Process new_process = null; try { CreateProcessFlags flags = CreateProcessFlags.None; bool parent_process = false; bool set_il = false; TokenIntegrityLevel il = 0; bool show_help = false; OptionSet opts = new OptionSet() { { "p", "Use parent technique to create the new process", v => parent_process = v != null }, { "j", "Try and break away from the current process job", v => flags |= v != null ? CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB : 0 }, { "c", "Create a new console for the process", v => flags |= v != null ? CreateProcessFlags.CREATE_NEW_CONSOLE : 0 }, { "s", "Create the process suspended", v => flags |= v != null ? CreateProcessFlags.CREATE_SUSPENDED : 0 }, { "i|il=", "Set the process IL level", v => { il = ParseIL(v); set_il = true; } }, { "h|help", "show this message and exit", v => show_help = v != null }, }; int pid; List <string> commands = opts.Parse(args); if (show_help || commands.Count < 2) { ShowHelp(opts); } if (!int.TryParse(commands[0], out pid)) { throw new ArgumentException("Couldn't parse PID value"); } if (!NtToken.EnableDebugPrivilege()) { Console.WriteLine("WARNING: Couldn't enable Debug privilege"); } using (NtProcess process = NtProcess.Open(pid, ProcessAccessRights.MaximumAllowed)) { if (parent_process) { new_process = Win32Process.CreateProcess(process, null, commands[1], set_il ? flags | CreateProcessFlags.CREATE_SUSPENDED : flags, null); if (set_il) { using (NtToken token = new_process.Process.OpenToken()) { token.SetIntegrityLevel(il); } if ((flags & CreateProcessFlags.CREATE_SUSPENDED) == 0) { new_process.Thread.Resume(); } } } else { using (NtToken token = process.OpenToken()) { using (NtToken target_token = token.DuplicateToken(TokenType.Primary, SecurityImpersonationLevel.Anonymous, TokenAccessRights.MaximumAllowed)) { if (set_il) { target_token.SetIntegrityLevel(il); } new_process = Win32Process.CreateProcessAsUser(target_token, null, commands[1], flags, null); } } } using (new_process) { Console.WriteLine("Created Process: PID: {0}, SID {1}", new_process.Pid, new_process.Process.SessionId); } } } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex.Message); if (new_process != null && new_process.Process != null) { try { new_process.Process.Terminate(NtStatus.STATUS_WAIT_1); } catch { } } } }
internal static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
public static PROCESS_INFORMATION CreateProcess(string applicationName, string commandLine, CreateProcessFlags flags) { bool retValue; STARTUPINFO sInfo = new STARTUPINFO(); SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); PROCESS_INFORMATION pInfo; retValue = NativeMethods.CreateProcess( lpApplicationName: applicationName, lpCommandLine: commandLine, lpProcessAttributes: ref pSec, lpThreadAttributes: ref tSec, bInheritHandles: false, dwCreationFlags: flags, lpEnvironment: IntPtr.Zero, lpCurrentDirectory: null, lpStartupInfo: ref sInfo, lpProcessInformation: out pInfo); 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 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 CreateProcess(NtProcess parent, string application_name, string command_line, CreateProcessFlags flags, string desktop) { ProcessCreateConfiguration config = new ProcessCreateConfiguration(); config.ParentProcess = parent; config.ApplicationName = application_name; config.CommandLine = command_line; config.CreationFlags = flags; config.Desktop = desktop; return(CreateProcess(config)); }
public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
private static extern bool CreateProcessAsUserW(IntPtr token, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
public static extern bool CreateProcessAsUserW(IntPtr token, [MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName, [MarshalAs(UnmanagedType.LPTStr)] string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, [In] StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
/// <summary> /// Calls <see cref="CreateProcessAsUserW"/> and safely stores the obtained handles. /// </summary> /// <param name="userToken">Token to impersonate the external process</param> /// <param name="createFlags">Flags used to create the external process</param> /// <param name="startupInfo">Startup information used to create the external process</param> /// <returns><c>true</c> if the call to <see cref="CreateProcessAsUserW"/> was successful; otherwise <c>false</c></returns> private bool SafeCreateProcessAsUserW(IntPtr userToken, CreateProcessFlags createFlags, StartupInfo startupInfo) { _processHandle = new SafeProcessHandle(); var threadHandle = new SafeThreadHandle(); bool success; // The following is necessary to make sure that processInformation.hProcess and processInformation.hThread // are safely stored in the respective SafeHandle classes. It is, unfortunately, not possible to define // processInformation.hProcess and processInformation.hThread as SafeHandles and use processInformation // as an out parameter, because the unmanaged code is not able to create these objects. We therefore use // IntPtr and ensure in the following that the IntPtrs are stored in SafeHandle objects immediately after // they have been obtained. // For details see here: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions(v=vs.110).aspx RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { ProcessInformation processInformation; success = CreateProcessAsUserW(userToken, null, GetCommandLine(), IntPtr.Zero, IntPtr.Zero, true, createFlags, IntPtr.Zero, null, startupInfo, out processInformation); if (success) { _processHandle.InitialSetHandle(processInformation.hProcess); threadHandle.InitialSetHandle(processInformation.hThread); _processId = processInformation.dwProcessId; } } // We don't need the threadHandle and therefore immediately dispose it. threadHandle.Dispose(); if (success) return true; _processHandle.Dispose(); var error = Marshal.GetLastWin32Error(); _debugLogger.Error("AsyncImpersonationProcess ({0}): Cannot start process. ErrorCode: {1} ({2})", StartInfo.FileName, error, new Win32Exception(error).Message); return false; }
/// <summary> /// Create process. /// </summary> /// <param name="parent">Optional parent process.</param> /// <param name="application_name">The path to the executable.</param> /// <param name="command_line">The process command line.</param> /// <param name="flags">Process creation flags.</param> /// <param name="desktop">The desktop name.</param> /// <returns>The created win32 process.</returns> public static Win32Process CreateProcess(NtProcess parent, string application_name, string command_line, CreateProcessFlags flags, string desktop) { Win32ProcessConfig config = new Win32ProcessConfig { ParentProcess = parent, ApplicationName = application_name, CommandLine = command_line, CreationFlags = flags, Desktop = desktop }; return(CreateProcess(config)); }
public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr security, IntPtr thread, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
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);
public static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SecurityAttributes lpProcessAttributes, ref SecurityAttributes lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out ProcessInformation 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); } } }
// Main logic public static void SpawnTheThing(String Launch, String RealCmdLine, String FakeCmdLine = "") { // Invoke all the checks RUNTIME_CHECK RunTime = CheckAllTheThings(Launch); if (RunTime.PePathIsValid == false) { Console.WriteLine("[!] Invalid PE path specified.."); return; } if (RunTime.PeArch == 0) { Console.WriteLine("[!] Invalid PE image.."); return; } if (RunTime.SwampIs32 && RunTime.PeArch == 0x020b || !RunTime.SwampIs32 && RunTime.PeArch == 0x010b) { Console.WriteLine("[!] SwampThing and target PE architectures do not match.."); return; } // Create the target process SecurityAttributes SecAttrib = new SecurityAttributes(); SecurityAttributes tSec = new SecurityAttributes(); String CurrentDir = Directory.GetCurrentDirectory(); STARTUPINFOEX si = new STARTUPINFOEX(); //StartupInfo si = new StartupInfo(); ProcessInformation pi; // INSERT PPID SPOOF //SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); //SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); IntPtr lpValue = IntPtr.Zero; SecAttrib.Length = Marshal.SizeOf(SecAttrib); tSec.Length = Marshal.SizeOf(tSec); CreateProcessFlags flags = CreateProcessFlags.CREATE_SUSPENDED | CreateProcessFlags.DETACHED_PROCESS | CreateProcessFlags.CREATE_NO_WINDOW | CreateProcessFlags.EXTENDED_STARTUPINFO_PRESENT; IntPtr lpSize = IntPtr.Zero; InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); si.lpAttributeList = Marshal.AllocHGlobal(lpSize); InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, ref lpSize); IntPtr parentHandle = Process.GetProcessById(4560).Handle; lpValue = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(lpValue, parentHandle); const int ProcThreadAttributeParentProcess = 0x00020000; UpdateProcThreadAttribute(si.lpAttributeList, 0, (IntPtr)ProcThreadAttributeParentProcess, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); string targetProcess = @"C:\Windows\System32\cmd.exe"; CreateProcess(targetProcess, null, ref SecAttrib, ref tSec, false, flags, IntPtr.Zero, null, ref si, out pi); // END PPID SPPOF //bool bProc = CreateProcess(Launch, FakeCmdLine, SecAttrib, SecAttrib, false, flags, IntPtr.Zero, CurrentDir, si, out pi); /* * if (!bProc) * { * Console.WriteLine("[!] Process execution failed.."); * return; * } else * { * Console.WriteLine("[>] CreateProcess -> Suspended"); * } * */ // Get PBI PROCESS_BASIC_INFORMATION CallResult = PBI(pi.hProcess); if (CallResult.PebBaseAddress == IntPtr.Zero) { Console.WriteLine("[!] Failed to aquire PBI"); return; } else { if (RunTime.PeArch == 0x010b) { Console.WriteLine("[+] PE Arch : 32-bit"); } else { Console.WriteLine("[+] PE Arch : 64-bit"); } Console.WriteLine("[+] Process Id : " + CallResult.UniqueProcessId); Console.WriteLine("[+] PEB Base : 0x" + string.Format("{0:X}", (CallResult.PebBaseAddress).ToInt64())); } // Get PEB->(IntPtr)_RTL_USER_PROCESS_PARAMETERS->(UNICODE_STRING)CommandLine Int32 RTL_USER_PROCESS_PARAMETERS; Int32 CommandLine; Int32 ReadSize; if (RunTime.PeArch == 0x010b) { RTL_USER_PROCESS_PARAMETERS = 0x10; CommandLine = 0x40; ReadSize = 0x4; } else { RTL_USER_PROCESS_PARAMETERS = 0x20; CommandLine = 0x70; ReadSize = 0x8; } // We can't acquire a remote PEB lock so we sleep briefly System.Threading.Thread.Sleep(500); // 500ms // Read remote PEB offsets UInt64 ProcParams; IntPtr pProcParams = ReadRemoteMem(pi.hProcess, ((CallResult.PebBaseAddress).ToInt64() + RTL_USER_PROCESS_PARAMETERS), ReadSize); if (ReadSize == 0x4) { ProcParams = (UInt64)Marshal.ReadInt32(pProcParams); } else { ProcParams = (UInt64)Marshal.ReadInt64(pProcParams); } Console.WriteLine("[+] RTL_USER_PROCESS_PARAMETERS : 0x" + string.Format("{0:X}", ProcParams)); UInt64 CmdLineUnicodeStruct = ProcParams + (UInt64)CommandLine; Console.WriteLine("[+] CommandLine : 0x" + string.Format("{0:X}", CmdLineUnicodeStruct)); // Get current CommandLine -> UNICODE_STRING UNICODE_STRING CurrentCmdLineStruct = new UNICODE_STRING(); Int32 UniStructSize = Marshal.SizeOf(CurrentCmdLineStruct); IntPtr pCmdLineStruct = ReadRemoteMem(pi.hProcess, (Int64)CmdLineUnicodeStruct, UniStructSize); CurrentCmdLineStruct = (UNICODE_STRING)Marshal.PtrToStructure(pCmdLineStruct, typeof(UNICODE_STRING)); Console.WriteLine("[+] UNICODE_STRING |-> Len : " + CurrentCmdLineStruct.Length); Console.WriteLine(" |-> MaxLen : " + CurrentCmdLineStruct.MaximumLength); Console.WriteLine(" |-> pBuff : 0x" + string.Format("{0:X}", (UInt64)CurrentCmdLineStruct.Buffer)); // Create replacement CommandLine Console.WriteLine("\n[>] Rewrite -> RTL_USER_PROCESS_PARAMETERS"); // RTL_USER_PROCESS_PARAMETERS unicode string params String WinDir = Environment.GetEnvironmentVariable("windir"); IntPtr uSystemDir = EmitUnicodeString((WinDir + "\\System32")); IntPtr uLaunchPath = EmitUnicodeString(Launch); IntPtr uWindowName = EmitUnicodeString("SwampThing"); IntPtr uRealCmdLine = EmitUnicodeString(" " + RealCmdLine); // Create local RTL_USER_PROCESS_PARAMETERS IntPtr pProcessParams = IntPtr.Zero; uint RtlCreateSuccess = RtlCreateProcessParametersEx(ref pProcessParams, uLaunchPath, uSystemDir, uSystemDir, uRealCmdLine, IntPtr.Zero, uWindowName, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 1); if (RtlCreateSuccess != 0) { Console.WriteLine("[!] Failed to create process parameters"); return; } else { Console.WriteLine("[+] RtlCreateProcessParametersEx : 0x" + string.Format("{0:X}", (UInt64)pProcessParams)); } // Remote map RTL_USER_PROCESS_PARAMETERS Int32 iProcessParamsSize = Marshal.ReadInt32((IntPtr)((Int64)pProcessParams + 4)); IntPtr pRemoteProcessParams = AllocRemoteMem(pi.hProcess, iProcessParamsSize, pProcessParams); Boolean bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, pProcessParams, pProcessParams, iProcessParamsSize, AllocationProtect.PAGE_READWRITE); if (bRemoteWriteSuccess) { Console.WriteLine("[+] RemoteAlloc : 0x" + string.Format("{0:X}", (UInt64)pRemoteProcessParams)); Console.WriteLine("[+] Size : " + iProcessParamsSize); } else { Console.WriteLine("[!] Failed to allocate custom RTL_USER_PROCESS_PARAMETERS"); return; } // Rewrite the process parameters pointer IntPtr pRewriteProcessParams = Marshal.AllocHGlobal(ReadSize); if (ReadSize == 0x4) { Marshal.WriteInt32(pRewriteProcessParams, (Int32)pProcessParams); } else { Marshal.WriteInt64(pRewriteProcessParams, (Int64)pProcessParams); } bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, pRewriteProcessParams, (IntPtr)((CallResult.PebBaseAddress).ToInt64() + RTL_USER_PROCESS_PARAMETERS), ReadSize, AllocationProtect.PAGE_READWRITE); if (bRemoteWriteSuccess) { Console.WriteLine("[?] Success, sleeping 500ms.."); } else { Console.WriteLine("[!] Failed to rewrite PEB->pProcessParameters"); return; } // Resume process UInt32 ResumeProc = ResumeThread(pi.hThread); System.Threading.Thread.Sleep(500); // Finally we rewrite the commandline to the fake value Console.WriteLine("\n[>] Reverting RTL_USER_PROCESS_PARAMETERS"); IntPtr uFakeCmdLine = EmitUnicodeString(" " + FakeCmdLine); Console.WriteLine("[+] Local UNICODE_STRING : 0x" + string.Format("{0:X}", (UInt64)uFakeCmdLine)); // Copy unicode buffer to remote process IntPtr pRemoteCmdLine = AllocRemoteMem(pi.hProcess, (Marshal.ReadInt16((IntPtr)((UInt64)uFakeCmdLine + 2)))); // MaxLength if (ReadSize == 0x4) { bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, (IntPtr)(Marshal.ReadInt32((IntPtr)((UInt64)uFakeCmdLine + 4))), pRemoteCmdLine, (Marshal.ReadInt16(uFakeCmdLine)), AllocationProtect.PAGE_READWRITE); } else { bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, (IntPtr)(Marshal.ReadInt64((IntPtr)((UInt64)uFakeCmdLine + 8))), pRemoteCmdLine, (Marshal.ReadInt16(uFakeCmdLine)), AllocationProtect.PAGE_READWRITE); } Console.WriteLine("[+] Remote UNICODE_STRING.Buffer : 0x" + string.Format("{0:X}", (UInt64)pRemoteCmdLine)); // Recalculate new RTL_USER_PROCESS_PARAMETERS pProcParams = ReadRemoteMem(pi.hProcess, ((CallResult.PebBaseAddress).ToInt64() + RTL_USER_PROCESS_PARAMETERS), ReadSize); if (ReadSize == 0x4) { ProcParams = (UInt64)Marshal.ReadInt32(pProcParams); } else { ProcParams = (UInt64)Marshal.ReadInt64(pProcParams); } Console.WriteLine("[+] pRTL_USER_PROCESS_PARAMETERS : 0x" + string.Format("{0:X}", ProcParams)); // Rewrite RTL_USER_PROCESS_PARAMETERS->CommandLine => Length, MaxLength, Buffer bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, uFakeCmdLine, (IntPtr)(ProcParams + (UInt32)CommandLine), 2, AllocationProtect.PAGE_READWRITE); bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, (IntPtr)((UInt64)uFakeCmdLine + 2), (IntPtr)(ProcParams + (UInt32)CommandLine + 2), 2, AllocationProtect.PAGE_READWRITE); IntPtr pRemoteBuff = Marshal.AllocHGlobal(8); if (ReadSize == 0x4) { Marshal.WriteInt32(pRemoteBuff, (Int32)pRemoteCmdLine); bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, pRemoteBuff, (IntPtr)(ProcParams + (UInt32)CommandLine + 4), 4, AllocationProtect.PAGE_READWRITE); } else { Marshal.WriteInt64(pRemoteBuff, (Int64)pRemoteCmdLine); bRemoteWriteSuccess = WriteRemoteMem(pi.hProcess, pRemoteBuff, (IntPtr)(ProcParams + (UInt32)CommandLine + 8), 8, AllocationProtect.PAGE_READWRITE); } Console.WriteLine("[?] Success rewrote Len, MaxLen, Buffer.."); }
public static Win32Process CreateProcessAsUser(NtToken token, string application_name, string command_line, CreateProcessFlags flags, string desktop) { ProcessCreateConfiguration config = new ProcessCreateConfiguration(); config.ApplicationName = application_name; config.CommandLine = command_line; config.CreationFlags = flags; config.Desktop = desktop; return(CreateProcessAsUser(token, config)); }
public static Win32Process CreateProcessWithLogin(string username, string domain, string password, CreateProcessLogonFlags logon_flags, string application_name, string command_line, CreateProcessFlags flags, string desktop) { ProcessCreateConfiguration config = new ProcessCreateConfiguration(); config.ApplicationName = application_name; config.CommandLine = command_line; config.CreationFlags = flags; config.Desktop = desktop; return(CreateProcessWithLogin(username, domain, password, logon_flags, config)); }
public static Process CreateSaferProcess(String fileName, string arguments, SaferLevel saferLevel, IntegrityLevel integrityLevel, CreateProcessFlags flags = CreateProcessFlags.CREATE_NEW_CONSOLE) { IntPtr saferLevelHandle = IntPtr.Zero; //Create a SaferLevel handle to match what was requested if (!SaferCreateLevel(SaferLevelScope.User, saferLevel, SaferOpen.Open, out saferLevelHandle, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } try { //Generate the access token to use, based on the safer level handle. IntPtr hToken = IntPtr.Zero; if (!SaferComputeTokenFromLevel( saferLevelHandle, // SAFER Level handle IntPtr.Zero, // NULL is current thread token. out hToken, // Target token SaferTokenBehaviour.Default, // No flags IntPtr.Zero)) // Reserved { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Get the Integrity SID IntPtr pIntegritySid = GetIntegritySid(integrityLevel); // Construct a structure describing the token integrity level var TIL = new TOKEN_MANDATORY_LABEL(); TIL.Label.Attributes = SE_GROUP_INTEGRITY; TIL.Label.Sid = pIntegritySid; IntPtr pTIL = Marshal.AllocHGlobal(Marshal.SizeOf <TOKEN_MANDATORY_LABEL>()); Marshal.StructureToPtr(TIL, pTIL, false); // Modify the token if (!SetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTIL, (uint)Marshal.SizeOf <TOKEN_MANDATORY_LABEL>() + GetLengthSid(pIntegritySid))) { throw new Win32Exception(); } try { //Now that we have a security token, we can lauch the process //using the standard CreateProcessAsUser API STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = String.Empty; var processAttributes = new SECURITY_ATTRIBUTES(); var threadAttributes = new SECURITY_ATTRIBUTES(); // Spin up the new process //bool result = CreateProcessAsUser(hToken, fileName, arguments, bool result = CreateProcessAsUser(hToken, fileName, $"\"{fileName}\"{(arguments?.Length > 0 ? " " + arguments : "")}", ref processAttributes, ref threadAttributes, false, //inherit handles flags, IntPtr.Zero, //environment null, //current directory ref si, //startup info out PROCESS_INFORMATION pi); //process info if (!result) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (pi.hProcess != IntPtr.Zero) { CloseHandle(pi.hProcess); } if (pi.hThread != IntPtr.Zero) { CloseHandle(pi.hThread); } return(Process.GetProcessById(pi.dwProcessId)); } finally { if (hToken != IntPtr.Zero) { CloseHandle(hToken); } } } finally { SaferCloseLevel(saferLevelHandle); } }