/// <summary> /// /// </summary> /// <param name="startInfo"></param> /// <returns></returns> internal static WardenProcess LaunchWin32App(WardenStartInfo startInfo) { if (!new FileInfo(startInfo.FileName).Exists) { throw new WardenLaunchException($"Unable to launch {startInfo.FileName} -- the file is missing."); } if (startInfo.AsUser) { if (!Api.StartProcessAndBypassUac(startInfo.FileName, startInfo.Arguments, startInfo.WorkingDirectory, out var procInfo)) { throw new WardenLaunchException(string.Format(Resources.Exception_Process_Not_Start, startInfo.FileName, startInfo.Arguments)); } return(WardenProcess.GetProcessFromId((int)procInfo.dwProcessId, startInfo.Filters)); } var processStartInfo = new ProcessStartInfo { FileName = startInfo.FileName, Arguments = startInfo.Arguments, WorkingDirectory = startInfo.WorkingDirectory, UseShellExecute = true }; using (var process = Process.Start(processStartInfo)) { if (process == null) { throw new WardenLaunchException(Resources.Exception_Process_Not_Launched_Unknown); } return(WardenProcess.GetProcessFromId(process.Id, startInfo.Filters)); } }
static void Main(string[] ars) { WardenManager.Logger = new WardenLogger(); WardenManager.OnUntrackedProcessAdded += WardenManagerOnOnUntrackedProcessAdded; WardenManager.Initialize(new WardenOptions { CleanOnExit = true, DeepKill = true, PollingInterval = TimeSpan.FromSeconds(1) }); Console.WriteLine("Start notepad"); /* var wardenTest = WardenProcess.StartUwp(new WardenStartInfo { PackageFamilyName = "Microsoft.MinecraftUWP_8wekyb3d8bbwe", ApplicationId = "App" });*/ var cancel = new CancellationTokenSource(); cancel.CancelAfter(TimeSpan.FromSeconds(10)); var wardenTest = WardenProcess.StartUriDeferred(new WardenStartInfo { FileName = "steam://run/107410", TargetFileName = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Arma 3\\arma3launcher.exe" }, delegate(bool b) { Console.WriteLine($"Alive! {b}"); }); if (wardenTest != null) { Console.WriteLine($"Hello {wardenTest.Id}"); wardenTest.OnStateChange += delegate (object sender, StateEventArgs args) { Console.WriteLine($"---\nName: {wardenTest.Name}\nId: {wardenTest.Id}\nstate changed to {args.State}\n---"); if (!wardenTest.IsTreeActive()) { Console.WriteLine("We're gone!"); Environment.Exit(0); } }; wardenTest.OnProcessAdded += delegate(object sender, ProcessAddedEventArgs args) { Console.WriteLine($"Added process {args.ProcessPath} to {args.ParentId}"); }; wardenTest.OnChildStateChange += delegate(object sender, StateEventArgs args) { var childInfo = wardenTest.FindChildById(args.Id); if (childInfo != null) { Console.WriteLine($"---\nName: {childInfo.Name}\nId: {childInfo.Id}\nParentId:{childInfo.ParentId}\nstated changed to {args.State}\n---"); } }; } Console.ReadKey(true); }
public async Task <WardenProcess> LaunchUri(string uri, string path, string arguments) { try { var startInfo = new ProcessStartInfo { FileName = uri, Arguments = string.IsNullOrWhiteSpace(arguments) ? string.Empty : arguments }; var process = new Process { StartInfo = startInfo }; if (!process.Start()) { throw new WardenLaunchException(string.Format(Resources.Exception_Process_Not_Start, startInfo.FileName, startInfo.Arguments)); } await Task.Delay(TimeSpan.FromMilliseconds(10)); var warden = new WardenProcess(Path.GetFileNameWithoutExtension(path), new Random().Next(100000, 199999), path, ProcessState.Alive, arguments, ProcessTypes.Uri); return(warden); } catch (Exception ex) { throw new WardenLaunchException(string.Format(Resources.Exception_Process_Not_Launched, ex.Message), ex); } }
public async Task <WardenProcess> Launch(string path, string arguments) { try { var getSafeFileName = ProgramPath.Match(path); if (!getSafeFileName.Success) { throw new WardenLaunchException(Resources.Exception_Process_Not_Launched_Unknown); } var filePath = getSafeFileName.Value; if (string.IsNullOrWhiteSpace(arguments)) { //Lets check our original path for arguments var argumentCollection = Arguments.Matches(path); var safeArguments = new StringBuilder(); foreach (Match arg in argumentCollection) { var argumentValue = arg.Value; if (argumentValue.Contains(filePath)) { continue; } safeArguments.Append(arg.Value); } arguments = safeArguments.ToString(); } if (string.IsNullOrWhiteSpace(_workingDir)) { _workingDir = new FileInfo(filePath).Directory.FullName; } var process = Process.Start(new ProcessStartInfo { FileName = filePath, Arguments = arguments, WorkingDirectory = (string.IsNullOrWhiteSpace(_workingDir) || !Directory.Exists(_workingDir)) ? string.Empty : _workingDir, UseShellExecute = true }); if (process == null) { throw new WardenLaunchException(Resources.Exception_Process_Not_Launched_Unknown); } await WaitForProcessStart(process, TimeSpan.FromSeconds(10)); var warden = new WardenProcess(process.ProcessName, process.Id, path, process.HasExited ? ProcessState.Dead : ProcessState.Alive, arguments?.SplitSpace(), ProcessTypes.Win32, null); return(warden); } catch (Exception ex) { throw new WardenLaunchException(string.Format(Resources.Exception_Process_Not_Launched, ex.Message), ex); } }
private bool Respawn() { _ulteriusInstance = null; _ulteriusInstance = WardenProcess.Start(_ulteriusPath, string.Empty, null, true).GetAwaiter().GetResult(); if (_ulteriusInstance == null || !_ulteriusInstance.IsTreeActive()) { return(false); } _ulteriusInstance.OnStateChange += UlteriusInstanceOnOnStateChange; return(true); }
/// <summary> /// Combines the Package Family Name and Application ID into a valid AUMID string and then launches the app. /// </summary> /// <param name="startInfo"></param> /// <returns>If the app is launched successfully a WardenProcess is returned.</returns> internal static WardenProcess LaunchApp(WardenStartInfo startInfo) { var aumid = $"{startInfo.PackageFamilyName}!{startInfo.ApplicationId}"; var processId = Launch(aumid, startInfo.Arguments); if (processId <= 0) { throw new WardenLaunchException(string.Format(Resources.Exception_Could_Not_Find_Process_Id, aumid)); } return(WardenProcess.GetProcessFromId(processId, startInfo.Filters)); }
public void Stop() { const string ulteriusFileName = "Ulterius Server.exe"; if (_ulteriusInstance != null) { _ulteriusInstance?.Kill(); WardenManager.Flush(_ulteriusInstance.Id); } _ulteriusInstance = null; EndProcessTree(ulteriusFileName); }
private static async Task Start() { WardenManager.Initialize(); Console.Write("Enter the process ID: "); var processId = int.Parse(Console.ReadLine()); var test = WardenProcess.GetProcessFromId(processId); test.OnProcessAdded += delegate(object sender, ProcessAddedEventArgs args) { if (args.ParentId == test.Id) { Console.WriteLine($"Added child {args.Name}({args.Id}) to root process {test.Name}({test.Id})"); } else { var parentInfo = test.FindChildById(args.ParentId); if (parentInfo != null) { Console.WriteLine($"Added child process {args.Name}({args.Id}) to child {parentInfo.Name}({parentInfo.Id})"); } } }; test.OnStateChange += delegate(object sender, StateEventArgs args) { Console.WriteLine($"---\nName: {test.Name}\nId: {test.Id}\nstate changed to {args.State}\n---"); }; test.OnChildStateChange += delegate(object sender, StateEventArgs args) { var childInfo = test.FindChildById(args.Id); if (childInfo != null) { Console.WriteLine($"---\nName: {childInfo.Name}\nId: {childInfo.Id}\nParentId:{childInfo.ParentId}\nstated changed to {args.State}\n---"); } }; Console.WriteLine($"Hooked into {test.Name}({test.Id})"); Console.Read(); Console.WriteLine("Start notepad"); var wardenTest = await WardenProcess.Start("notepad.exe", string.Empty, ProcessTypes.Win32); if (wardenTest != null) { wardenTest.OnStateChange += delegate(object sender, StateEventArgs args) { Console.WriteLine($"---\nName: {wardenTest.Name}\nId: {wardenTest.Id}\nstate changed to {args.State}\n---"); }; } Console.ReadKey(true); }
public async void WardenGetsTestProcessInformation() { WardenManager.Initialize(); var testProcess = await WardenProcess.Start("TestProcess.exe", string.Empty, ProcessTypes.Win32); var children = testProcess.Children.ToArray(); testProcess.OnChildStateChange += TestProcessOnOnChildStateChange; await Task.Delay(5000); Assert.NotEmpty(testProcess.Children); testProcess.Kill(); await Task.Delay(2000); Assert.True(testProcess.State == ProcessState.Dead); }
public async Task <WardenProcess> Launch(string path, string arguments, bool asUser) { if (asUser) { var formattedPath = $"{path} {arguments}"; if (Api.StartProcessAndBypassUac(formattedPath, out var procInfo) && procInfo.dwProcessId > 0) { return(WardenProcess.GetProcessFromId((int)procInfo.dwProcessId)); } } else { return(await Launch(path, arguments)); } return(null); }
/// <summary> /// Attempts to create a process outside of session zero. /// </summary> /// <param name="startInfo"></param> /// <returns></returns> internal static WardenProcess CreateProcessAsUser(WardenStartInfo startInfo) { if (!new FileInfo(startInfo.FileName).Exists) { throw new WardenLaunchException($"Unable to launch {startInfo.FileName} -- the file is missing."); } if (startInfo.RaisePrivileges) { if (Api.StartProcessAsPrivilegedUser(startInfo.FileName, startInfo.Arguments, startInfo.WorkingDirectory, out var privInfo)) { return(WardenProcess.GetProcessFromId(privInfo, startInfo.Filters, startInfo.Track)); } throw new WardenLaunchException("Unable to start process as privileged user"); } if (Api.StartProcessAsUser(startInfo.FileName, startInfo.Arguments, startInfo.WorkingDirectory, out var procInfo)) { return(WardenProcess.GetProcessFromId(procInfo, startInfo.Filters, startInfo.Track)); } throw new WardenLaunchException("Unable to start process as user"); }
private static void Main(string[] args) { var process = WardenProcess.GetCurrentProcess(); Console.WriteLine(process.Info); SystemProcessMonitor.Start(new MonitorOptions()); WardenProcess.Start(new WardenStartInfo { FileName = "spotify://album:27ftYHLeunzcSzb33Wk1hf", Track = false, }); var solitaire = WardenProcess.Start( new WardenStartInfo { FileName = "xboxliveapp-1297287741:", TargetImage = "C:\\Program Files\\WindowsApps\\Microsoft.MicrosoftSolitaireCollection_4.7.10142.0_x64__8wekyb3d8bbwe\\Solitaire.exe", Track = true, }, OnFound); if (solitaire is { Info : not null })
public async Task <WardenProcess> Launch(string path, string arguments) { try { var process = Process.Start(new ProcessStartInfo { FileName = path, Arguments = string.IsNullOrWhiteSpace(arguments) ? string.Empty : arguments }); if (process == null) { throw new WardenLaunchException(Resources.Exception_Process_Not_Launched_Unknown); } await WaitForProcessStart(process, TimeSpan.FromSeconds(10)); var warden = new WardenProcess(process.ProcessName, process.Id, path, process.HasExited ? ProcessState.Dead : ProcessState.Alive, arguments, ProcessTypes.Win32); return(warden); } catch (Exception ex) { throw new WardenLaunchException(string.Format(Resources.Exception_Process_Not_Launched, ex.Message), ex); } }
/// <summary> /// Creates a new process object with the privileges of LocalSystem in the interactive desktop session. /// </summary> /// <param name="info"> /// The <see cref="WardenStartInfo"/> that contains the information that is used to start the process, /// including the PackageFamilyName, ApplicationId, and any command-line arguments. /// </param> /// <returns>A <see cref="WardenProcess"/> instance that is associated with the created process.</returns> internal static WardenProcess?AsLocalSystem(WardenStartInfo info) { var environmentBlockHandle = IntPtr.Zero; var startInfo = new StartupInfo(); var processInformation = new ProcessInformation(); startInfo.cb = Marshal.SizeOf <StartupInfo>(); try { if (!TryGetInteractiveUserToken(out var sessionId, out var interactiveUserToken)) { throw new Win32Exception("GetSessionUserToken failed."); } // 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. startInfo.wShowWindow = (short)SW.SW_SHOW; startInfo.lpDesktop = InteractiveWindowStation; using var registryHandle = LoadUserProfile((int)sessionId, interactiveUserToken, out _); if (registryHandle.IsInvalid) { throw new Win32Exception("LoadUserProfile failed."); } // copy the users env block if (!CreateEnvironmentBlock(ref environmentBlockHandle, interactiveUserToken, false)) { throw new Win32Exception("CreateEnvironmentBlock failed."); } var logonProcessId = GetWinLogonProcessId(sessionId); if (logonProcessId == 0) { throw new Win32Exception($"Unable to find the WinLogon process ID for session '{sessionId}'."); } using var processHandle = ProcessNative.OpenProcessHandle(ProcessNative.ProcessAccessFlags.MaximumAllowed, logonProcessId); if (processHandle.IsInvalid) { throw new Win32Exception("Unable to obtain a valid handle for winlogon.exe"); } if (!ProcessNative.OpenProcessToken(processHandle, TOKEN_ALL_ACCESS, out var processToken)) { throw new Win32Exception("Unable to open the process token for winlogon.exe"); } // ReSharper disable once UseObjectOrCollectionInitializer var securityAttributes = new SecurityAttributes(); securityAttributes.Length = Marshal.SizeOf <SecurityAttributes>(); // copy the access token of the explorer process; the newly created token will be a primary token if (!DuplicateTokenEx(processToken, MAXIMUM_ALLOWED, securityAttributes, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, TokenType.Primary, out var winLogonToken)) { throw new Win32Exception("Unable to duplicate the winlogon.exe process token"); } const int creationFlags = CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS; if (!CreateProcessAsUser(winLogonToken, info.FileName, info.Arguments, securityAttributes, securityAttributes, false, creationFlags, environmentBlockHandle, info.WorkingDirectory, ref startInfo, out processInformation)) { throw new Win32Exception($"CreateProcessAsUserW failed: {Marshal.GetLastWin32Error()}"); } UnloadUserProfile(interactiveUserToken, registryHandle); return(WardenProcess.GetProcessById(processInformation.ProcessId, info.Track, info.FilteredImages)); } finally { DestroyEnvironmentBlock(environmentBlockHandle); CloseHandle(processInformation.ThreadHandle); CloseHandle(processInformation.ProcessHandle); CloseHandle(startInfo.hStdError); CloseHandle(startInfo.hStdInput); CloseHandle(startInfo.hStdOutput); CloseHandle(startInfo.lpReserved2); } }
/// <summary> /// Creates a new process object the interactive desktop session. /// </summary> /// <param name="info"> /// The <see cref="WardenStartInfo"/> that contains the information that is used to start the process, /// including the PackageFamilyName, ApplicationId, and any command-line arguments. /// </param> /// <returns>A <see cref="WardenProcess"/> instance that is associated with the created process.</returns> internal static WardenProcess?AsUser(WardenStartInfo info) { var environmentBlockHandle = IntPtr.Zero; var startInfo = new StartupInfo(); var processInformation = new ProcessInformation(); startInfo.cb = Marshal.SizeOf <StartupInfo>(); try { if (!TryGetInteractiveUserToken(out var sessionId, out var interactiveUserToken)) { throw new Win32Exception("GetSessionUserToken failed."); } // 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. startInfo.wShowWindow = (short)SW.SW_SHOW; startInfo.lpDesktop = InteractiveWindowStation; using var registryHandle = LoadUserProfile((int)sessionId, interactiveUserToken, out _); if (registryHandle.IsInvalid) { throw new Win32Exception("LoadUserProfile failed."); } // copy the users env block if (!CreateEnvironmentBlock(ref environmentBlockHandle, interactiveUserToken, false)) { throw new Win32Exception("CreateEnvironmentBlock failed."); } const int creationFlags = CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS; if (!CreateProcessAsUser(interactiveUserToken, info.FileName, info.Arguments, null, null, false, creationFlags, environmentBlockHandle, info.WorkingDirectory, ref startInfo, out processInformation)) { throw new Win32Exception("CreateProcessAsUser failed"); } UnloadUserProfile(interactiveUserToken, registryHandle); return(WardenProcess.GetProcessById(processInformation.ProcessId, info.Track, info.FilteredImages)); } finally { DestroyEnvironmentBlock(environmentBlockHandle); CloseHandle(processInformation.ThreadHandle); CloseHandle(processInformation.ProcessHandle); CloseHandle(startInfo.hStdError); CloseHandle(startInfo.hStdInput); CloseHandle(startInfo.hStdOutput); CloseHandle(startInfo.lpReserved2); } }
private static async Task Start() { WardenManager.Initialize(new WardenOptions { CleanOnExit = true, DeepKill = true, ReadFileHeaders = true }); Console.Write("Enter the process ID: "); var processId = int.Parse(Console.ReadLine()); var test = WardenProcess.GetProcessFromId(processId); if (test != null) { test.OnProcessAdded += delegate(object sender, ProcessAddedEventArgs args) { if (args.ParentId == test.Id) { Console.WriteLine($"Added child {args.Name}({args.Id}) to root process {test.Name}({test.Id})"); } else { var parentInfo = test.FindChildById(args.ParentId); if (parentInfo != null) { Console.WriteLine($"Added child process {args.Name}({args.Id}) to child {parentInfo.Name}({parentInfo.Id})"); } } }; test.OnStateChange += delegate(object sender, StateEventArgs args) { Console.WriteLine($"---\nName: {test.Name}\nId: {test.Id}\nstate changed to {args.State}\n---"); }; test.OnChildStateChange += delegate(object sender, StateEventArgs args) { var childInfo = test.FindChildById(args.Id); if (childInfo != null) { Console.WriteLine($"---\nName: {childInfo.Name}\nId: {childInfo.Id}\nParentId:{childInfo.ParentId}\nstated changed to {args.State}\n---"); } }; Console.WriteLine($"Hooked into {test.Name}({test.Id})"); Console.Read(); Console.WriteLine(JsonConvert.SerializeObject(test, Formatting.Indented)); test.Kill(); } Console.WriteLine("Start notepad"); var wardenTest = await WardenProcess.Start("notepad", string.Empty, null); if (wardenTest != null) { wardenTest.OnStateChange += delegate(object sender, StateEventArgs args) { Console.WriteLine($"---\nName: {wardenTest.Name}\nId: {wardenTest.Id}\nstate changed to {args.State}\n---"); }; } Console.ReadKey(true); }
public TestWardenOnTestProcess() { WardenManager.Initialize(true); _currentProcess = WardenProcess.GetProcessFromId(Process.GetCurrentProcess().Id); }