Ejemplo n.º 1
0
 public void OpenCloseSCManager()
 {
     using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
     {
         AssertHandleIsValid(scm);
     }
 }
Ejemplo n.º 2
0
        public bool Delete()
        {
            IntPtr manager = AdvApi32.OpenSCManager(null, null, AdvApi32.SC_MANAGER_ACCESS_MASK.SC_MANAGER_ALL_ACCESS);

            if (manager == IntPtr.Zero)
            {
                return(false);
            }


            IntPtr service = AdvApi32.OpenService(manager, _id, AdvApi32.SERVICE_ACCESS_MASK.SERVICE_ALL_ACCESS);

            if (service == IntPtr.Zero)
            {
                return(true);
            }


            AdvApi32.SERVICE_STATUS status = new AdvApi32.SERVICE_STATUS();
            AdvApi32.ControlService(service, AdvApi32.SERVICE_CONTROL.SERVICE_CONTROL_STOP, ref status);
            AdvApi32.DeleteService(service);
            AdvApi32.CloseServiceHandle(service);
            AdvApi32.CloseServiceHandle(manager);

            return(true);
        }
Ejemplo n.º 3
0
        public static bool DeleteService(string serviceName)
        // Marks the specified service for deletion from
        // the service control manager database
        {
            Trace.WriteLine(
                "Deleting service: \'" + serviceName + "\'"
                );

            IntPtr scManagerHandle = AdvApi32.OpenSCManager(
                null,
                null,
                AdvApi32.SC_MANAGER_ALL_ACCESS
                );

            if (scManagerHandle == IntPtr.Zero)
            {
                Win32Error.Set("OpenSCManager");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
                return(false);
            }

            IntPtr serviceHandle = AdvApi32.OpenService(
                scManagerHandle,
                serviceName,
                AdvApi32.DELETE
                );

            if (serviceHandle == IntPtr.Zero)
            {
                Win32Error.Set("OpenService");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
                AdvApi32.CloseServiceHandle(scManagerHandle);
                return(false);
            }

            bool success = AdvApi32.DeleteService(serviceHandle);

            if (success)
            {
                Trace.WriteLine("Service deleted successfully");
            }
            else
            {
                Win32Error.Set("DeleteService");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
            }

            AdvApi32.CloseServiceHandle(serviceHandle);
            AdvApi32.CloseServiceHandle(scManagerHandle);

            return(success);
        }
Ejemplo n.º 4
0
        public void OpenCloseService()
        {
            using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
            {
                AssertHandleIsValid(scm);

                //opens task scheduler service
                using (var service = AdvApi32.OpenService(scm, "Schedule", ServiceAccessTypes.SERVICE_QUERY_STATUS))
                {
                    AssertHandleIsValid(service);
                }
            }
        }
Ejemplo n.º 5
0
        public void StartStopService()
        {
            using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
            {
                AssertHandleIsValid(scm);

                var access = ServiceAccessTypes.SERVICE_START | ServiceAccessTypes.SERVICE_STOP | ServiceAccessTypes.SERVICE_QUERY_STATUS;

                //opens print spooler service
                using (var service = AdvApi32.OpenService(scm, "Spooler", access))
                {
                    AssertHandleIsValid(service);

                    //query service status
                    var status = AdvApi32.QueryServiceStatusEx <SERVICE_STATUS_PROCESS>(service, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO);

                    if (status.dwCurrentState == ServiceState.SERVICE_RUNNING)
                    {
                        var ret4 = AdvApi32.StopService(service, out var _);
                        if (!ret4)
                        {
                            Win32Error.ThrowLastError();
                        }

                        WaitForServiceStatus(service, ServiceState.SERVICE_STOPPED);

                        var ret6 = AdvApi32.StartService(service);
                        if (!ret6)
                        {
                            Win32Error.ThrowLastError();
                        }
                    }
                    else
                    {
                        var ret4 = AdvApi32.StartService(service);
                        if (!ret4)
                        {
                            Win32Error.ThrowLastError();
                        }

                        WaitForServiceStatus(service, ServiceState.SERVICE_RUNNING);

                        var ret6 = AdvApi32.StopService(service, out var _);
                        if (!ret6)
                        {
                            Win32Error.ThrowLastError();
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public static void Uninstall()
        {
            try
            {
                logger.Info($"Opening service control manager");
                var      serviceManager = AdvApi32.OpenSCManager(null, null, AdvApi32.ScManagerAccessTypes.SC_MANAGER_ALL_ACCESS);
                string[] dependencies   = new[] { "http" };
                logger.Info($"Opened service control manager");

                try
                {
                    logger.Info($"Checking for existing {Constants.ServiceName} service");
                    var serviceHandle = AdvApi32.OpenService(serviceManager, Constants.ServiceName, AdvApi32.ServiceAccessTypes.SERVICE_ALL_ACCESS);

                    if (serviceHandle.IsNull)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    logger.Info($"Found existing {Constants.ServiceName} service");

                    if (!AdvApi32.DeleteService(serviceHandle))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    logger.Info($"Deleted existing {Constants.ServiceName} service");
                }
                catch (Win32Exception ex)
                {
                    if (ex.NativeErrorCode == 1060)
                    {
                        logger.Info($"Existing {Constants.ServiceName} service not found");
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Unable to uninstall service");
            }
        }
Ejemplo n.º 7
0
        public void QueryServiceStatus()
        {
            using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
            {
                AssertHandleIsValid(scm);

                //opens task scheduler service
                using (var service = AdvApi32.OpenService(scm, "Schedule", ServiceAccessTypes.SERVICE_QUERY_STATUS))
                {
                    AssertHandleIsValid(service);

                    //query service status
                    var status = AdvApi32.QueryServiceStatusEx <SERVICE_STATUS_PROCESS>(service, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO);

                    Assert.That(status.dwServiceType, Is.EqualTo(ServiceTypes.SERVICE_WIN32).Or.EqualTo(ServiceTypes.SERVICE_WIN32_SHARE_PROCESS));
                    Assert.That(status.dwServiceFlags, Is.EqualTo(0));
                }
            }
        }
Ejemplo n.º 8
0
 public void CreateService()
 {
     Console.WriteLine($"created service serviceName:{serviceName}, displayName:{displayName}, desiredAccess: 0x{(uint)desiredAccess:X8}," +
                       $" serviceType: {serviceType},startType: {startType}, errorControl: {errorControl}," +
                       $" binaryPathName: {binaryPathName}, serviceStartName: {serviceStartName}");
     using var scManager     = AdvApi32.OpenSCManager(null, null, desiredAccess);
     using var serviceHandle = AdvApi32.CreateService(scManager,
                                                      serviceName,
                                                      displayName,
                                                      desiredAccess,
                                                      serviceType,
                                                      startType,
                                                      errorControl,
                                                      binaryPathName,
                                                      null,
                                                      0,
                                                      null,
                                                      serviceStartName,
                                                      password);
 }
Ejemplo n.º 9
0
        public static bool ChangeServiceStartMode(
            string serviceName,
            ExpandedServiceStartMode mode)
        {
            Trace.WriteLine(
                "Changing Start Mode of service: \'" + serviceName + "\'"
                );

            IntPtr scManagerHandle = AdvApi32.OpenSCManager(
                null,
                null,
                AdvApi32.SC_MANAGER_ALL_ACCESS
                );

            if (scManagerHandle == IntPtr.Zero)
            {
                Trace.WriteLine("Open Service Manager Error");
                return(false);
            }

            IntPtr serviceHandle = AdvApi32.OpenService(
                scManagerHandle,
                serviceName,
                AdvApi32.SERVICE_QUERY_CONFIG |
                AdvApi32.SERVICE_CHANGE_CONFIG
                );

            if (serviceHandle == IntPtr.Zero)
            {
                Trace.WriteLine("Open Service Error");
                return(false);
            }

            if (!AdvApi32.ChangeServiceConfig(
                    serviceHandle,
                    AdvApi32.SERVICE_NO_CHANGE,
                    (uint)mode,
                    AdvApi32.SERVICE_NO_CHANGE,
                    null,
                    null,
                    IntPtr.Zero,
                    null,
                    null,
                    null,
                    null))
            {
                Win32Error.Set("ChangeServiceConfig");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
                return(false);
            }

            AdvApi32.CloseServiceHandle(serviceHandle);
            AdvApi32.CloseServiceHandle(scManagerHandle);

            Trace.WriteLine(
                "Start Mode successfully changed to: \'" +
                mode.ToString() + "\'"
                );

            return(true);
        }
Ejemplo n.º 10
0
        public bool Install(string path, out string errorMessage)
        {
            IntPtr manager = AdvApi32.OpenSCManager(null, null, AdvApi32.SC_MANAGER_ACCESS_MASK.SC_MANAGER_ALL_ACCESS);

            if (manager == IntPtr.Zero)
            {
                errorMessage = "OpenSCManager returned zero.";
                return(false);
            }

            IntPtr service = AdvApi32.CreateService(manager,
                                                    _id,
                                                    _id,
                                                    AdvApi32.SERVICE_ACCESS_MASK.SERVICE_ALL_ACCESS,
                                                    AdvApi32.SERVICE_TYPE.SERVICE_KERNEL_DRIVER,
                                                    AdvApi32.SERVICE_START.SERVICE_DEMAND_START,
                                                    AdvApi32.SERVICE_ERROR.SERVICE_ERROR_NORMAL,
                                                    path,
                                                    null,
                                                    null,
                                                    null,
                                                    null,
                                                    null);

            if (service == IntPtr.Zero)
            {
                if (Marshal.GetHRForLastWin32Error() == Kernel32.ERROR_SERVICE_EXISTS)
                {
                    errorMessage = "Service already exists";
                    return(false);
                }

                errorMessage = "CreateService returned the error: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                AdvApi32.CloseServiceHandle(manager);
                return(false);
            }

            if (!AdvApi32.StartService(service, 0, null))
            {
                if (Marshal.GetHRForLastWin32Error() != Kernel32.ERROR_SERVICE_ALREADY_RUNNING)
                {
                    errorMessage = "StartService returned the error: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                    AdvApi32.CloseServiceHandle(service);
                    AdvApi32.CloseServiceHandle(manager);
                    return(false);
                }
            }

            AdvApi32.CloseServiceHandle(service);
            AdvApi32.CloseServiceHandle(manager);

#if NETFRAMEWORK
            try
            {
                // restrict the driver access to system (SY) and builtin admins (BA)
                // TODO: replace with a call to IoCreateDeviceSecure in the driver
                FileSecurity fileSecurity = File.GetAccessControl(@"\\.\" + _id);
                fileSecurity.SetSecurityDescriptorSddlForm("O:BAG:SYD:(A;;FA;;;SY)(A;;FA;;;BA)");
                File.SetAccessControl(@"\\.\" + _id, fileSecurity);
            }
            catch
            { }
#endif
            errorMessage = null;
            return(true);
        }
Ejemplo n.º 11
0
        public static void Install(string path, string username, string password)
        {
            try
            {
                logger.Info($"Opening service control manager");
                var      serviceManager = AdvApi32.OpenSCManager(null, null, AdvApi32.ScManagerAccessTypes.SC_MANAGER_ALL_ACCESS);
                string[] dependencies   = new[] { "http" };
                logger.Info($"Opened service control manager");
                AdvApi32.SafeSC_HANDLE serviceHandle;

                if (!path.StartsWith("\""))
                {
                    path = "\"" + path;
                }

                if (!path.EndsWith("\""))
                {
                    path = path + "\"";
                }

                try
                {
                    logger.Info($"Checking for existing {Constants.ServiceName} service");
                    serviceHandle = AdvApi32.OpenService(serviceManager, Constants.ServiceName, AdvApi32.ServiceAccessTypes.SERVICE_ALL_ACCESS);

                    if (serviceHandle.IsNull)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    logger.Info($"Found existing {Constants.ServiceName} service");
                }
                catch (Win32Exception ex)
                {
                    if (ex.NativeErrorCode == 1060)
                    {
                        logger.Info($"Existing {Constants.ServiceName} service not found");
                        logger.Info($"Attempting to create server {Constants.ServiceName} for user {username} at {path}");

                        serviceHandle = AdvApi32.CreateService(serviceManager, Constants.ServiceName, Constants.ServiceDisplayName, (uint)AdvApi32.ServiceAccessTypes.SERVICE_ALL_ACCESS, AdvApi32.ServiceTypes.SERVICE_WIN32_OWN_PROCESS, AdvApi32.ServiceStartType.SERVICE_DEMAND_START, AdvApi32.ServiceErrorControlType.SERVICE_ERROR_NORMAL, path, null, IntPtr.Zero, dependencies, username, password);

                        if (serviceHandle.IsNull)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }

                        logger.Info($"Created {Constants.ServiceName} service");
                    }
                    else
                    {
                        throw;
                    }
                }

                var description = new AdvApi32.SERVICE_DESCRIPTION()
                {
                    lpDescription = Constants.ServiceDescription
                };

                logger.Info($"Updating service description");
                if (!AdvApi32.ChangeServiceConfig2(serviceHandle, AdvApi32.ServiceConfigOption.SERVICE_CONFIG_DESCRIPTION, description))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                var sidConfig = new AdvApi32.SERVICE_SID_INFO()
                {
                    dwServiceSidType = 0x1
                };

                logger.Info($"Updating service SID configuration");
                if (!AdvApi32.ChangeServiceConfig2(serviceHandle, AdvApi32.ServiceConfigOption.SERVICE_CONFIG_SERVICE_SID_INFO, sidConfig))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                logger.Info($"Updated existing {Constants.ServiceName} service parameters");

                TryGrantLogonAsAService(username);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Unable to install service");
                throw;
            }
        }