/// <summary>
            /// Creates a new service handle.
            /// </summary>
            /// <param name="ServiceName">The name of the service to open.</param>
            /// <param name="access">The desired access to the service.</param>
            public ServiceHandle(string ServiceName, SERVICE_RIGHTS access)
            {
                using (ServiceManagerHandle manager =
                           new ServiceManagerHandle(SC_MANAGER_RIGHTS.SC_MANAGER_CONNECT))
                {
                    this.Handle = OpenService(manager, ServiceName, access);

                    if (this.Handle == 0)
                    {
                        ThrowLastWin32Error();
                    }
                }
            }
Beispiel #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();
            }
        }
Beispiel #3
0
        /// <summary>
        /// Gets a dictionary containing the services on the system.
        /// </summary>
        /// <returns>A dictionary, indexed by service name.</returns>
        public static Dictionary <string, EnumServiceStatusProcess> GetServices()
        {
            using (ServiceManagerHandle manager =
                       new ServiceManagerHandle(ScManagerAccess.EnumerateService))
            {
                int requiredSize;
                int servicesReturned;
                int resume = 0;

                if (_servicesBuffer == null)
                {
                    _servicesBuffer = new MemoryAlloc(0x10000);
                }

                MemoryAlloc data = _servicesBuffer;

                if (!Win32.EnumServicesStatusEx(manager, IntPtr.Zero, ServiceQueryType.Win32 | ServiceQueryType.Driver,
                                                ServiceQueryState.All, data,
                                                data.Size, out requiredSize, out servicesReturned,
                                                ref resume, null))
                {
                    // resize buffer
                    data.ResizeNew(requiredSize);

                    if (!Win32.EnumServicesStatusEx(manager, IntPtr.Zero, ServiceQueryType.Win32 | ServiceQueryType.Driver,
                                                    ServiceQueryState.All, data,
                                                    data.Size, out requiredSize, out servicesReturned,
                                                    ref resume, null))
                    {
                        Win32.Throw();
                    }
                }

                var dictionary = new Dictionary <string, EnumServiceStatusProcess>(servicesReturned);

                for (int i = 0; i < servicesReturned; i++)
                {
                    var service = data.ReadStruct <EnumServiceStatusProcess>(i);

                    dictionary.Add(service.ServiceName, service);
                }

                return(dictionary);
            }
        }
Beispiel #4
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            try
            {
                using (ServiceManagerHandle scmhandle = new ServiceManagerHandle(ScManagerAccess.CreateService))
                {
                    ServiceType serviceType;

                    if (comboType.SelectedItem.ToString() == "Win32OwnProcess, InteractiveProcess")
                    {
                        serviceType = ServiceType.Win32OwnProcess |
                                      ServiceType.InteractiveProcess;
                    }
                    else
                    {
                        serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), comboType.SelectedItem.ToString());
                    }

                    var startType = (ServiceStartType)
                                    Enum.Parse(typeof(ServiceStartType), comboStartType.SelectedItem.ToString());
                    var errorControl = (ServiceErrorControl)
                                       Enum.Parse(typeof(ServiceErrorControl), comboErrorControl.SelectedItem.ToString());

                    scmhandle.CreateService(
                        textName.Text,
                        textDisplayName.Text,
                        serviceType,
                        startType,
                        errorControl,
                        textBinaryPath.Text,
                        null,
                        null,
                        null
                        ).Dispose();
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to create the service", ex);
            }
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            try
            {
                using (var scmhandle = new ServiceManagerHandle(ScManagerAccess.CreateService))
                {
                    ServiceType serviceType;

                    if (comboType.SelectedItem.ToString() == "Win32OwnProcess, InteractiveProcess")
                        serviceType = ServiceType.Win32OwnProcess |
                            ServiceType.InteractiveProcess;
                    else
                        serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), comboType.SelectedItem.ToString());

                    var startType = (ServiceStartType)
                        Enum.Parse(typeof(ServiceStartType), comboStartType.SelectedItem.ToString());
                    var errorControl = (ServiceErrorControl)
                        Enum.Parse(typeof(ServiceErrorControl), comboErrorControl.SelectedItem.ToString());

                    scmhandle.CreateService(
                        textName.Text,
                        textDisplayName.Text,
                        serviceType,
                        startType,
                        errorControl,
                        textBinaryPath.Text,
                        null,
                        null,
                        null
                        ).Dispose();
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                PhUtils.ShowException("Unable to create the service", ex);
            }
        }
Beispiel #6
0
        public static void Run(IDictionary<string, string> args)
        {
            try
            {
                ThemingScope.Activate();
            }
            catch
            { }

            if (!args.ContainsKey("-type"))
                throw new Exception("-type switch required.");

            string type = args["-type"].ToLower();

            if (!args.ContainsKey("-obj"))
                throw new Exception("-obj switch required.");

            string obj = args["-obj"];

            if (!args.ContainsKey("-action"))
                throw new Exception("-action switch required.");

            string action = args["-action"].ToLower();

            WindowFromHandle window = new WindowFromHandle(IntPtr.Zero);

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

            try
            {
                switch (type)
                {
                    case "processhacker":
                        {
                            switch (action)
                            {
                                case "runas":
                                    {
                                        using (var manager = new ServiceManagerHandle(ScManagerAccess.CreateService))
                                        {
                                            Random r = new Random((int)(DateTime.Now.ToFileTime() & 0xffffffff));
                                            string serviceName = "";

                                            for (int i = 0; i < 8; i++)
                                                serviceName += (char)('A' + r.Next(25));

                                            using (var service = manager.CreateService(
                                                serviceName,
                                                serviceName + " (Process Hacker Assistant)",
                                                ServiceType.Win32OwnProcess,
                                                ServiceStartType.DemandStart,
                                                ServiceErrorControl.Ignore,
                                                obj,
                                                "",
                                                "LocalSystem",
                                                null))
                                            { 
                                                // Create a mailslot so we can receive the error code for Assistant.
                                                using (var mhandle = MailslotHandle.Create(
                                                    FileAccess.GenericRead, @"\Device\Mailslot\" + args["-mailslot"], 0, 5000)
                                                    )
                                                {
                                                    try { service.Start(); }
                                                    catch { }
                                                    service.Delete();

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

                                                    if (errorCode != Win32Error.Success)
                                                        throw new WindowsException(errorCode);
                                                }
                                            }
                                        }
                                    }
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    case "process":
                        {
                            var processes = Windows.GetProcesses();
                            string[] pidStrings = obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            int[] pids = new int[pidStrings.Length];
                            string[] names = new string[pidStrings.Length];

                            for (int i = 0; i < pidStrings.Length; i++)
                            {
                                pids[i] = int.Parse(pidStrings[i]);
                                names[i] = processes[pids[i]].Name;
                            }

                            switch (action)
                            {
                                case "terminate":
                                    ProcessActions.Terminate(window, pids, names, true);
                                    break;
                                case "suspend":
                                    ProcessActions.Suspend(window, pids, names, true);
                                    break;
                                case "resume":
                                    ProcessActions.Resume(window, pids, names, true);
                                    break;
                                case "reduceworkingset":
                                    ProcessActions.ReduceWorkingSet(window, pids, names, false);
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    case "thread":
                        {
                            foreach (string tid in obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                switch (action)
                                {
                                    case "terminate":
                                        {
                                            try
                                            {
                                                using (var thandle =
                                                    new ThreadHandle(int.Parse(tid), ThreadAccess.Terminate))
                                                    thandle.Terminate();
                                            }
                                            catch (Exception ex)
                                            {
                                                DialogResult result = MessageBox.Show(window,
                                                    "Could not terminate thread with ID " + tid + ":\n\n" +
                                                    ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                                if (result == DialogResult.Cancel)
                                                    return;
                                            }
                                        }
                                        break;
                                    case "suspend":
                                        {
                                            try
                                            {
                                                using (var thandle =
                                                    new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                                    thandle.Suspend();
                                            }
                                            catch (Exception ex)
                                            {
                                                DialogResult result = MessageBox.Show(window,
                                                    "Could not suspend thread with ID " + tid + ":\n\n" +
                                                    ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                                if (result == DialogResult.Cancel)
                                                    return;
                                            }
                                        }
                                        break;
                                    case "resume":
                                        {
                                            try
                                            {
                                                using (var thandle =
                                                    new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                                    thandle.Resume();
                                            }
                                            catch (Exception ex)
                                            {
                                                DialogResult result = MessageBox.Show(window,
                                                    "Could not resume thread with ID " + tid + ":\n\n" +
                                                    ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                                if (result == DialogResult.Cancel)
                                                    return;
                                            }
                                        }
                                        break;
                                    default:
                                        throw new Exception("Unknown action '" + action + "'");
                                }
                            }
                        }
                        break;

                    case "service":
                        {
                            switch (action)
                            {
                                case "start":
                                    {
                                        ServiceActions.Start(window, obj, false);
                                    }
                                    break;
                                case "continue":
                                    {
                                        ServiceActions.Continue(window, obj, false);
                                    }
                                    break;
                                case "pause":
                                    {
                                        ServiceActions.Pause(window, obj, false);
                                    }
                                    break;
                                case "stop":
                                    {
                                        ServiceActions.Stop(window, obj, false);
                                    }
                                    break;
                                case "delete":
                                    {
                                        ServiceActions.Delete(window, obj, true);
                                    }
                                    break;
                                case "config":
                                    {
                                        using (ServiceHandle service = new ServiceHandle(obj, ServiceAccess.ChangeConfig))
                                        {
                                            ServiceType serviceType;

                                            if (args["-servicetype"] == "Win32OwnProcess, InteractiveProcess")
                                                serviceType = ServiceType.Win32OwnProcess | ServiceType.InteractiveProcess;
                                            else if (args["-servicetype"] == "Win32ShareProcess, InteractiveProcess")
                                                serviceType = ServiceType.Win32ShareProcess | ServiceType.InteractiveProcess;
                                            else
                                                serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), args["-servicetype"]);

                                            var startType = (ServiceStartType)
                                                Enum.Parse(typeof(ServiceStartType), args["-servicestarttype"]);
                                            var errorControl = (ServiceErrorControl)
                                                Enum.Parse(typeof(ServiceErrorControl), args["-serviceerrorcontrol"]);

                                            string binaryPath = null;
                                            string loadOrderGroup = null;
                                            string userAccount = null;
                                            string password = null;

                                            if (args.ContainsKey("-servicebinarypath"))
                                                binaryPath = args["-servicebinarypath"];
                                            if (args.ContainsKey("-serviceloadordergroup"))
                                                loadOrderGroup = args["-serviceloadordergroup"];
                                            if (args.ContainsKey("-serviceuseraccount"))
                                                userAccount = args["-serviceuseraccount"];
                                            if (args.ContainsKey("-servicepassword"))
                                                password = args["-servicepassword"];

                                            if (!Win32.ChangeServiceConfig(service,
                                                serviceType, startType, errorControl,
                                                binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null))
                                                Win32.ThrowLastError();
                                        }
                                    }
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    case "session":
                        {
                            int sessionId = int.Parse(obj);

                            switch (action)
                            {
                                case "disconnect":
                                    {
                                        SessionActions.Disconnect(window, sessionId, false);
                                    }
                                    break;
                                case "logoff":
                                    {
                                        SessionActions.Logoff(window, sessionId, false);
                                    }
                                    break;
                                default:
                                    throw new Exception("Unknown action '" + action + "'");
                            }
                        }
                        break;

                    default:
                        throw new Exception("Unknown object type '" + type + "'");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(window, ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #7
0
        public static void Run(IDictionary <string, string> args)
        {
            try
            {
                ThemingScope.Activate();
            }
            catch
            { }

            if (!args.ContainsKey("-type"))
            {
                throw new Exception("-type switch required.");
            }

            string type = args["-type"].ToLowerInvariant();

            if (!args.ContainsKey("-obj"))
            {
                throw new Exception("-obj switch required.");
            }

            string obj = args["-obj"];

            if (!args.ContainsKey("-action"))
            {
                throw new Exception("-action switch required.");
            }

            string action = args["-action"].ToLowerInvariant();

            WindowFromHandle window = new WindowFromHandle(IntPtr.Zero);

            if (args.ContainsKey("-hwnd"))
            {
                window = new WindowFromHandle(new IntPtr(int.Parse(args["-hwnd"])));
            }

            try
            {
                switch (type)
                {
                case "processhacker":
                {
                    switch (action)
                    {
                    case "runas":
                    {
                        using (var manager = new ServiceManagerHandle(ScManagerAccess.CreateService))
                        {
                            Random r           = new Random((int)(DateTime.Now.ToFileTime() & 0xffffffff));
                            string serviceName = "";

                            for (int i = 0; i < 8; i++)
                            {
                                serviceName += (char)('A' + r.Next(25));
                            }

                            using (var service = manager.CreateService(
                                       serviceName,
                                       serviceName + " (Process Hacker Assistant)",
                                       ServiceType.Win32OwnProcess,
                                       ServiceStartType.DemandStart,
                                       ServiceErrorControl.Ignore,
                                       obj,
                                       "",
                                       "LocalSystem",
                                       null))
                            {
                                // Create a mailslot so we can receive the error code for Assistant.
                                using (var mhandle = MailslotHandle.Create(
                                           FileAccess.GenericRead, @"\Device\Mailslot\" + args["-mailslot"], 0, 5000)
                                       )
                                {
                                    try { service.Start(); }
                                    catch { }
                                    service.Delete();

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

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

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                case "process":
                {
                    var      processes  = Windows.GetProcesses();
                    string[] pidStrings = obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    int[]    pids       = new int[pidStrings.Length];
                    string[] names      = new string[pidStrings.Length];

                    for (int i = 0; i < pidStrings.Length; i++)
                    {
                        pids[i]  = int.Parse(pidStrings[i]);
                        names[i] = processes[pids[i]].Name;
                    }

                    switch (action)
                    {
                    case "terminate":
                        ProcessActions.Terminate(window, pids, names, true);
                        break;

                    case "suspend":
                        ProcessActions.Suspend(window, pids, names, true);
                        break;

                    case "resume":
                        ProcessActions.Resume(window, pids, names, true);
                        break;

                    case "reduceworkingset":
                        ProcessActions.ReduceWorkingSet(window, pids, names, false);
                        break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                case "thread":
                {
                    foreach (string tid in obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        switch (action)
                        {
                        case "terminate":
                        {
                            try
                            {
                                using (var thandle =
                                           new ThreadHandle(int.Parse(tid), ThreadAccess.Terminate))
                                    thandle.Terminate();
                            }
                            catch (Exception ex)
                            {
                                DialogResult result = MessageBox.Show(window,
                                                                      "Could not terminate thread with ID " + tid + ":\n\n" +
                                                                      ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                if (result == DialogResult.Cancel)
                                {
                                    return;
                                }
                            }
                        }
                        break;

                        case "suspend":
                        {
                            try
                            {
                                using (var thandle =
                                           new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                    thandle.Suspend();
                            }
                            catch (Exception ex)
                            {
                                DialogResult result = MessageBox.Show(window,
                                                                      "Could not suspend thread with ID " + tid + ":\n\n" +
                                                                      ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                if (result == DialogResult.Cancel)
                                {
                                    return;
                                }
                            }
                        }
                        break;

                        case "resume":
                        {
                            try
                            {
                                using (var thandle =
                                           new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                    thandle.Resume();
                            }
                            catch (Exception ex)
                            {
                                DialogResult result = MessageBox.Show(window,
                                                                      "Could not resume thread with ID " + tid + ":\n\n" +
                                                                      ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                if (result == DialogResult.Cancel)
                                {
                                    return;
                                }
                            }
                        }
                        break;

                        default:
                            throw new Exception("Unknown action '" + action + "'");
                        }
                    }
                }
                break;

                case "service":
                {
                    switch (action)
                    {
                    case "start":
                    {
                        ServiceActions.Start(window, obj, false);
                    }
                    break;

                    case "continue":
                    {
                        ServiceActions.Continue(window, obj, false);
                    }
                    break;

                    case "pause":
                    {
                        ServiceActions.Pause(window, obj, false);
                    }
                    break;

                    case "stop":
                    {
                        ServiceActions.Stop(window, obj, false);
                    }
                    break;

                    case "delete":
                    {
                        ServiceActions.Delete(window, obj, true);
                    }
                    break;

                    case "config":
                    {
                        using (ServiceHandle service = new ServiceHandle(obj, ServiceAccess.ChangeConfig))
                        {
                            ServiceType serviceType;

                            if (args["-servicetype"] == "Win32OwnProcess, InteractiveProcess")
                            {
                                serviceType = ServiceType.Win32OwnProcess | ServiceType.InteractiveProcess;
                            }
                            else if (args["-servicetype"] == "Win32ShareProcess, InteractiveProcess")
                            {
                                serviceType = ServiceType.Win32ShareProcess | ServiceType.InteractiveProcess;
                            }
                            else
                            {
                                serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), args["-servicetype"]);
                            }

                            var startType = (ServiceStartType)
                                            Enum.Parse(typeof(ServiceStartType), args["-servicestarttype"]);
                            var errorControl = (ServiceErrorControl)
                                               Enum.Parse(typeof(ServiceErrorControl), args["-serviceerrorcontrol"]);

                            string binaryPath     = null;
                            string loadOrderGroup = null;
                            string userAccount    = null;
                            string password       = null;

                            if (args.ContainsKey("-servicebinarypath"))
                            {
                                binaryPath = args["-servicebinarypath"];
                            }
                            if (args.ContainsKey("-serviceloadordergroup"))
                            {
                                loadOrderGroup = args["-serviceloadordergroup"];
                            }
                            if (args.ContainsKey("-serviceuseraccount"))
                            {
                                userAccount = args["-serviceuseraccount"];
                            }
                            if (args.ContainsKey("-servicepassword"))
                            {
                                password = args["-servicepassword"];
                            }

                            if (!Win32.ChangeServiceConfig(service,
                                                           serviceType, startType, errorControl,
                                                           binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null))
                            {
                                Win32.Throw();
                            }
                        }
                    }
                    break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                case "session":
                {
                    int sessionId = int.Parse(obj);

                    switch (action)
                    {
                    case "disconnect":
                    {
                        SessionActions.Disconnect(window, sessionId, false);
                    }
                    break;

                    case "logoff":
                    {
                        SessionActions.Logoff(window, sessionId, false);
                    }
                    break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                default:
                    throw new Exception("Unknown object type '" + type + "'");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(window, ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        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;

                    using (var scm = new ServiceManagerHandle(ScManagerAccess.CreateService))
                    {
                        shandle = scm.CreateService(
                            deviceName,
                            deviceName,
                            ServiceType.KernelDriver,
                            fileName
                            );
                        shandle.Start();
                    }

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

                        shandle.Delete();
                    }
                }
                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
            { }
        }
Beispiel #9
0
		internal static bool ContinueService(ServiceManagerHandle smhandle, string serviceName)
		{
			IntPtr srvHandle = OpenService(smhandle.Handle, serviceName, SERVICE_PAUSE_CONTINUE);
			CheckHandleAndThrowLastError(srvHandle);

			ServiceStatus status = new ServiceStatus();
			if (!ControlService(srvHandle, SERVICE_CONTROL_CONTINUE, ref status))
			{
				ThrowLastError();
			}

			CloseServiceHandle(srvHandle);
			return true;
		}
        /// <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 (OSVersion.Architecture != OSArch.I386)
                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
            { }
        }
Beispiel #11
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
            { }
        }
Beispiel #12
0
        /// <summary>
        /// Gets a dictionary containing the services on the system.
        /// </summary>
        /// <returns>A dictionary, indexed by service name.</returns>
        public static Dictionary<string, EnumServiceStatusProcess> GetServices()
        {
            using (ServiceManagerHandle manager = new ServiceManagerHandle(ScManagerAccess.EnumerateService))
            {
                int requiredSize;
                int servicesReturned;
                int resume = 0;

                if (_servicesBuffer == null)
                    _servicesBuffer = new MemoryAlloc(0x10000);

                MemoryAlloc data = _servicesBuffer;

                if (!Win32.EnumServicesStatusEx(manager, IntPtr.Zero, ServiceQueryType.Win32 | ServiceQueryType.Driver,
                    ServiceQueryState.All, data, data.Size, out requiredSize, out servicesReturned, ref resume, null))
                {
                    // resize buffer
                    data.ResizeNew(requiredSize);

                    if (!Win32.EnumServicesStatusEx(manager, IntPtr.Zero, ServiceQueryType.Win32 | ServiceQueryType.Driver,
                        ServiceQueryState.All, data, data.Size, out requiredSize, out servicesReturned, ref resume, null))
                        Win32.Throw();
                }

                Dictionary<string, EnumServiceStatusProcess> dictionary = new Dictionary<string, EnumServiceStatusProcess>(servicesReturned);

                for (int i = 0; i < servicesReturned; i++)
                {
                    EnumServiceStatusProcess service = data.ReadStruct<EnumServiceStatusProcess>(0, EnumServiceStatusProcess.SizeOf, i);

                    dictionary.Add(service.ServiceName, service);
                }

                return dictionary;
            }
        }
Beispiel #13
0
		internal static bool UnInstallService(ServiceManagerHandle smHandle, string svcName)
		{
			if (GetServiceState(smHandle, svcName) != ServiceState.STOPPED)
			{
				StopService(smHandle, svcName);
			}

			IntPtr srvHandle = OpenService(smHandle.Handle, svcName, SERVICE_DELETE);
			CheckHandleAndThrowLastError(srvHandle);

			bool result = DeleteService(srvHandle);
			CloseServiceHandle(srvHandle);
			return result;
		}
Beispiel #14
0
		internal static bool SetServiceDescription(ServiceManagerHandle smhandle, string serviceName, string description)
		{
			IntPtr srvHandle = OpenService(smhandle.Handle, serviceName, SERVICE_START | SERVICE_CHANGE_CONFIG);
			CheckHandleAndThrowLastError(srvHandle);

			ServiceDescription sd = new ServiceDescription();
			sd.Description = description;

			bool result = ChangeServiceConfig2(srvHandle, SERVICE_CONFIG_DESCRIPTION, ref sd);
			if (!result)
			{
				ThrowLastError();
			}
			CloseServiceHandle(srvHandle);
			return result;
		}
Beispiel #15
0
		internal static void InstallService(ServiceManagerHandle smHandle, string svcPath, string svcName, string svcDispName, string svcUserName, string svcPassword, bool autoStart, string[] dependencies)
		{
			StringBuilder dependenciesBuilder = new StringBuilder();
			if (dependencies != null)
			{
				for (int i = 0; i < dependencies.Length; i++)
				{
					dependenciesBuilder.Append(dependencies[i]);
					dependenciesBuilder.Append('\0');
				}
			}
			else
			{
				dependenciesBuilder.Append('\0');
			}

			IntPtr srvHandle = CreateService(
				smHandle.Handle,
				svcName,
				svcDispName,
				SERVICE_ALL_ACCESS,
				SERVICE_WIN32_OWN_PROCESS,
				autoStart ? SERVICE_AUTO_START : SERVICE_DEMAND_START,
				SERVICE_ERROR_NORMAL,
				svcPath,
				null,
				0,
				dependenciesBuilder.ToString(),
				svcUserName,
				svcPassword);

			CheckHandleAndThrowLastError(srvHandle);
			CloseServiceHandle(srvHandle);
		}
Beispiel #16
0
		internal static bool ServiceExists(ServiceManagerHandle smHandle, string serviceName)
		{
			IntPtr srvHandle = OpenService(smHandle.Handle, serviceName, SERVICE_QUERY_STATUS);
			if (srvHandle.ToInt32() != 0)
			{
				CloseServiceHandle(srvHandle);
				return true;
			}
			return false;
		}
Beispiel #17
0
		internal static ServiceState GetServiceState(ServiceManagerHandle smHandle, string serviceName)
		{
			IntPtr srvHandle = OpenService(smHandle.Handle, serviceName, SERVICE_QUERY_STATUS);
			CheckHandleAndThrowLastError(srvHandle);

			ServiceStatus status = new ServiceStatus();
			if (!QueryServiceStatus(srvHandle, ref status))
			{
				ThrowLastError();
			}

			CloseServiceHandle(srvHandle);

			return status.dwCurrentState;
		}
Beispiel #18
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;
        }
        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();
            }
        }
Beispiel #20
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();

            try
            {
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

                info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                info.FileName    = Application.StartupPath + "\\Assistant.exe";
                info.Arguments   = "-w";

                System.Diagnostics.Process.Start(info);
            }
            catch
            { }

            try
            {
                string binPath;
                string mailslotName;
                bool   omitUserAndType = false;

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

                mailslotName = "ProcessHackerAssistant" + Utils.CreateRandomString(8);
                binPath      = "\"" + Application.StartupPath + "\\Assistant.exe\" " +
                               (omitUserAndType ? "" :
                                ("-u \"" + comboUsername.Text + "\" -t " + comboType.SelectedItem.ToString().ToLower() + " ")) +
                               (_pid != -1 ? ("-P " + _pid.ToString() + " ") : "") + "-p \"" +
                               textPassword.Text.Replace("\"", "\\\"") + "\" -s " + textSessionID.Text + " -c \"" +
                               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 (var manager = new ServiceManagerHandle(ScManagerAccess.CreateService))
                    {
                        using (var service = manager.CreateService(
                                   serviceName,
                                   serviceName + " (Process Hacker Assistant)",
                                   ServiceType.Win32OwnProcess,
                                   ServiceStartType.DemandStart,
                                   ServiceErrorControl.Ignore,
                                   binPath,
                                   "",
                                   "LocalSystem",
                                   null))
                        {
                            // Create a mailslot so we can receive the error code for Assistant.
                            using (var 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;
        }
Beispiel #21
0
		internal static void CloseServiceManagerHandle(ServiceManagerHandle scHandle)
		{
			CloseServiceHandle(scHandle.Handle);
		}
        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;
        }
Beispiel #23
0
		internal static bool StartService(ServiceManagerHandle smhandle, string serviceName)
		{
			IntPtr srvHandle = OpenService(smhandle.Handle, serviceName, SERVICE_START);
			CheckHandleAndThrowLastError(srvHandle);

			bool result = StartService(srvHandle, 0, null);
			CloseServiceHandle(srvHandle);

			return result;
		}