Пример #1
0
        public static void Delete(IWin32Window window, string service, bool prompt)
        {
            if (ElevateIfRequired(window, service, (ServiceAccess)StandardRights.Delete, "delete"))
            {
                return;
            }

            if (prompt && !Prompt(window, service, "delete",
                                  "Deleting a service can prevent the system from starting or functioning properly. " +
                                  "Are you sure you want to continue?", TaskDialogIcon.Warning))
            {
                return;
            }

            try
            {
                using (var shandle = new ServiceHandle(service, (ServiceAccess)StandardRights.Delete))
                    shandle.Delete();
            }
            catch (Exception ex)
            {
                DialogResult r = MessageBox.Show(window, "Could not delete the service \"" + service +
                                                 "\":\n\n" +
                                                 ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #2
0
        public void LoadService()
        {
            // Attempt to load the driver, then try again.
            ServiceHandle shandle;
            bool          created = false;

            try
            {
                using (shandle = new ServiceHandle(_deviceName, ServiceAccess.Start))
                {
                    shandle.Start();
                }
            }
            catch
            {
                using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                {
                    shandle = scm.CreateService(
                        _deviceName,
                        _deviceName,
                        ServiceType.KernelDriver,
                        Application.StartupPath + "\\kprocesshacker.sys"
                        );
                    shandle.Start();
                    created = true;
                }
            }

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + _deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            finally
            {
                if (created)
                {
                    // The SCM will delete the service when it is stopped.
                    shandle.Delete();
                }

                shandle.Dispose();
            }
        }
Пример #3
0
        public static void Delete(IWin32Window window, string service, bool prompt)
        {
            if (ElevateIfRequired(window, service, (ServiceAccess)StandardRights.Delete, "delete"))
                return;

            if (prompt && !Prompt(window, service, "delete",
                "Deleting a service can prevent the system from starting or functioning properly. " +
                "Are you sure you want to continue?", TaskDialogIcon.Warning))
                return;

            try
            {
                using (var shandle = new ServiceHandle(service, (ServiceAccess)StandardRights.Delete))
                    shandle.Delete();
            }
            catch (Exception ex)
            {
                DialogResult r = MessageBox.Show(window, "Could not delete the service \"" + service +
                    "\":\n\n" +
                    ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #4
0
        private static bool ProcessCommandLine(Dictionary<string, string> pArgs)
        {
            if (pArgs.ContainsKey("-assistant"))
            {
                Assistant.Main(pArgs);

                return true;
            }

            if (pArgs.ContainsKey("-e"))
            {
                try
                {
                    ExtendedCmd.Run(pArgs);
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to complete the operation", ex);
                }

                return true;
            }

            if (pArgs.ContainsKey("-installkph"))
            {
                try
                {
                    using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                    {
                        using (ServiceHandle shandle = scm.CreateService(
                            "KProcessHacker2",
                            "KProcessHacker2",
                            ServiceType.KernelDriver,
                            ServiceStartType.SystemStart,
                            ServiceErrorControl.Ignore,
                            Application.StartupPath + "\\kprocesshacker.sys",
                            null,
                            null,
                            null
                            ))
                        {
                            shandle.Start();
                        }
                    }
                }
                catch (WindowsException ex)
                {
                    // Need to pass status back.
                    Environment.Exit((int)ex.ErrorCode);
                }

                return true;
            }

            if (pArgs.ContainsKey("-uninstallkph"))
            {
                try
                {
                    using (ServiceHandle shandle = new ServiceHandle("KProcessHacker2", ServiceAccess.Stop | (ServiceAccess)StandardRights.Delete))
                    {
                        try { shandle.Control(ServiceControl.Stop); }
                        catch { }

                        shandle.Delete();
                    }
                }
                catch (WindowsException ex)
                {
                    // Need to pass status back.
                    Environment.Exit((int)ex.ErrorCode);
                }

                return true;
            }

            if (pArgs.ContainsKey("-ip"))
                InspectPid = int.Parse(pArgs["-ip"]);

            if (pArgs.ContainsKey("-pw"))
            {
                int pid = int.Parse(pArgs["-pw"]);

                PrimaryProviderThread = new ProviderThread(Settings.Instance.RefreshInterval);
                SecondaryProviderThread = new ProviderThread(Settings.Instance.RefreshInterval);

                ProcessProvider = new ProcessSystemProvider();
                ServiceProvider = new ServiceProvider();
                PrimaryProviderThread.Add(ProcessProvider);
                PrimaryProviderThread.Add(ServiceProvider);
                ProcessProvider.Boost();
                ServiceProvider.Boost();
                ProcessProvider.Enabled = true;
                ServiceProvider.Enabled = true;

                Win32.LoadLibrary(Settings.Instance.DbgHelpPath);

                if (!ProcessProvider.Dictionary.ContainsKey(pid))
                {
                    PhUtils.ShowError("The process (PID " + pid.ToString() + ") does not exist.");
                    Environment.Exit(0);
                    return true;
                }

                ProcessWindow pw = new ProcessWindow(ProcessProvider.Dictionary[pid]);

                Application.Run(pw);

                PrimaryProviderThread.Dispose();
                ProcessProvider.Dispose();
                ServiceProvider.Dispose();

                Environment.Exit(0);

                return true;
            }

            if (pArgs.ContainsKey("-pt"))
            {
                int pid = int.Parse(pArgs["-pt"]);

                try
                {
                    using (var phandle = new ProcessHandle(pid, Program.MinProcessQueryRights))
                        Application.Run(new TokenWindow(phandle));
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to show token properties", ex);
                }

                return true;
            }

            if (pArgs.ContainsKey("-o"))
            {
                OptionsWindow options = new OptionsWindow(true)
                {
                    StartPosition = FormStartPosition.CenterScreen
                };
                IWin32Window window;

                if (pArgs.ContainsKey("-hwnd"))
                    window = new WindowFromHandle(new IntPtr(int.Parse(pArgs["-hwnd"])));
                else
                    window = new WindowFromHandle(IntPtr.Zero);

                if (pArgs.ContainsKey("-rect"))
                {
                    Rectangle rect = Utils.GetRectangle(pArgs["-rect"]);

                    options.Location = new Point(rect.X + 20, rect.Y + 20);
                    options.StartPosition = FormStartPosition.Manual;
                }

                options.SelectedTab = options.TabPages["tabAdvanced"];
                options.ShowDialog(window);

                return true;
            }

            if (pArgs.ContainsKey(string.Empty))
                if (pArgs[string.Empty].Replace("\"", string.Empty).Trim().EndsWith("taskmgr.exe", StringComparison.OrdinalIgnoreCase))
                    StartVisible = true;

            if (pArgs.ContainsKey("-m"))
                StartHidden = true;
            if (pArgs.ContainsKey("-v"))
                StartVisible = true;

            if (pArgs.ContainsKey("-a"))
            {
                try { Unhook(); }
                catch { }
                try { NProcessHacker.KphHookInit(); }
                catch { }
            }

            if (pArgs.ContainsKey("-t"))
            {
                if (pArgs["-t"] == "0")
                    SelectTab = "Processes";
                else if (pArgs["-t"] == "1")
                    SelectTab = "Services";
                else if (pArgs["-t"] == "2")
                    SelectTab = "Network";
            }

            return false;
        }
Пример #5
0
        public void LoadService()
        {
            // Attempt to load the driver, then try again.
            ServiceHandle shandle;
            bool created = false;

            try
            {
                using (shandle = new ServiceHandle(_deviceName, ServiceAccess.Start))
                {
                    shandle.Start();
                }
            }
            catch
            {
                using (ServiceManagerHandle scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                {
                    shandle = scm.CreateService(
                        _deviceName,
                        _deviceName,
                        ServiceType.KernelDriver,
                        Application.StartupPath + "\\kprocesshacker.sys"
                        );
                    shandle.Start();
                    created = true;
                }
            }

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + _deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            finally
            {
                if (created)
                {
                    // The SCM will delete the service when it is stopped.
                    shandle.Delete();
                }

                shandle.Dispose();
            }
        }
Пример #6
0
        public KProcessHacker(string deviceName, string fileName)
        {
            _deviceName = deviceName;

            if (IntPtr.Size != 4)
                throw new NotSupportedException("KProcessHacker does not support 64-bit Windows.");

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            catch (WindowsException ex)
            {
                if (
                    ex.Status == NtStatus.NoSuchDevice ||
                    ex.Status == NtStatus.NoSuchFile ||
                    ex.Status == NtStatus.ObjectNameNotFound
                    )
                {

                    ServiceHandle shandle;
                    bool created = false;

                    try
                    {
                        using (shandle = new ServiceHandle("KProcessHacker", ServiceAccess.Start))
                        {
                            shandle.Start();
                        }
                    }
                    catch
                    {
                        using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                        {
                            shandle = scm.CreateService(
                                deviceName,
                                deviceName,
                                ServiceType.KernelDriver,
                                fileName
                                );
                            shandle.Start();
                            created = true;
                        }
                    }

                    try
                    {
                        _fileHandle = new FileHandle(
                            @"\Device\" + deviceName,
                            0,
                            FileAccess.GenericRead | FileAccess.GenericWrite
                            );
                    }
                    finally
                    {
                        if (shandle != null)
                        {
                            if (created)
                            {

                                shandle.Delete();
                            }

                            shandle.Dispose();
                        }
                    }
                }
                else
                {
                    throw ex;
                }
            }

            _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose);

            byte[] bytes = _fileHandle.Read(4);

            fixed (byte* bytesPtr = bytes)
                _baseControlNumber = *(uint*)bytesPtr;

            try
            {
                _features = this.GetFeatures();
            }
            catch
            { }
        }
Пример #7
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();

            try
            {
                Assistant.SetDesktopWinStaAccess();
            }
            catch
            { }

            try
            {
                bool omitUserAndType = false;

                if (_pid != -1)
                {
                    omitUserAndType = true;
                }

                string mailslotName = "ProcessHackerAssistant" + Utils.CreateRandomString(8);

                string binPath = "\"" + Application.ExecutablePath + "\" -assistant " +
                                 (omitUserAndType ? string.Empty : ("-u \"" + this.comboUsername.Text + "\" -t " + this.comboType.SelectedItem.ToString().ToLowerInvariant() + " ")) +
                                 (this._pid != -1 ? ("-P " + this._pid.ToString() + " ") : string.Empty) + "-p \"" +
                                 this.textPassword.Text.Replace("\"", "\\\"") + "\" -s " + this.textSessionID.Text + " -c \"" +
                                 this.textCmdLine.Text.Replace("\"", "\\\"") + "\" -E " + mailslotName;

                if (Program.ElevationType == TokenElevationType.Limited)
                {
                    var result = Program.StartProcessHackerAdminWait(
                        "-e -type processhacker -action runas -obj \"" + binPath.Replace("\"", "\\\"") +
                        "\" -mailslot " + mailslotName +
                        " -hwnd " + this.Handle.ToString(), this.Handle, 5000);

                    if (result == WaitResult.Object0)
                    {
                        this.Close();
                    }
                }
                else
                {
                    string serviceName = Utils.CreateRandomString(8);

                    using (ServiceManagerHandle manager = new ServiceManagerHandle(ScManagerAccess.CreateService))
                        using (ServiceHandle service = manager.CreateService(
                                   serviceName,
                                   serviceName + " (Process Hacker Assistant)",
                                   ServiceType.Win32OwnProcess,
                                   ServiceStartType.DemandStart,
                                   ServiceErrorControl.Ignore,
                                   binPath,
                                   string.Empty,
                                   "LocalSystem",
                                   null
                                   ))
                        {
                            // Create a mailslot so we can receive the error code for Assistant.
                            using (MailslotHandle mhandle = MailslotHandle.Create(FileAccess.GenericRead, @"\Device\Mailslot\" + mailslotName, 0, 5000))
                            {
                                try
                                {
                                    service.Start();
                                }
                                catch { }

                                service.Delete();

                                Win32Error errorCode = (Win32Error)mhandle.Read(4).ToInt32();

                                if (errorCode != Win32Error.Success)
                                {
                                    throw new WindowsException(errorCode);
                                }
                            }
                        }


                    this.Close();
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to start the program", ex);
            }

            this.Cursor = Cursors.Default;
        }
Пример #8
0
        /// <summary>
        /// Creates a connection to KProcessHacker.
        /// </summary>
        /// <param name="deviceName">The name of the KProcessHacker service and device.</param>
        /// <param name="fileName">The file name of the KProcessHacker driver.</param>
        public KProcessHacker(string deviceName, string fileName)
        {
            _deviceName = deviceName;

            if (IntPtr.Size != 4)
            {
                throw new NotSupportedException("KProcessHacker does not support 64-bit Windows.");
            }

            try
            {
                _fileHandle = new FileHandle(
                    @"\Device\" + deviceName,
                    0,
                    FileAccess.GenericRead | FileAccess.GenericWrite
                    );
            }
            catch (WindowsException ex)
            {
                if (
                    ex.Status == NtStatus.NoSuchDevice ||
                    ex.Status == NtStatus.NoSuchFile ||
                    ex.Status == NtStatus.ObjectNameNotFound
                    )
                {
                    // Attempt to load the driver, then try again.
                    ServiceHandle shandle;
                    bool          created = false;

                    try
                    {
                        using (shandle = new ServiceHandle("KProcessHacker", ServiceAccess.Start))
                        {
                            shandle.Start();
                        }
                    }
                    catch
                    {
                        using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                        {
                            shandle = scm.CreateService(
                                deviceName,
                                deviceName,
                                ServiceType.KernelDriver,
                                fileName
                                );
                            shandle.Start();
                            created = true;
                        }
                    }

                    try
                    {
                        _fileHandle = new FileHandle(
                            @"\Device\" + deviceName,
                            0,
                            FileAccess.GenericRead | FileAccess.GenericWrite
                            );
                    }
                    finally
                    {
                        if (shandle != null)
                        {
                            if (created)
                            {
                                // The SCM will delete the service when it is stopped.
                                shandle.Delete();
                            }

                            shandle.Dispose();
                        }
                    }
                }
                else
                {
                    throw ex;
                }
            }

            _fileHandle.SetHandleFlags(Win32HandleFlags.ProtectFromClose, Win32HandleFlags.ProtectFromClose);

            byte[] bytes = _fileHandle.Read(4);

            fixed(byte *bytesPtr = bytes)
            _baseControlNumber = *(uint *)bytesPtr;

            try
            {
                _features = this.GetFeatures();
            }
            catch
            { }
        }