Esempio n. 1
0
        /// <summary>
        /// Check to see whether the domain account and its password are valid
        /// </summary>
        private static bool CheckDomainAccountValid()
        {
            string       domainName = SetupInputs.Instance.FindItem(SetupInputTags.CmpServiceDomainTag);
            string       userName   = SetupInputs.Instance.FindItem(SetupInputTags.CmpServiceUserNameTag);
            SecureString password   = SetupInputs.Instance.FindItem(SetupInputTags.CmpServiceUserPasswordTag);

            if (UserAccountHelper.ValidateCredentials(userName, domainName, password))
            {
                return(true);
            }
            else
            {
                //throw SetupExceptionFactory.NewBackEndErrorException(ErrorCode.InvalidDomainAccount);
                SetupLogger.LogError("CheckDomainAccountValid(): Invalid domain account");
                return(false);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// This method calls into native code for creating a service.
        /// The service is created with the following standard parameters:
        /// WIN32_OWN_PROCESS, ERROR_NORMAL, No dependencies
        /// The handle of the service obtained is closed and not returned
        /// </summary>
        /// <param name="hSCManager">Handle to SCM with create service rights</param>
        /// <param name="svcName">Name of service to create</param>
        /// <param name="displayName">Localized display name of the service</param>
        /// <param name="svcDescription">Description of the service</param>
        /// <param name="binaryPath">Path to the binary</param>
        /// <param name="dependenciesArray">Array of dependencies</param>
        /// <param name="serviceStartName">The user account under which the service will run</param>
        /// <param name="password">Password for the user account</param>
        /// <param name="autoStart">Should the service be AutoStart on booting the machine</param>
        /// <param name="interactive">Allow service to interact with desktop or not</param>
        public static void CreateService(IntPtr hSCManager,
                                         string svcName,
                                         string displayName,
                                         string svcDescription,
                                         string binaryPath,
                                         string[] dependenciesArray,
                                         string serviceStartName,
                                         IntPtr password,
                                         bool autoStart,
                                         bool interactive)
        {
            IntPtr hService = NativeMethods.NullIntPtr;

            try
            {
                AppAssert.Assert(null != svcName, "Null service name passed!");
                AppAssert.Assert(null != binaryPath, "Null binary path passed!");

                string dependenciesString = CreateNativeStringArray(dependenciesArray);

                int svcType = NativeMethods.SERVICE_WIN32_OWN_PROCESS;
                if (interactive)
                {
                    svcType = NativeMethods.SERVICE_WIN32_OWN_PROCESS | NativeMethods.SERVICE_INTERACTIVE_PROCESS;
                }

                int svcStartType = NativeMethods.SERVICE_DEMAND_START;
                if (autoStart)
                {
                    svcStartType = NativeMethods.SERVICE_AUTO_START;
                }

                if (!NativeMethods.NullIntPtr.Equals(password))
                //if we are using a password we need to gr  ant logon as service permissions to this user.
                {
                    try
                    {
                        NativeMethods.SetRight(serviceStartName, "SeServiceLogonRight", true);
                        NativeMethods.SetRight(serviceStartName, "SeAssignPrimaryTokenPrivilege", true);
                    }
                    catch (Exception exp)
                    {
                        SetupLogger.LogError("Failed to grant user ( " + serviceStartName +
                                             " ) logon as service permissions. Error: " + exp.Message);
                    }
                }

                hService = NativeMethods.CreateService(
                    hSCManager,
                    svcName,
                    displayName,
                    NativeMethods.SERVICE_CHANGE_CONFIG,
                    svcType,
                    svcStartType,
                    NativeMethods.SERVICE_ERROR_NORMAL,
                    binaryPath,
                    null,                     //load order group
                    NativeMethods.NullIntPtr, //[out] tagId
                    dependenciesString,
                    serviceStartName,         //Username
                    password
                    );

                if (NativeMethods.NullIntPtr.Equals(hService))
                {
                    SetupLogger.LogInfo("BackEnd.Configure: Got back NULL service handle!");
                    int lastWin32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    throw new Exception(String.Format("Cannot create service {0}", svcName));
                }

                NativeMethods.SERVICE_DESCRIPTION svcDesc = new NativeMethods.SERVICE_DESCRIPTION();
                svcDesc.lpDescription = svcDescription;
                bool success = NativeMethods.ChangeServiceConfig2(hService, NativeMethods.SERVICE_CONFIG_DESCRIPTION,
                                                                  ref svcDesc);

                if (!success)
                {
                    SetupLogger.LogInfo("BackEnd.Configure: Couldn't modify service description!");
                    int lastWin32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    throw new Exception(String.Format("Cannot create service {0}", svcName));
                }

                // Set service SID type. This is required for any service that has a firewall rule targeted for that specific service.
                NativeMethods.SERVICE_SID_INFO svcSidType = new NativeMethods.SERVICE_SID_INFO();
                svcSidType.serviceSidType = NativeMethods.SERVICE_SID_TYPE.SERVICE_SID_TYPE_UNRESTRICTED;
                success = NativeMethods.ChangeServiceConfig2(hService, NativeMethods.SERVICE_CONFIG_SERVICE_SID_INFO,
                                                             ref svcSidType);

                if (!success)
                {
                    SetupLogger.LogInfo("BackEnd.Configure: Couldn't modify service SID type!");
                    int lastWin32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    throw new Exception(String.Format("Cannot create service {0}", svcName));
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (NativeMethods.NullIntPtr != hService)
                {
                    NativeMethods.CloseServiceHandle(hService);
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Starts a particular service
        /// The method times out if service does not reach "Running" status within the timeout period.
        /// </summary>
        /// <param name="serviceName">name of service to start</param>
        /// <param name="machineName">name of computer on which the service resides</param>
        /// <exception cref="ServiceConfigurationException">when  service could not be started</exception>
        public void StartService(String serviceName, String machineName)
        {
            AppAssert.Assert(null != serviceName, "Null service name passed!");

            SetupLogger.LogInfo("StartService: Start the service {0}", serviceName);
            //ConfigurationMessageEvent(this, new ConfigurationMessageEventArgs(String.Format(Resources.StartingService, serviceName)));
            try
            {
                AppAssert.AssertNotNull(serviceName, "serviceName");

                ServiceController serviceController = null;

                try
                {
                    SetupLogger.LogInfo("Starting service" + serviceName);

                    if (machineName == null)
                    {
                        serviceController = new ServiceController(serviceName); // local host
                    }
                    else
                    {
                        serviceController = new ServiceController(serviceName, machineName);
                    }

                    SetupLogger.LogInfo("StartService: Service {0} status = {1}", serviceName, serviceController.Status);

                    //
                    // Query configurations (credentials and start mode) of service
                    //
                    ServiceConfig serviceConfig = GetServiceConfig(serviceName, machineName);

                    //
                    // Check if the service is disabled or manual and stopped
                    //
                    if (serviceConfig.StartMode == ServiceStartMode.Disabled ||
                        (serviceConfig.StartMode == ServiceStartMode.Manual &&
                         serviceController.Status == ServiceControllerStatus.Stopped))
                    {
                        SetupLogger.LogInfo(
                            "StartService : service is disabled or manual and not running");

                        throw new Exception(String.Format("Cannot start the service. Service name: {0}", serviceName));
                    }

                    // Check if the service is stopped or paused
                    if (serviceController.Status == ServiceControllerStatus.Running)
                    {
                        // Service is running, log and return

                        SetupLogger.LogInfo("StartService: Service running, check if needs to be restarted");

                        return;
                    }
                    if (serviceController.Status == ServiceControllerStatus.Stopped)
                    {
                        // Service stopped, Start the service

                        SetupLogger.LogInfo("StartService: Service stopped, Start the service");
                        serviceController.Start();
                    }
                    else if (serviceController.Status == ServiceControllerStatus.Paused)
                    {
                        // Service paused, Resume the service

                        SetupLogger.LogInfo("StartService: Service paused, Resume the service");
                        serviceController.Continue();
                    }

                    SetupLogger.LogInfo("StartService: Wait for service to start (timeout = {0})", SetupConstants.ServiceStartTimeout);
                    serviceController.WaitForStatus(ServiceControllerStatus.Running, SetupConstants.ServiceStartTimeout);
                }
                catch (System.ComponentModel.Win32Exception win32Exception)
                {
                    // The native service API failed
                    SetupLogger.LogError("StartService: Couldn't start service! Throwing exception: {0}", win32Exception.ToString());
                    throw new Exception(String.Format("Cannot start the service. Service name: {0}", serviceName));
                }
                catch (InvalidOperationException invalidOperationException)
                {
                    // The service can not be started
                    SetupLogger.LogError("StartService: Couldn't start service! Throwing exception: {0}", invalidOperationException.ToString());
                    throw;
                }
                catch (System.ServiceProcess.TimeoutException timeoutException)
                {
                    // There was a timeout
                    SetupLogger.LogError("StartService: Couldn't start service! Throwing exception: {0}", timeoutException.ToString());
                    throw new Exception(String.Format("Cannot start the service. Service name: {0}", serviceName));
                }
                finally
                {
                    if (serviceController != null)
                    {
                        serviceController.Close();
                    }
                }
            }
            catch (Exception serviceNotFoundException)
            {
                SetupLogger.LogInfo("ServiceConfigurationHandler.StartService: Start the service, exception {0}", serviceNotFoundException);
                throw new Exception(String.Format("Cannot start the service. Service name: {0}", serviceName));
            }
        }
Esempio n. 4
0
        public static ServiceConfig GetServiceConfig(String serviceName, String machineName)
        {
            if (serviceName == null)
            {
                SetupLogger.LogInfo("InspectConfigs.GetServiceConfig : Service name parametr is null");

                throw new Exception("Service name is null");
            }

            ServiceConfig serviceConfig = new ServiceConfig();

            NativeMethods.QUERY_SERVICE_CONFIGW serviceConfigQueryResult = new NativeMethods.QUERY_SERVICE_CONFIGW();

            IntPtr schSCManager = new IntPtr(0);
            IntPtr schService   = new IntPtr(0);

            int result = 0;

            UInt32 dwBytesNeeded = 0;

            try
            {
                //
                // Open handle to Service control manager
                //

                schSCManager = NativeMethods.OpenSCManager(
                    machineName, // null for local machine
                    null,        // ServicesActive database
                    NativeMethods.SC_MANAGER_CONNECT);

                if (NativeMethods.NullIntPtr.Equals(schSCManager))
                {
                    //
                    // Could not open service database
                    //

                    result = Marshal.GetLastWin32Error();
                    SetupLogger.LogError("GetServiceConfig : Unknown error while connecting to OpenSCManager");

                    throw new Exception("Cannot connect to service manager");
                }

                //
                // Open handle to the service
                //

                schService = NativeMethods.OpenService(
                    schSCManager,                        // SCManager database
                    serviceName,                         // name of service
                    NativeMethods.SERVICE_QUERY_CONFIG); // need QUERY access

                if (NativeMethods.NullIntPtr.Equals(schService))
                {
                    //
                    // Could not open service
                    //

                    result = Marshal.GetLastWin32Error();

                    switch (result)
                    {
                    case NativeMethods.ERROR_SERVICE_DOES_NOT_EXIST:
                    {
                        SetupLogger.LogInfo("GetServiceConfig : Service not found, ERROR_SERVICE_DOES_NOT_EXIST");

                        throw new Exception(String.Format("OpenService returned error ERROR_SERVICE_DOES_NOT_EXIST (Service not found) for service {0}", serviceName));
                    }

                    default:
                    {
                        SetupLogger.LogError("GetServiceConfig : Unknown error while connecting to Service");

                        throw new Exception("GetServiceConfig : Unknown error while connecting to Service");
                    }
                    }
                }

                //
                // Get the configuration information (Query SCM)
                //

                UInt32 size        = (UInt32)Marshal.SizeOf(serviceConfigQueryResult);
                bool   queryResult = NativeMethods.QueryServiceConfig(
                    schService,
                    ref serviceConfigQueryResult,
                    size,
                    ref dwBytesNeeded);

                if (queryResult == false)
                {
                    //
                    // Query to SCM for service configuration failed
                    //

                    result = Marshal.GetLastWin32Error();

                    SetupLogger.LogError("InspectConfigs.GetServiceConfig : Unknown error while querying service configuration information");

                    throw new Exception(String.Format("Error getting the service configuration for service {0}", serviceName));
                }

                //
                // Set service credentials parameter in output structure ServiceConfig
                //

                serviceConfig.ServiceCredentials = Marshal.PtrToStringAuto(serviceConfigQueryResult.lpServiceStartName);

                //
                // Set start mode parameter in output structure ServiceConfig
                //

                if (serviceConfigQueryResult.dwStartType == NativeMethods.SERVICE_AUTO_START)
                {
                    //
                    // Service AUTO start
                    //

                    serviceConfig.StartMode = ServiceStartMode.Automatic;
                }
                else if (serviceConfigQueryResult.dwStartType == NativeMethods.SERVICE_DISABLED)
                {
                    //
                    // Service disabled (can not be started)
                    //

                    serviceConfig.StartMode = ServiceStartMode.Disabled;
                }
                else
                {
                    //
                    // The .NET enumeration does not define SERVICE_BOOT_START and SERVICE_SYSTEM_START
                    // Hence we set it to manual. Service needs to be started manually
                    //

                    serviceConfig.StartMode = ServiceStartMode.Manual;
                }
            }
            finally
            {
                // cleanup
                if (!NativeMethods.NullIntPtr.Equals(schService))
                {
                    NativeMethods.CloseServiceHandle(schService);
                }

                if (!NativeMethods.NullIntPtr.Equals(schSCManager))
                {
                    NativeMethods.CloseServiceHandle(schSCManager);
                }
            }


            return(serviceConfig);
        }