示例#1
0
        public static List <Win32Process> GetWin32Processes(string processName = null)
        {
            ManagementObjectSearcher   searcher   = new ManagementObjectSearcher("SELECT * FROM Win32_Process");
            ManagementObjectCollection collection = searcher.Get();

            var items = new List <Win32Process>();

            foreach (var obj in collection)
            {
                var item = new Win32Process
                {
                    Name            = (string)obj["Name"],
                    ProcessId       = (uint?)obj["ProcessId"],
                    ParentProcessId = (uint?)obj["ParentProcessId"],
                    CreationDate    =
                        obj["CreationDate"] == null
                            ? (DateTime?)null
                            : ManagementDateTimeConverter.ToDateTime(obj["CreationDate"].ToString())
                };
                if (!string.IsNullOrEmpty(processName) &&
                    !item.Name.StartsWith(processName, StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                items.Add(item);
            }
            return(items);
        }
        public static bool AttachToProgram(DTE2 DTE, string program)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            var processes = Win32Process.GetProcesses().ToList();

            var reattachedProcess = processes.FirstOrDefault(x => string.Equals(x.CommandLine, PreviousProgram));

            if (reattachedProcess == null)
            {
                return(false);
            }

            var localProcesses = DTE.Debugger.LocalProcesses;

            foreach (Process localProcess in localProcesses)
            {
                if (localProcess.ProcessID != reattachedProcess.ProcessId)
                {
                    continue;
                }

                localProcess.Attach();

                return(true);
            }

            return(false);
        }
 public void QueryParentProcess()
 {
     Win32Process[] processes = ProcessHelper.ByName("svchost.exe").ToArray();
     EnumerableAssert.Any(processes);
     processes.ForEach(process =>
     {
         Win32Process parentProcess = ProcessHelper.ParentProcess(process.ProcessId.Value);
         Assert.IsNotNull(parentProcess);
     });
 }
示例#4
0
文件: Program.cs 项目: codehz/winsilo
 static void Main()
 {
     using var token = FetchDesktopToken();
     using var proc  = Win32Process.CreateProcessWithToken(token, new Win32ProcessConfig {
         ApplicationName = @"C:\Windows\System32\cmd.exe",
         CommandLine     = @"",
         CreationFlags   = CreateProcessFlags.NewConsole,
         Token           = token,
     });
 }
        public void QueryByIdTest()
        {
            int id = Process.GetProcessesByName("wininit").Single().Id;

            Assert.IsNotNull(id);
            Win32Process process = ProcessHelper.ById((uint)id);

            Assert.IsNotNull(process);
            Assert.AreEqual("wininit.exe", process.Name);
        }
        static void Main(string[] args)
        {
            try
            {
                if (!IsInAppContainer())
                {
                    if (args.Length > 0)
                    {
                        throw new ArgumentException("Already started");
                    }

                    Win32ProcessConfig config = new Win32ProcessConfig();
                    config.ApplicationName = CopyToTempDir();
                    config.CommandLine     = "run abc";
                    config.AppContainerSid = TokenUtils.DerivePackageSidFromName("microsoft.windowscalculator_8wekyb3d8bbwe");
                    config.CreationFlags   = CreateProcessFlags.NewConsole;
                    using (var p = Win32Process.CreateProcess(config))
                    {
                        p.Process.Wait();
                    }
                }
                else
                {
                    Console.WriteLine("In AC");
                    Console.WriteLine("idiot");
                    // Spawn an OOP process to init
                    Guid clsid = new Guid("ce0e0be8-cf56-4577-9577-34cc96ac087c");
                    Guid iid   = new Guid("00000000-0000-0000-c000-000000000046");
                    CoCreateInstance(ref clsid, IntPtr.Zero, CLSCTX.LOCAL_SERVER, ref iid);
                    using (var client = new Client())
                    {
                        client.Connect("actkernel");
                        uint res = client.PrivGetPsmToken(0x40000001, 0, "Microsoft.MicrosoftEdge_44.18362.1.0_neutral__8wekyb3d8bbwe",
                                                          "Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge", out NtToken token, out int a);
                        if (res != 0)
                        {
                            throw new SafeWin32Exception((int)res);
                        }

                        using (token)
                        {
                            Console.WriteLine("{0} - Handle: {1:X}", token, token.Handle.DangerousGetHandle().ToInt32());
                            Console.WriteLine("Package Sid: {0}", token.AppContainerSid.Name);
                            Console.WriteLine("AppId: {0}", token.PackageFullName);
                            Console.ReadLine();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
        private void btnCreateProcess_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBoxUseWmi.Checked || checkBoxUseNetLogon.Checked)
                {
                    using (var token = _token.DuplicateToken(TokenType.Impersonation, SecurityImpersonationLevel.Impersonation, TokenAccessRights.MaximumAllowed))
                    {
                        token.SetDefaultDacl(new Acl(IntPtr.Zero, false));
                        using (var imp = token.Impersonate())
                        {
                            if (checkBoxUseWmi.Checked)
                            {
                                using (var managementClass = new ManagementClass(@"\\.\root\cimv2",
                                                                                 "Win32_Process",
                                                                                 new ObjectGetOptions()))
                                {
                                    var inputParams = managementClass.GetMethodParameters("Create");

                                    inputParams["CommandLine"] = txtCommandLine.Text;
                                    var outParams = managementClass.InvokeMethod("Create",
                                                                                 inputParams,
                                                                                 new InvokeMethodOptions());
                                }
                            }
                            else
                            {
                                var config = new Win32ProcessConfig
                                {
                                    CommandLine = txtCommandLine.Text,
                                    Desktop     = @"WinSta0\Default"
                                };
                                using (Win32Process.CreateProcessWithLogon("abc", "abc", "abc",
                                                                           CreateProcessLogonFlags.NetCredentialsOnly | CreateProcessLogonFlags.WithProfile, config))
                                {
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (CreateProcessForToken(txtCommandLine.Text, _token, checkBoxMakeInteractive.Checked))
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#8
0
        public void KillHost()
        {
            _sessionLogger.LogTrace("Killing host process for session '{0}'.", Id);

            try {
                _process?.Kill();
            } catch (Exception ex) {
                _sessionLogger.LogError(0, ex, "Failed to kill host process for session '{0}'.", Id);
                throw;
            }

            _process = null;
        }
示例#9
0
        static void Main(string[] args)
        {
            Process[] processes;

            do
            {
                processes = Process.GetProcessesByName("lawl.exe");
                if (processes.Length > 0)
                {
                    Win32Process process = new Win32Process(processes[0]);
                    process.Inject("dllName.dll", "Initialize");
                }
            } while (processes.Length <= 0);
        }
        static NtToken CreateProcessForToken(string cmdline, NtToken token, bool make_interactive)
        {
            using (NtToken newtoken = token.DuplicateToken(TokenType.Primary, SecurityImpersonationLevel.Anonymous, TokenAccessRights.MaximumAllowed))
            {
                string desktop = null;
                if (make_interactive)
                {
                    desktop = @"WinSta0\Default";
                    newtoken.SetSessionId(NtProcess.Current.SessionId);
                }

                using (Win32Process process = Win32Process.CreateProcessAsUser(newtoken, null, cmdline, CreateProcessFlags.None, desktop))
                {
                    return(process.Process.OpenToken());
                }
            }
        }
示例#11
0
        static bool RestartInAppContainer(string[] args)
        {
            string FakeFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "1.txt");

            if (!File.Exists(FakeFile))
            {
                File.WriteAllText(FakeFile, "fake");
            }
            FixSecurity(Path.GetDirectoryName(typeof(Program).Assembly.Location));
            FixSecurity(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));


            List <Sid> caps = new List <Sid>
            {
                KnownSids.CapabilityInternetClient,
                KnownSids.CapabilityInternetClientServer,
                KnownSids.CapabilityPrivateNetworkClientServer,
                KnownSids.CapabilityPicturesLibrary
            };


            Win32ProcessConfig config = new Win32ProcessConfig
            {
                CreationFlags    = CreateProcessFlags.NewConsole,
                CurrentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                ApplicationName  = mainExe,
                CommandLine      = mainExe + " " + FakeFile
            };

            config.SetAppContainerSidFromName("microsoft.windowscalculator_8wekyb3d8bbwe");

            config.Capabilities.AddRange(caps);

            using (var p = Win32Process.CreateProcess(config))
            {
                p.Process.Wait();
            }
            return(true);
        }
示例#12
0
        public SystemInfo(Win32ComputerSystem system, Win32Process process)
        {
            if (system != null)
            {
                Domain                = system.Domain;
                MachineName           = system.Name;
                ProcessorCount        = system.NumberOfProcessors;
                LogicalProcessorCount = system.NumberOfLogicalProcessors;
                PartOfDomain          = system.PartOfDomain;
                SystemType            = string.Format("{0} ({1})", system.PcSystemType, system.SystemType);
            }

            if (process != null)
            {
                ProcessName    = process.Name;
                ThreadCount    = process.ThreadCount;
                ExecutablePath = process.ExecutablePath;
                StartDate      = process.CreationDate.ToUniversalTime();

                float workingSetSizeInMb = (process.WorkingSetSize / 1024f) / 1024f;;
                WorkingSetSize = string.Format("{0} MB", workingSetSizeInMb.ToString("0.00"));
            }

            LastUpdated = DateTime.Now;

            ulong freeBytesAvailable;
            ulong totalNumberOfBytes;
            ulong totalNumberOfFreeBytes;

            bool success = GetDiskFreeSpaceEx(Directory.GetCurrentDirectory(),
                                              out freeBytesAvailable,
                                              out totalNumberOfBytes,
                                              out totalNumberOfFreeBytes);

            if (success)
            {
                FreeDiskSpace = BytesToString(freeBytesAvailable);
            }
        }
示例#13
0
        private void OnEventArrived(object sender, EventArrivedEventArgs e)
        {
            string eventType = e.NewEvent.ClassPath.ClassName;

            Win32Process process = new
                                   Win32Process(e.NewEvent["TargetInstance"] as ManagementBaseObject);

            if (ProcessStateChanged != null)
            {
                ProcessStateChangedEventArgs processStateChangedEventArgs = new ProcessStateChangedEventArgs();
                processStateChangedEventArgs.ProcessProxy.Id          = (int)process.ProcessId;
                processStateChangedEventArgs.ProcessProxy.ProcessName = process.Name;

                switch (eventType)
                {
                case "__InstanceCreationEvent":
                    processStateChangedEventArgs.StateChangeType =
                        ProcessStateChangedEventArgs.StateChangeTypes.Created;
                    break;

                case "__InstanceModificationEvent":
                    processStateChangedEventArgs.StateChangeType =
                        ProcessStateChangedEventArgs.StateChangeTypes.Modified;
                    break;

                case "__InstanceDeletionEvent":
                    processStateChangedEventArgs.StateChangeType =
                        ProcessStateChangedEventArgs.StateChangeTypes.Deleted;
                    break;
                }

                if (processStateChangedEventArgs.StateChangeType
                    != ProcessStateChangedEventArgs.StateChangeTypes.Modified)
                {
                    ProcessStateChanged(this, processStateChangedEventArgs);
                }
            }
        }
示例#14
0
        private static void Inject()
        {
            var targetLibBase = IntPtr.Zero;
            // Get process handle.
            using (var steamProc = DDDAExUtil.LaunchGame())
            {
                Debug.WriteLine("Waiting for Steam to launch DDDA..");
                steamProc.WaitForExit();
            }

            Debug.WriteLine("Attempting to capture DDDA process..");
            // Capture game process.
            Process process;
            do
            {
                process = Process.GetProcessesByName("DDDA").FirstOrDefault();
                Task.Delay(10).Wait();
            } while (process == null);
            using (var proc = new Win32Process(process.Id, ProcessAccess.All))
            {
                Debug.WriteLine("Suspending DDDA process..");
                proc.Suspend();
                var procMainThread = proc.Threads.OrderBy(t => t.Created.Ticks).First();
                var threadEip = procMainThread.Registers.Eip;

                Debug.Write("Reading main thread bytes..");
                // Copy first two bytes of thread entry.
                var threadPStart = proc.ReadBytes(threadEip, 2);
                Debug.WriteLine(BitConverter.ToString(threadPStart));

                Debug.Write("Writing loop in main thread location..");
                // Write infinite loop.
                Debug.WriteLine($"Wrote {proc.WriteBytes(threadEip, new byte[] { 0xEB, 0xFE })} bytes.");

                Debug.WriteLine("Waiting for DLLs to load..");
                // Resume and wait for kernel32 to load. Then pause.
                procMainThread.Resume();
                while (!proc.Modules.Any(m => m.Name.IndexOf("kernel32", StringComparison.OrdinalIgnoreCase) >= 0))
                    Thread.Sleep(10);
                procMainThread.Suspend();

                Debug.WriteLine("Restoring original thread code..");
                // Remove infinite loop from target process and resume game.
                proc.WriteBytes(threadEip, threadPStart);
                procMainThread.Resume();

                Debug.WriteLine("Getting LoadLibraryW offset..");
                // Get the LoadLibraryW function pointer from kernel32.dll.
                var loadLibFunc = proc.Modules.First(m => m.Name.IndexOf("kernel32.dll", StringComparison.OrdinalIgnoreCase) >= 0).GetProcAddress("LoadLibraryA");

                Debug.WriteLine(
                    $"Writing CLR hoster dll path into process.. loadLibFunc: 0x{loadLibFunc.ToString("X2")}");
                // Write dll path in process.
                var fullPath = Path.GetFullPath(LocalHosterPath);
                var alloc = proc.Alloc(fullPath.Length, AllocationType.MemReserve | AllocationType.MemCommit,
                    ProtectType.ReadWrite);
                proc.WriteString(alloc, fullPath);

                Debug.WriteLine("Retrieve ExecuteCLR function offset..");
                // Load library in current process (to retrieve function pointer offset).
                var currentDll = proc.Load(LocalHosterPath);
                var clrFuncOffset = IntPtr.Subtract(Win32Process.GetProcAddress(currentDll, "ExecuteCLR"),
                    currentDll.ToInt32());

                // Resume process (to make sure that LoadLibrary gets called and not dead-locking).
                process.Threads.Cast<ProcessThread>().ToList().ForEach(t => Win32Thread.Resume(t.Id));

                // Load library in target process.
                WaitForType waitResult;
                do
                {
                    Debug.WriteLine(
                        $"Loading CLR hoster into target.. procHandle:0x{proc.Handle.ToString("X2")}, loadLibFunc:0x{loadLibFunc.ToString("X2")}, alloc:0x{alloc.ToString("X2")}");
                    using (var loadLibThread = proc.Execute(loadLibFunc, alloc))
                    {
                        Debug.WriteLine("Wait for dll to load in target process..");
                        waitResult = loadLibThread.Wait(3 * 1000);
                        if (waitResult == WaitForType.Failed)
                        {
                            MessageBox.Show("Could not wait for LoadLibraryThread to inject dll.", "Injection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        targetLibBase = loadLibThread.ExitCode;
                        Debug.WriteLine($"Wait result: {waitResult}");
                    }
                } while (waitResult != WaitForType.StateSignaled);

                // Wait for the process to initalize a bit..
                Task.Delay(1000).Wait();

                proc.Execute(IntPtr.Add(targetLibBase, clrFuncOffset.ToInt32()));
            }
        }
示例#15
0
        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.BreakawayFromJob : 0 },
                    { "c", "Create a new console for the process", v => flags |= v != null ? CreateProcessFlags.NewConsole : 0 },
                    { "s", "Create the process suspended", v => flags |= v != null ? CreateProcessFlags.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.Suspended : flags, null);
                        if (set_il)
                        {
                            using (NtToken token = new_process.Process.OpenToken())
                            {
                                token.SetIntegrityLevel(il);
                            }
                            if ((flags & CreateProcessFlags.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
                    {
                    }
                }
            }
        }
示例#16
0
        public IProcess StartHost(Interpreter interpreter, string profilePath, string userName, WindowsIdentity useridentity, string commandLine)
        {
            string brokerPath   = Path.GetDirectoryName(typeof(Program).Assembly.GetAssemblyPath());
            string rhostExePath = Path.Combine(brokerPath, RHostExe);

            commandLine = FormattableString.Invariant($"\"{rhostExePath}\" {commandLine}");
            var usernameBldr = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
            var domainBldr   = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1);

            // Get R_HOME value
            var shortHome = new StringBuilder(NativeMethods.MAX_PATH);

            NativeMethods.GetShortPathName(interpreter.Info.Path, shortHome, shortHome.Capacity);

            var loggedOnUser = useridentity != null && WindowsIdentity.GetCurrent().User != useridentity.User;

            // build user environment block
            Win32EnvironmentBlock eb;

            if (loggedOnUser)
            {
                uint error = NativeMethods.CredUIParseUserName(userName, usernameBldr, usernameBldr.Capacity, domainBldr, domainBldr.Capacity);
                if (error != 0)
                {
                    _sessionLogger.LogError(Resources.Error_UserNameParse, userName, error);
                    throw new ArgumentException(Resources.Error_UserNameParse.FormatInvariant(userName, error));
                }

                string username = usernameBldr.ToString();
                string domain   = domainBldr.ToString();

                eb = CreateEnvironmentBlockForUser(useridentity, username, profilePath);
            }
            else
            {
                eb = Win32EnvironmentBlock.Create((useridentity ?? WindowsIdentity.GetCurrent()).Token);
            }

            // add additional variables to the environment block
            eb["R_HOME"] = shortHome.ToString();
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "R_HOME", eb["R_HOME"]);
            eb["PATH"] = FormattableString.Invariant($"{interpreter.Info.BinPath};{Environment.GetEnvironmentVariable("PATH")}");
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "PATH", eb["PATH"]);

            Win32Process win32Process;

            using (Win32NativeEnvironmentBlock nativeEnv = eb.GetNativeEnvironmentBlock()) {
                if (loggedOnUser)
                {
                    win32Process = Win32Process.StartProcessAsUser(useridentity, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv);
                }
                else
                {
                    win32Process = Win32Process.StartProcessAsUser(null, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv);
                }
            }

            win32Process.WaitForExit(250);
            if (win32Process.HasExited && win32Process.ExitCode < 0)
            {
                var message = ErrorCodeConverter.MessageFromErrorCode(win32Process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new Win32Exception(message);
                }
                throw new Win32Exception(win32Process.ExitCode);
            }

            return(win32Process);
        }
示例#17
0
        protected override void FillFloppyDriveInfo()
        {
            ManagementObjectCollection moc = this.GetAllInfo(this.WSql);

            foreach (ManagementObject mo in moc)
            {
                Win32Process csp = new Win32Process();

                if (mo != null)
                {
                    csp.Caption             = GetManagementObject <string>(mo, "Caption");
                    csp.CommandLine         = GetManagementObject <string>(mo, "CommandLine");
                    csp.CreationClassName   = GetManagementObject <string>(mo, "CreationClassName");
                    csp.Cim_CreationDate    = GetManagementObject <string>(mo, "CreationDate");
                    csp.CSCreationClassName = GetManagementObject <string>(mo, "CSCreationClassName");
                    csp.CSName                = GetManagementObject <string>(mo, "CSName");
                    csp.Description           = GetManagementObject <string>(mo, "Description");
                    csp.ExecutablePath        = GetManagementObject <string>(mo, "ExecutablePath");
                    csp.ExecutionState        = GetManagementObject <ushort>(mo, "ExecutionState");
                    csp.Handle                = GetManagementObject <string>(mo, "Handle");
                    csp.HandleCount           = GetManagementObject <uint>(mo, "HandleCount");
                    csp.Cim_InstallDate       = GetManagementObject <string>(mo, "InstallDate");
                    csp.KernelModeTime        = GetManagementObject <ulong>(mo, "KernelModeTime");
                    csp.MaximumWorkingSetSize = GetManagementObject <uint>(mo, "MaximumWorkingSetSize");
                    csp.MinimumWorkingSetSize = GetManagementObject <uint>(mo, "MinimumWorkingSetSize");
                    csp.Name = GetManagementObject <string>(mo, "Name");
                    csp.OSCreationClassName = GetManagementObject <string>(mo, "OSCreationClassName");
                    csp.OSName = GetManagementObject <string>(mo, "OSName");
                    csp.OtherOperationCount        = GetManagementObject <ulong>(mo, "OtherOperationCount");
                    csp.OtherTransferCount         = GetManagementObject <ulong>(mo, "OtherTransferCount");
                    csp.PageFaults                 = GetManagementObject <uint>(mo, "PageFaults");
                    csp.PageFileUsage              = GetManagementObject <uint>(mo, "PageFileUsage");
                    csp.ParentProcessId            = GetManagementObject <uint>(mo, "ParentProcessId");
                    csp.PeakPageFileUsage          = GetManagementObject <uint>(mo, "PeakPageFileUsage");
                    csp.PeakVirtualSize            = GetManagementObject <ulong>(mo, "PeakVirtualSize");
                    csp.PeakWorkingSetSize         = GetManagementObject <uint>(mo, "PeakWorkingSetSize");
                    csp.Priority                   = GetManagementObject <uint>(mo, "Priority");
                    csp.PrivatePageCount           = GetManagementObject <ulong>(mo, "PrivatePageCount");
                    csp.ProcessId                  = GetManagementObject <uint>(mo, "ProcessId");
                    csp.QuotaNonPagedPoolUsage     = GetManagementObject <uint>(mo, "QuotaNonPagedPoolUsage");
                    csp.QuotaPagedPoolUsage        = GetManagementObject <uint>(mo, "QuotaPagedPoolUsage");
                    csp.QuotaPeakPagedPoolUsage    = GetManagementObject <uint>(mo, "QuotaPeakPagedPoolUsage");
                    csp.QuotaPeakNonPagedPoolUsage = GetManagementObject <uint>(mo, "QuotaPeakNonPagedPoolUsage");
                    csp.ReadOperationCount         = GetManagementObject <ulong>(mo, "ReadOperationCount");
                    csp.ReadTransferCount          = GetManagementObject <ulong>(mo, "ReadTransferCount");
                    csp.SessionId                  = GetManagementObject <uint>(mo, "SessionId");
                    csp.Status = GetManagementObject <string>(mo, "Status");
                    csp.Cim_TerminationDate = GetManagementObject <string>(mo, "TerminationDate");
                    csp.ThreadCount         = GetManagementObject <uint>(mo, "ThreadCount");
                    csp.UserModeTime        = GetManagementObject <ulong>(mo, "UserModeTime");
                    csp.VirtualSize         = GetManagementObject <ulong>(mo, "VirtualSize");
                    csp.WindowsVersion      = GetManagementObject <string>(mo, "WindowsVersion");
                    csp.WorkingSetSize      = GetManagementObject <ulong>(mo, "WorkingSetSize");
                    csp.WriteOperationCount = GetManagementObject <ulong>(mo, "WriteOperationCount");
                    csp.WriteTransferCount  = GetManagementObject <ulong>(mo, "WriteTransferCount");

                    ps.Add(csp);
                }
            }
            moc.Dispose();
        }
示例#18
0
        public void StartHost(string profilePath, string logFolder, ILogger outputLogger, LogVerbosity verbosity)
        {
            if (_hostEnd != null)
            {
                throw new InvalidOperationException("Host process is already running");
            }

            var useridentity = User as WindowsIdentity;
            // In remote broker User Identity type is always WindowsIdentity
            string suppressUI     = (useridentity == null) ? string.Empty : "--rhost-suppress-ui ";
            string isRepl         = _isInteractive ? "--rhost-interactive " : string.Empty;
            string brokerPath     = Path.GetDirectoryName(typeof(Program).Assembly.GetAssemblyPath());
            string rhostExePath   = Path.Combine(brokerPath, RHostExe);
            string logFolderParam = string.IsNullOrEmpty(logFolder) ? string.Empty : Invariant($"--rhost-log-dir \"{logFolder}\"");
            string commandLine    = Invariant($"\"{rhostExePath}\" {suppressUI}{isRepl}--rhost-name \"{Id}\" {logFolderParam} --rhost-log-verbosity {(int)verbosity} {CommandLineArguments}");
            var    usernameBldr   = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
            var    domainBldr     = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1);

            // Get R_HOME value
            var shortHome = new StringBuilder(NativeMethods.MAX_PATH);

            NativeMethods.GetShortPathName(Interpreter.Info.Path, shortHome, shortHome.Capacity);

            Stream stdout, stdin, stderror;
            bool   loggedOnUser = useridentity != null && WindowsIdentity.GetCurrent().User != useridentity.User;

            // build user environment block
            Win32EnvironmentBlock eb;

            if (loggedOnUser)
            {
                uint error = NativeMethods.CredUIParseUserName(User.Name, usernameBldr, usernameBldr.Capacity, domainBldr, domainBldr.Capacity);
                if (error != 0)
                {
                    _sessionLogger.LogError(Resources.Error_UserNameParse, User.Name, error);
                    throw new ArgumentException(Resources.Error_UserNameParse.FormatInvariant(User.Name, error));
                }

                string username = usernameBldr.ToString();
                string domain   = domainBldr.ToString();

                eb = CreateEnvironmentBlockForUser(useridentity, username, profilePath);
            }
            else
            {
                eb = Win32EnvironmentBlock.Create((useridentity ?? WindowsIdentity.GetCurrent()).Token);
            }

            // add additional variables to the environment block
            eb["R_HOME"] = shortHome.ToString();
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "R_HOME", eb["R_HOME"]);
            eb["PATH"] = Invariant($"{Interpreter.Info.BinPath};{Environment.GetEnvironmentVariable("PATH")}");
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "PATH", eb["PATH"]);


            _sessionLogger.LogInformation(Resources.Info_StartingRHost, Id, User.Name, commandLine);
            using (Win32NativeEnvironmentBlock nativeEnv = eb.GetNativeEnvironmentBlock()) {
                if (loggedOnUser)
                {
                    _process = Win32Process.StartProcessAsUser(useridentity, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv, out stdin, out stdout, out stderror);
                }
                else
                {
                    _process = Win32Process.StartProcessAsUser(null, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv, out stdin, out stdout, out stderror);
                }
            }

            _process.Exited += delegate(object o, Win32ProcessExitEventArgs exitState){
                _hostEnd?.Dispose();
                _hostEnd = null;
                State    = SessionState.Terminated;
                if (exitState.HasError())
                {
                    _sessionLogger.LogInformation(Resources.Error_ExitRHost, exitState.ExitCode);
                }
            };

            _process.WaitForExit(250);
            if (_process.HasExited && _process.ExitCode < 0)
            {
                var message = ErrorCodeConverter.MessageFromErrorCode(_process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new Win32Exception(message);
                }
                throw new Win32Exception(_process.ExitCode);
            }

            _sessionLogger.LogInformation(Resources.Info_StartedRHost, Id, User.Name);

            var hostEnd = _pipe.ConnectHost(_process.ProcessId);

            _hostEnd = hostEnd;

            ClientToHostWorker(stdin, hostEnd).DoNotWait();
            HostToClientWorker(stdout, hostEnd).DoNotWait();

            HostToClientErrorWorker(stderror, _process.ProcessId, (int processid, string errdata) => {
                outputLogger?.LogTrace(Resources.Trace_ErrorDataReceived, processid, errdata);
            }).DoNotWait();
        }
 public IsolatedWin32Process(Win32Process process, AppContainerProfile appContainer)
 {
     _process      = process;
     _appContainer = appContainer;
     Process       = Process.GetProcessById(process.Pid);
 }
        /// <summary>
        /// Starts the process isolated.
        /// </summary>
        /// <param name="isolationIdentifier">Name identifier for the isolation. This has to be unique. Under windows this is the name of the AppContainerIsolator.</param>
        /// <param name="path">The path to the executable.</param>
        /// <param name="commandLineArguments">The command line arguments.</param>
        /// <param name="networkPermissions">The network permissions the process should have.</param>
        /// <param name="attachToCurrentProcess">
        /// If set to <c>true</c> the started process will be terminated when the current
        /// process exits.
        /// </param>
        /// <param name="fileAccess">The extended file access. Allows for custom file and folder access rights.</param>
        /// <param name="makeApplicationDirectoryReadable">
        /// By default the folder containing the executable will be made available to the process to allow loading dependencies.
        /// Set this to false to suppress this behaviour.
        /// </param>
        /// <param name="workingDirectory">
        /// The working directory of the process.
        /// </param>
        /// <returns>
        /// The process object. Needs to be disposed.
        /// </returns>
        /// <exception cref="ArgumentException">$"Couldn't resolve directory for '{path}'.</exception>
        public IIsolatedProcess StartIsolatedProcess(
            string isolationIdentifier,
            string path,
            string[]?commandLineArguments         = null,
            NetworkPermissions networkPermissions = NetworkPermissions.None,
            bool attachToCurrentProcess           = true,
            IEnumerable <FileAccess>?fileAccess   = null,
            bool makeApplicationDirectoryReadable = true,
            string?workingDirectory = null)
        {
            string applicationName = Path.GetFileNameWithoutExtension(path);

            var container = AppContainerProfile.Create(
                isolationIdentifier,
                $"{applicationName} Container ({isolationIdentifier})",
                $"Application container for {applicationName}");

            var config = new Win32ProcessConfig
            {
                ApplicationName = path,
                CommandLine     = commandLineArguments is not null?string.Join(" ", commandLineArguments) : string.Empty,
                                      ChildProcessMitigations = ChildProcessMitigationFlags.Restricted,
                                      AppContainerSid         = container.Sid,
                                      TerminateOnDispose      = true,
                                      CurrentDirectory        = workingDirectory is null ? null : Path.GetFullPath(workingDirectory),
            };

            // Allow the process to access it's own files.
            if (makeApplicationDirectoryReadable)
            {
                var appDirectory = Path.GetDirectoryName(path) ??
                                   throw new ArgumentException($"Couldn't resolve directory for '{path}'.");
                AllowFileAccess(container, appDirectory, FileAccessRights.GenericRead);
            }

            // Apply user folder and file permissions
            if (fileAccess is not null)
            {
                foreach (var cur in fileAccess)
                {
                    if (!Directory.Exists(cur.Path) && !File.Exists(cur.Path))
                    {
                        throw new ArgumentException($"The file or folder '{cur.Path}' does not exist.");
                    }

                    AllowFileAccess(
                        container,
                        cur.Path,
                        (FileAccessRights)cur.AccessRight);
                }
            }

            // Apply network networkPermissions
            if ((networkPermissions & NetworkPermissions.LocalNetwork) != 0)
            {
                config.AddCapability(KnownSids.CapabilityPrivateNetworkClientServer);
            }

            if ((networkPermissions & NetworkPermissions.Internet) != 0)
            {
                config.AddCapability(KnownSids.CapabilityInternetClient);
            }

            var process = Win32Process.CreateProcess(config);

            // Make sure the new process gets killed when the current process stops.
            if (attachToCurrentProcess)
            {
                _childProcessCascadeCloseJob.Value.AssignProcess(process.Process);
            }

            return(new IsolatedWin32Process(process, container));
        }
示例#21
0
        static void Main(string[] args)
        {
            //WmiProcess wip = new WmiProcess();
            //int i = 0;
            ////StreamWriter sw = new StreamWriter("d:/f.txt");
            ////Win32Processor a = new Win32Processor();
            Win32Process a = new Win32Process();

            uint aaa;

            a.Create(@"E:\广东\test\SSPTTest\SSPTTest\bin\Debug\SSPTTest.exe");
            // a.Create(@"E:\广东\test\SSPTTest\SSPTTest\bin\Debug\SSPTTest.exe", @"E:\广东\test\SSPTTest\SSPTTest\bin\Debug", out aaa);
            //Console.ReadKey();
            //WmiService ws = new WmiService();

            //a.dictionFamily = new Dictionary<ushort, string>();
            //a.dictionFamily.Add(1, "Other");
            //a.dictionFamily.Add(2, "Unknown");
            //a.dictionFamily.Add(3, "8086");
            //a.dictionFamily.Add(4, "80286");
            //a.dictionFamily.Add(5, "80386");
            //a.dictionFamily.Add(6, "80486");
            //a.dictionFamily.Add(7, "8087");
            //a.dictionFamily.Add(8, "80287");
            //a.dictionFamily.Add(9, "80387");
            //a.dictionFamily.Add(10, "80487");
            //a.dictionFamily.Add(11, "Pentium Family");
            //a.dictionFamily.Add(12, "Pentium Pro");
            //a.dictionFamily.Add(13, "Pentium II");
            //a.dictionFamily.Add(14, "Pentium MMX");
            //a.dictionFamily.Add(15, "Celeron");
            //a.dictionFamily.Add(16, "Pentium II Xeon");
            //a.dictionFamily.Add(17, "Pentium III");
            //a.dictionFamily.Add(18, "M1 Family");
            //a.dictionFamily.Add(19, "M2 Family");
            //a.dictionFamily.Add(25, "K5 Family");
            //a.dictionFamily.Add(26, "K6 Family");
            //a.dictionFamily.Add(27, "K6-2");
            //a.dictionFamily.Add(28, "K6-III");
            //a.dictionFamily.Add(29, "Athlon");
            //a.dictionFamily.Add(32, "Power PC Family");
            //a.dictionFamily.Add(33, "Power PC 601");
            //a.dictionFamily.Add(34, "Power PC 603");
            //a.dictionFamily.Add(35, "Power PC 603+");
            //a.dictionFamily.Add(36, "Power PC 604");
            //a.dictionFamily.Add(48, "Alpha Family");
            //a.dictionFamily.Add(64, "MIPS Family");
            //a.dictionFamily.Add(80, "SPARC Family");
            //a.dictionFamily.Add(96, "68040");
            //a.dictionFamily.Add(97, "68xxx Family");
            //a.dictionFamily.Add(98, "68000");
            //a.dictionFamily.Add(99, "68010");
            //a.dictionFamily.Add(100, "68020");
            //a.dictionFamily.Add(101, "68030");
            //a.dictionFamily.Add(112, "Hobbit Family");
            //a.dictionFamily.Add(128, "Weitek");
            //a.dictionFamily.Add(144, "PA-RISC Family");
            //a.dictionFamily.Add(160, "V30 Family");
            //a.dictionFamily.Add(176, "Pentium III Xeon");
            //a.dictionFamily.Add(180, "AS400 Family");
            //a.dictionFamily.Add(200, "IBM390 Family");
            //a.dictionFamily.Add(250, "i860");
            //a.dictionFamily.Add(251, "i960");
            //a.dictionFamily.Add(260, "SH-3");
            //a.dictionFamily.Add(261, "SH-4");
            //a.dictionFamily.Add(280, "ARM");
            //a.dictionFamily.Add(281, "StrongARM");
            //a.dictionFamily.Add(300, "6x86");
            //a.dictionFamily.Add(301, "MediaGX");
            //a.dictionFamily.Add(302, "MII");
            //a.dictionFamily.Add(320, "WinChip");

            //a.dictionUpgradeMethod = new Dictionary<ushort, string>();
            //a.dictionUpgradeMethod.Add(1, "Other");
            //a.dictionUpgradeMethod.Add(2, "Unknown");
            //a.dictionUpgradeMethod.Add(3, "Daughter board");
            //a.dictionUpgradeMethod.Add(4, "ZIF socket");
            //a.dictionUpgradeMethod.Add(5, "Replacement/piggy back");
            //a.dictionUpgradeMethod.Add(6, "None");
            //a.dictionUpgradeMethod.Add(7, "LIF socket");
            //a.dictionUpgradeMethod.Add(8, "Slot 1");
            //a.dictionUpgradeMethod.Add(9, "Slot 2");
            //a.dictionUpgradeMethod.Add(10, "370 Pin socket");
            //a.dictionUpgradeMethod.Add(11, "Slot A");
            //a.dictionUpgradeMethod.Add(12, "Slot M");
            // Emit(sw, a);
            // sw.WriteLine();
            //sw.Close();
        }