public static int GetParentProcessId(int pid) { IntPtr hProcess = ProcessApi.OpenProcess(ProcessApi.PROCESS_QUERY_INFORMATION, true, (uint)pid); try { if (hProcess == IntPtr.Zero) { return(0); } var pbi = new NtDllApi.PROCESS_BASIC_INFORMATION(); int returnLength; if (NtDllApi.NativeMethods.NtQueryInformationProcess(hProcess, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength) != 0) { return(0); } return((int)pbi.InheritedFromUniqueProcessId); } finally { CloseHandle(hProcess); } }
public Task <int> Execute() { Native.ConsoleApi.FreeConsole(); if (!Native.ConsoleApi.AttachConsole(-1)) { Native.ConsoleApi.AllocConsole(); Logger.Instance.Log($"Failed to attach console.\r\n{new Win32Exception().ToString()}", LogLevel.Error); } var app = CommandToRun.First(); var args = string.Join(" ", CommandToRun.Skip(1).ToArray()); if (InputArguments.IntegrityLevel.HasValue && (int)InputArguments.IntegrityLevel != ProcessHelper.GetCurrentIntegrityLevel() && Environment.GetEnvironmentVariable("gsudoAttachRun") != "1") { Environment.SetEnvironmentVariable("gsudoAttachRun", "1"); // prevents infinite loop on machines with UAC disabled. var process = ProcessFactory.StartAttachedWithIntegrity( InputArguments.GetIntegrityLevel(), app, args, Directory.GetCurrentDirectory(), false, true); process.GetProcessWaitHandle().WaitOne(); if (ProcessApi.GetExitCodeProcess(process, out var exitCode)) { return(Task.FromResult(exitCode)); } } else { Helpers.ProcessFactory.StartAttached(app, args).WaitForExit(); } return(Task.FromResult(0)); }
public static TokenProvider OpenCurrentProcessToken(uint access = TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS) { IntPtr existingProcessToken; if (!ProcessApi.OpenProcessToken(Process.GetCurrentProcess().Handle, access // internal const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100; , out existingProcessToken)) { throw new Win32Exception(); } if (existingProcessToken == IntPtr.Zero) { throw new Win32Exception(); } return(new TokenProvider() { Token = new SafeTokenHandle(existingProcessToken) }); }
private static int RunWithoutService(string exeName, string args, ElevationRequest elevationRequest) { Logger.Instance.Log("Already running as the specified user/permission-level. Running in-process...", LogLevel.Debug); var sameIntegrity = (int)InputArguments.GetIntegrityLevel() == ProcessHelper.GetCurrentIntegrityLevel(); // No need to escalate. Run in-process if (!string.IsNullOrEmpty(elevationRequest.Prompt)) { Environment.SetEnvironmentVariable("PROMPT", Environment.ExpandEnvironmentVariables(elevationRequest.Prompt)); } if (sameIntegrity) { if (elevationRequest.NewWindow) { using (var process = ProcessFactory.StartDetached(exeName, args, Environment.CurrentDirectory, false)) { if (elevationRequest.Wait) { process.WaitForExit(); var exitCode = process.ExitCode; Logger.Instance.Log($"Process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info); return(exitCode); } return(0); } } else { using (Process process = ProcessFactory.StartAttached(exeName, args)) { process.WaitForExit(); var exitCode = process.ExitCode; Logger.Instance.Log($"Process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info); return(exitCode); } } } else // lower integrity { var p = ProcessFactory.StartAttachedWithIntegrity(InputArguments.GetIntegrityLevel(), exeName, args, elevationRequest.StartFolder, InputArguments.NewWindow, !InputArguments.NewWindow); if (p == null || p.IsInvalid) { return(Constants.GSUDO_ERROR_EXITCODE); } if (elevationRequest.Wait) { ProcessHelper.GetProcessWaitHandle(p.DangerousGetHandle()).WaitOne(); ProcessApi.GetExitCodeProcess(p, out var exitCode); Logger.Instance.Log($"Process exited with code {exitCode}", exitCode == 0 ? LogLevel.Debug : LogLevel.Info); return(exitCode); } return(0); } }
/// <summary> /// The function gets the integrity level of the current process. /// </summary> /// <returns> /// Returns the integrity level of the current process. It is usually one of /// these values: /// /// SECURITY_MANDATORY_UNTRUSTED_RID - means untrusted level /// SECURITY_MANDATORY_LOW_RID - means low integrity level. /// SECURITY_MANDATORY_MEDIUM_RID - means medium integrity level. /// SECURITY_MANDATORY_HIGH_RID - means high integrity level. /// SECURITY_MANDATORY_SYSTEM_RID - means system integrity level. /// /// </returns> /// <exception cref="System.ComponentModel.Win32Exception"> /// When any native Windows API call fails, the function throws a Win32Exception /// with the last error code. /// </exception> static internal int GetCurrentIntegrityLevel() { if (_cacheGetCurrentIntegrityLevelCache.HasValue) { return(_cacheGetCurrentIntegrityLevelCache.Value); } return(GetProcessIntegrityLevel(ProcessApi.GetCurrentProcess())); }
public void Start(CreateTerminalRequest request, TerminalsManager terminalsManager) { Id = request.Id; _terminalsManager = terminalsManager; var configHandle = IntPtr.Zero; var spawnConfigHandle = IntPtr.Zero; var errorHandle = IntPtr.Zero; try { configHandle = winpty_config_new(WINPTY_FLAG_COLOR_ESCAPES, out errorHandle); winpty_config_set_initial_size(configHandle, request.Size.Columns, request.Size.Rows); _handle = winpty_open(configHandle, out errorHandle); if (errorHandle != IntPtr.Zero) { throw new Exception(winpty_error_msg(errorHandle)); } string exe = request.Profile.Location; string args = $"\"{exe}\" {request.Profile.Arguments}"; string cwd = GetWorkingDirectory(request.Profile); spawnConfigHandle = winpty_spawn_config_new(WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN, exe, args, cwd, null, out errorHandle); if (errorHandle != IntPtr.Zero) { throw new Exception(winpty_error_msg(errorHandle)); } _stdin = CreatePipe(winpty_conin_name(_handle), PipeDirection.Out); _stdout = CreatePipe(winpty_conout_name(_handle), PipeDirection.In); if (!winpty_spawn(_handle, spawnConfigHandle, out IntPtr process, out IntPtr thread, out int procError, out errorHandle)) { throw new Exception($"Failed to start the shell process. Please check your shell settings.\nTried to start: {args}"); } var shellProcessId = ProcessApi.GetProcessId(process); _shellProcess = Process.GetProcessById(shellProcessId); _shellProcess.EnableRaisingEvents = true; _shellProcess.Exited += _shellProcess_Exited; ShellExecutableName = Path.GetFileNameWithoutExtension(exe); } finally { winpty_config_free(configHandle); winpty_spawn_config_free(spawnConfigHandle); winpty_error_free(errorHandle); } ListenToStdOut(); }
private void PrintConsoleProcessList() { var processIds = new uint[100]; var ownPid = ProcessApi.GetCurrentProcessId(); processIds = GetConsoleAttachedPids(processIds); const string unknown = "(Unknown)"; Console.WriteLine($"{"PID".PadLeft(9)} {"Integrity".PadRight(10)} {"UserName".PadRight(25)} {"Name"}"); foreach (var pid in processIds.Reverse()) { Process p = null; string name = unknown; string integrity = unknown; string username = unknown; try { p = Process.GetProcessById((int)pid); name = p.GetExeName(); try { var i = ProcessHelper.GetProcessIntegrityLevel(p.Handle); integrity = i.ToString(CultureInfo.InvariantCulture); if (Enum.IsDefined(typeof(IntegrityLevel), i)) { integrity = ((IntegrityLevel)i).ToString(); } } catch { } try { username = p.GetProcessUser() ?? unknown; } catch { } } catch { } Console.WriteLine($"{pid.ToString(CultureInfo.InvariantCulture).PadLeft(9)} {integrity.PadRight(10)} {username.PadRight(25)} {name}{((ownPid == pid) ? " (this gsudo status)" : null)}"); } }
private async Task <List <ProcessVariableRm> > GetProcessVariables(WorkflowPluginLinkContext context, List <string> variableNames) { List <ProcessVariableRm> allVariables = new List <ProcessVariableRm>(); int pageIndex = 0; int pageSize = 5; long totalCount = 0; do { // We need to be sure to load all the process variables in order to match all the required variables var pageVariables = await ProcessApi.ApiV1ProcessesProcessIdVariablesGetAsync(context.Process.Id, pageIndex ++ *pageSize, pageSize); allVariables.AddRange(pageVariables.Items); totalCount = pageVariables.ResultCount.TotalResultCount.Value; } while (allVariables.Count < totalCount); return(allVariables.Where(x => variableNames.Contains(x.VariableDefinition.Configuration.Name)).ToList()); }
public Task <int> GetResult() { try { _ = ProcessApi.ResumeThread(_processInformation.hThread); if (_elevationRequest.Wait) { _process.GetProcessWaitHandle().WaitOne(); if (ProcessApi.GetExitCodeProcess(_process, out int exitCode)) { return(Task.FromResult(exitCode)); } } return(Task.FromResult(0)); } finally { ConsoleApi.SetConsoleCtrlHandler(ConsoleHelper.IgnoreConsoleCancelKeyPress, false); } }
public static void ReplaceProcessToken(ElevationRequest elevationRequest) { SafeTokenHandle desiredToken; desiredToken = GetDesiredToken(elevationRequest); try { var tokenInfo = new NtDllApi.PROCESS_ACCESS_TOKEN(); tokenInfo.Token = desiredToken.DangerousGetHandle(); tokenInfo.Thread = IntPtr.Zero; TokenProvider .CreateFromSystemAccount() .EnablePrivilege(Privilege.SeAssignPrimaryTokenPrivilege, true) .Impersonate(() => { IntPtr hProcess = ProcessApi.OpenProcess(ProcessApi.PROCESS_SET_INFORMATION, true, (uint)elevationRequest.TargetProcessId); NtDllApi.PROCESS_INFORMATION_CLASS processInformationClass = NtDllApi.PROCESS_INFORMATION_CLASS.ProcessAccessToken; int res = NtDllApi.NativeMethods.NtSetInformationProcess(hProcess, processInformationClass, ref tokenInfo, Marshal.SizeOf <NtDllApi.PROCESS_ACCESS_TOKEN>()); Logger.Instance.Log($"NtSetInformationProcess returned {res}", LogLevel.Debug); if (res < 0) { throw new Win32Exception(); } ProcessApi.CloseHandle(hProcess); }); } finally { desiredToken?.Close(); } }
internal static SafeProcessHandle CreateProcessAsUserWithFlags(string lpApplicationName, string args, ProcessApi.CreateProcessFlags dwCreationFlags, out PROCESS_INFORMATION pInfo) { var sInfoEx = new ProcessApi.STARTUPINFOEX(); sInfoEx.StartupInfo.cb = Marshal.SizeOf(sInfoEx); IntPtr lpValue = IntPtr.Zero; var pSec = new ProcessApi.SECURITY_ATTRIBUTES(); var tSec = new ProcessApi.SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); var command = $"{lpApplicationName} {args}"; Logger.Instance.Log($"{nameof(CreateProcessAsUser)}: {lpApplicationName} {args}", LogLevel.Debug); if (!ProcessApi.CreateProcess(null, command, ref pSec, ref tSec, false, dwCreationFlags, IntPtr.Zero, null, ref sInfoEx, out pInfo)) { throw new Win32Exception((int)ConsoleApi.GetLastError()); } return(new SafeProcessHandle(pInfo.hProcess, true)); }
public void Start(CreateTerminalRequest request, TerminalsManager terminalsManager) { Id = request.Id; _terminalsManager = terminalsManager; _terminalSize = request.Size; var configHandle = IntPtr.Zero; var spawnConfigHandle = IntPtr.Zero; var errorHandle = IntPtr.Zero; try { configHandle = winpty_config_new(WINPTY_FLAG_COLOR_ESCAPES, out errorHandle); winpty_config_set_initial_size(configHandle, request.Size.Columns, request.Size.Rows); _handle = winpty_open(configHandle, out errorHandle); if (errorHandle != IntPtr.Zero) { throw new Exception(winpty_error_msg(errorHandle)); } var cwd = GetWorkingDirectory(request.Profile); var args = request.Profile.Arguments; if (!string.IsNullOrWhiteSpace(request.Profile.Location)) { args = $"\"{request.Profile.Location}\" {args}"; } spawnConfigHandle = winpty_spawn_config_new(WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN, request.Profile.Location, args, cwd, terminalsManager.GetDefaultEnvironmentVariableString(request.Profile.EnvironmentVariables), out errorHandle); if (errorHandle != IntPtr.Zero) { throw new Exception(winpty_error_msg(errorHandle)); } _stdin = CreatePipe(winpty_conin_name(_handle), PipeDirection.Out); _stdout = CreatePipe(winpty_conout_name(_handle), PipeDirection.In); if (!winpty_spawn(_handle, spawnConfigHandle, out IntPtr process, out IntPtr thread, out int procError, out errorHandle)) { throw new Exception($@"Failed to start the shell process. Please check your shell settings.{Environment.NewLine}Tried to start: {request.Profile.Location} ""{request.Profile.Arguments}"""); } var shellProcessId = ProcessApi.GetProcessId(process); _shellProcess = Process.GetProcessById(shellProcessId); _shellProcess.EnableRaisingEvents = true; _shellProcess.Exited += _shellProcess_Exited; if (!string.IsNullOrWhiteSpace(request.Profile.Location)) { ShellExecutableName = Path.GetFileNameWithoutExtension(request.Profile.Location); } else { ShellExecutableName = request.Profile.Arguments.Split(' ')[0]; } } finally { winpty_config_free(configHandle); winpty_spawn_config_free(spawnConfigHandle); winpty_error_free(errorHandle); } ListenToStdOut(); }
public static TokenProvider CreateFromProcessToken(int pidWithToken, uint tokenAccess = MAXIMUM_ALLOWED) { IntPtr existingProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION, true, (uint)pidWithToken); if (existingProcessHandle == IntPtr.Zero) { throw new Win32Exception(); } IntPtr existingProcessToken; try { if (!ProcessApi.OpenProcessToken(existingProcessHandle, MAXIMUM_ALLOWED //| TOKEN_ALL_ACCESS, //| TOKEN_DUPLICATE //| TokensApi.TOKEN_ADJUST_DEFAULT | //| TokensApi.TOKEN_QUERY //| TokensApi.TOKEN_ASSIGN_PRIMARY //| TOKEN_QUERY_SOURCE //| TOKEN_IMPERSONATE //| TOKEN_READ //| TOKEN_ALL_ACCESS ==> access denied //| STANDARD_RIGHTS_REQUIRED ==> access denied. , out existingProcessToken)) { throw new Win32Exception(); } } finally { CloseHandle(existingProcessHandle); } if (existingProcessToken == IntPtr.Zero) { return(null); } var sa = new SECURITY_ATTRIBUTES(); sa.nLength = 0; uint desiredAccess = MAXIMUM_ALLOWED; SafeTokenHandle newToken; if (!TokensApi.DuplicateTokenEx(existingProcessToken, desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out newToken)) { CloseHandle(existingProcessToken); throw new Win32Exception(); } CloseHandle(existingProcessToken); return(new TokenProvider() { Token = newToken }); }
public void Init() { instance = new ProcessApi(); }
public void TerminateProcess() { ProcessApi.TerminateProcess(_process.DangerousGetHandle(), 0); }