Esempio n. 1
0
        private static int RunListServicesAndReturnExitCode(ListOptions opts)
        {
            //Check Admin right
            if (!DaemonMasterUtils.IsElevated())
            {
                Console.WriteLine("You must start the program with admin rights.");
                return(1);
            }

            try
            {
                Console.WriteLine("Number:  service name / display name");

                List <DmServiceDefinition> services = RegistryManagement.GetInstalledServices();
                for (var i = 0; i < services.Count; i++)
                {
                    var sb = new StringBuilder();
                    sb.Append(i);
                    sb.Append(": ");
                    sb.Append(services[i].ServiceName.Contains("DaemonMaster_") ? services[i].ServiceName.Remove(0, 13) : services[i].ServiceName); //Remove internally used prefix TODO: remove that on a later release
                    sb.Append(" / ");
                    sb.Append(services[i].DisplayName);
                    Console.WriteLine(sb);
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(1);
            }
        }
Esempio n. 2
0
        private static int RunOptionsAndReturnExitCode(GeneralOptions option)
        {
            int result = 0;

            //Check Admin right
            if (!DaemonMasterUtils.IsElevated())
            {
                Console.WriteLine("You must start the program with admin rights.");
                return(1);
            }


            //TODO

            return(result);
        }
Esempio n. 3
0
        private static int RunInstallAndReturnExitCode(InstallOptions opts)
        {
            //Check Admin right
            if (!DaemonMasterUtils.IsElevated())
            {
                Console.WriteLine("You must start the program with admin rights.");
                return(1);
            }

            //------------------------

            if (string.IsNullOrWhiteSpace(opts.ServiceName))
            {
                Console.WriteLine("The given service name is invalid.");
                return(-1);
            }

            var serviceDefinition = new DmServiceDefinition(opts.ServiceName)
            {
                BinaryPath  = opts.FullPath,
                DisplayName = opts.DisplayName
            };

            try
            {
                CheckAndSetCommonArguments(ref serviceDefinition, opts);

                //Install service
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.CreateService))
                {
                    scm.CreateService(serviceDefinition);
                }

                //Save arguments in registry
                RegistryManagement.SaveInRegistry(serviceDefinition);

                Console.WriteLine("Successful!");
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(1);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Allows you to get the user token from a user logon
        /// </summary>
        /// <param name="username">The username</param>
        /// <param name="password">The password to login</param>
        /// <param name="logonTyp">The logon type</param>
        /// <returns>A <see cref="TokenHelper"/> or null if no valid sessions was found.</returns>
        public static SafeAccessTokenHandle GetUserTokenFromLogon(string username, SecureString password, Advapi32.LogonType logonTyp)
        {
            IntPtr passwordHandle = Marshal.SecureStringToGlobalAllocUnicode(password);

            try
            {
                if (!Advapi32.LogonUser(DaemonMasterUtils.GetLoginFromUsername(username), DaemonMasterUtils.GetDomainFromUsername(username), passwordHandle, logonTyp, Advapi32.LogonProvider.Default, out SafeAccessTokenHandle token))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                return(token);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(passwordHandle);
            }
        }
Esempio n. 5
0
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            //If Windows 10 1803 installed don't ask for start the UI0Detect service
            if (DaemonMasterUtils.IsSupportedWindows10VersionForIwd)
            {
                //If Windows 10 1803 installed don't ask for UI0Detect registry key change
                AskToEnableInteractiveServices();

                if (!DaemonMasterUtils.CheckUi0DetectService())
                {
                    MessageBox.Show(_resManager.GetString("error_ui0service", CultureInfo.CurrentUICulture),
                                    _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }
            }

            _ = Updater.Updater.StartAsync("https://github.com/TWC-Software/DaemonMaster");
        }
Esempio n. 6
0
        public Win32Sid(string account)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                throw new ArgumentException("Failed to instantiate Win32Sid: String is empty or null!");
            }


            //var sid = (SecurityIdentifier)new NTAccount(DaemonMasterUtils.GetLoginFromUsername(account)).Translate(typeof(SecurityIdentifier));

            //var buffer = new byte[sid.BinaryLength];
            //sid.GetBinaryForm(buffer, 0);

            //Pointer = Marshal.AllocHGlobal(buffer.Length);
            //Marshal.Copy(buffer, 0, Pointer, buffer.Length);

            Pointer = IntPtr.Zero;
            uint cbSid = 0;
            var  referencedDomainName   = new StringBuilder();
            var  cbReferencedDomainName = (uint)referencedDomainName.Capacity;

            if (!Advapi32.LookupAccountName(null, DaemonMasterUtils.GetLoginFromUsername(account), Pointer, ref cbSid, referencedDomainName, ref cbReferencedDomainName, out uint sidUse))
            {
                int result = Marshal.GetLastWin32Error();

                if (result == 0x7A) //ERROR_INSUFFICIENT_BUFFER
                {
                    Pointer = Marshal.AllocHGlobal((int)cbSid);
                    referencedDomainName.EnsureCapacity((int)cbReferencedDomainName);
                    referencedDomainName.Append(DaemonMasterUtils.GetDomainFromUsername(account));

                    if (!Advapi32.LookupAccountName(null, DaemonMasterUtils.GetLoginFromUsername(account), Pointer, ref cbSid, referencedDomainName, ref cbReferencedDomainName, out sidUse))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(result);
                }
            }
        }
Esempio n. 7
0
        public Win32Sid(string account)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                throw new ArgumentException("Win32Sid: Account name is empty or null.");
            }

            //When the user is from the local domain, just use the username else error
            account = DaemonMasterUtils.IsLocalDomain(account) ? DaemonMasterUtils.GetLoginFromUsername(account) : account;

            uint sidSize = 0;
            uint referencedDomainNameSize = 0;

            if (!Advapi32.LookupAccountName(null, account, IntPtr.Zero, ref sidSize, null, ref referencedDomainNameSize, out uint sidType))
            {
                int result = Marshal.GetLastWin32Error();

                if (result != Win32ErrorCodes.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw new Win32Exception(result);
                }
            }

            StringBuilder referencedDomainName = new StringBuilder((int)referencedDomainNameSize);

            Pointer = Marshal.AllocHGlobal((int)sidSize);
            try
            {
                if (!Advapi32.LookupAccountName(null, account, Pointer, ref sidSize, referencedDomainName, ref referencedDomainNameSize, out sidType))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Esempio n. 8
0
        private void SwitchToSession0()
        {
            if (!DaemonMasterUtils.IsSupportedWindows10VersionForIwd)
            {
                MessageBox.Show(_resManager.GetString("windows10_1803_switch_session0", CultureInfo.CurrentUICulture),
                                _resManager.GetString("warning", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                                MessageBoxImage.Warning);
                return;
            }


            if (DaemonMasterUtils.CheckUi0DetectService())
            {
                //if its Windows 10 then showing a warning message
                if (Environment.OSVersion.Version.Major == 10)
                {
                    MessageBoxResult result =
                        MessageBox.Show(_resManager.GetString("windows10_mouse_keyboard", CultureInfo.CurrentUICulture),
                                        _resManager.GetString("warning", CultureInfo.CurrentUICulture), MessageBoxButton.OKCancel,
                                        MessageBoxImage.Warning);

                    if (result == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
                //Switch to session 0
                Winsta.WinStationSwitchToServicesSession();
            }
            else
            {
                MessageBox.Show(
                    _resManager.GetString("failed_start_UI0detect_service", CultureInfo.CurrentUICulture),
                    _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Determines whether the credentials specifying a virtual account.
 /// </summary>
 /// <param name="credentials">The credentials.</param>
 /// <returns>
 ///   <c>true</c> if it is virtual account; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsVirtualAccount(ServiceCredentials credentials)
 {
     return(DaemonMasterUtils.GetDomainFromUsername(credentials.Username) == "NT SERVICE" && !string.IsNullOrWhiteSpace(DaemonMasterUtils.GetLoginFromUsername(credentials.Username)) && (credentials.Password == EmptyPassword || credentials.Password == null));
 }
Esempio n. 10
0
        public static ActionResult DeleteAllServices(Session session)
        {
            string appFolder = session.CustomActionData["APPDIR"];

            if (string.IsNullOrWhiteSpace(appFolder) || !Directory.Exists(appFolder))
            {
                session.Log("AppFolder is null or invalid.");
                return(ActionResult.Failure);
            }

            session.Log("Beginning the uninstall of all services.");

            try
            {
                using (ServiceControlManager controlManager = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    //Get all services for this installation
                    List <string> serviceNameList = new List <string>();
                    using (RegistryKey mainKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\", RegistryKeyPermissionCheck.ReadSubTree))
                    {
                        if (mainKey == null)
                        {
                            return(ActionResult.Failure);
                        }

                        foreach (string serviceName in mainKey.GetSubKeyNames())
                        {
                            using (RegistryKey key = mainKey.OpenSubKey(serviceName, RegistryKeyPermissionCheck.ReadSubTree))
                            {
                                //If the key invalid, skip this service
                                if (key == null)
                                {
                                    continue;
                                }

                                //Get the exe path of the service to determine later if its a service from DaemonMaster
                                string serviceExePath = Convert.ToString(key.GetValue("ImagePath") ?? string.Empty);


                                if (string.IsNullOrWhiteSpace(serviceExePath) || !DaemonMasterUtils.ComparePaths(serviceExePath, appFolder + ServiceControlManager.DmServiceFileName)) //Not possible to use ServiceControlManager.DmServiceExe because the AppDomain changed here => so that we need to rebuilt the path.
                                {
                                    continue;
                                }

                                serviceNameList.Add(serviceName);
                            }
                        }
                    }

                    foreach (string serviceName in serviceNameList)
                    {
                        using (ServiceHandle service = controlManager.OpenService(serviceName, Advapi32.ServiceAccessRights.AllAccess))
                        {
                            session.Log("Try to delete " + serviceName);

                            try
                            {
                                Advapi32.ServiceStatusProcess serviceStatus = service.QueryServiceStatus();

                                if (serviceStatus.currentState != Advapi32.ServiceCurrentState.Stopped)
                                {
                                    session.Log("Try killing " + serviceName + " service.");
                                    service.ExecuteCommand((int)ServiceCommands.ServiceKillProcessAndStop);

                                    try
                                    {
                                        service.WaitForStatus(Advapi32.ServiceCurrentState.Stopped, TimeSpan.FromSeconds(5));
                                    }
                                    catch (TimeoutException)
                                    {
                                        session.Log("Terminate " + serviceName + " service.");
                                        Process process = Process.GetProcessById((int)serviceStatus.processId);
                                        process.Kill();
                                    }
                                }

                                service.DeleteService();
                                session.Log("Deleted " + serviceName + " service successful.");
                            }
                            catch (Exception e)
                            {
                                session.Log("Deletion of " + serviceName + " failed.\n" + e.Message + "\n" + e.StackTrace);
                                //continue
                            }
                        }
                    }
                }

                session.Log("Uninstall of all services was successful.");
                return(ActionResult.Success);
            }
            catch (Exception e)
            {
                session.Log(e.Message + "\n" + e.StackTrace);
                return(ActionResult.Failure);
            }
        }
Esempio n. 11
0
        private void SaveConfiguration()
        {
            try
            {
                //Path / File not exist
                if (!Directory.Exists(Path.GetDirectoryName(TextBoxFilePath.Text)) ||
                    !File.Exists(TextBoxFilePath.Text))
                {
                    MessageBox.Show(_resManager.GetString("invalid_path", CultureInfo.CurrentUICulture),
                                    _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                //Invalid value error
                if (string.IsNullOrWhiteSpace(TextBoxDisplayName.Text) ||
                    string.IsNullOrWhiteSpace(TextBoxServiceName.Text) ||
                    !int.TryParse(TextBoxMaxRestarts.Text, out int maxRestarts) ||
                    !int.TryParse(TextBoxProcessTimeoutTime.Text, out int processKillTime) ||
                    !int.TryParse(TextBoxProcessRestartDelay.Text, out int processRestartDelay) ||
                    !int.TryParse(TextBoxCounterResetTime.Text, out int counterResetTime) ||
                    (CheckBoxIsConsoleApp.IsChecked ?? false) && !(RadioButtonUseCtrlBreak.IsChecked ?? true) &&
                    !(RadioButtonUseCtrlC.IsChecked ?? true))
                {
                    MessageBox.Show(_resManager.GetString("invalid_values", CultureInfo.CurrentUICulture),
                                    _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                #region Password/LocalSystem

                if (CheckBoxUseLocalSystem.IsChecked ?? false) // => LocalSystem is null
                {
                    _tempServiceConfig.Credentials = ServiceCredentials.LocalSystem;
                }
                else if (CheckBoxUseVirtualAccount.IsChecked ?? false)
                {
                    _tempServiceConfig.Credentials = new ServiceCredentials(TextBoxUsername.Text, ServiceCredentials.EmptyPassword);
                }
                else if (string.Equals(TextBoxPassword.Password, PLACEHOLDER_PASSWORD) &&              //Nothing has changed (null safe)
                         string.Equals(TextBoxUsername.Text, _tempServiceConfig.Credentials.Username)) //Nothing has changed (null safe
                {
                    _tempServiceConfig.Credentials = ServiceCredentials.NoChange;                      //Null stands for nothing has changed
                }
                else
                {
                    //No date has been written in the textfields
                    if (string.IsNullOrWhiteSpace(TextBoxUsername.Text))
                    {
                        MessageBox.Show(_resManager.GetString("invalid_pw_user", CultureInfo.CurrentUICulture),
                                        _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                        return;
                    }

                    //When its not a local user...
                    if (!DaemonMasterUtils.IsLocalDomain(TextBoxUsername.Text))
                    {
                        MessageBox.Show(_resManager.GetString("extern_domain_user_error", CultureInfo.CurrentUICulture),
                                        _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                        return;
                    }

                    ////Password or username is not correct
                    //if (!DaemonMasterUtils.ValidateUser(TextBoxUsername.Text, TextBoxPassword.SecurePassword))
                    //{
                    //    MessageBox.Show(_resManager.GetString("login_failed", CultureInfo.CurrentUICulture),
                    //        _resManager.GetString("error", CultureInfo.CurrentUICulture), MessageBoxButton.OK,
                    //        MessageBoxImage.Error);
                    //    return;
                    //}

                    _tempServiceConfig.Credentials = new ServiceCredentials(TextBoxUsername.Text, TextBoxPassword.SecurePassword);
                }

                #endregion

                _tempServiceConfig.DisplayName = TextBoxDisplayName.Text;
                _tempServiceConfig.ServiceName = TextBoxServiceName.Text;

                _tempServiceConfig.BinaryPath = TextBoxFilePath.Text;

                _tempServiceConfig.Arguments      = TextBoxParam.Text;
                _tempServiceConfig.Description    = TextBoxDescription.Text;
                _tempServiceConfig.LoadOrderGroup = TextBoxLoadOrderGroup.Text;

                _tempServiceConfig.ProcessMaxRestarts  = maxRestarts;
                _tempServiceConfig.ProcessTimeoutTime  = processKillTime;
                _tempServiceConfig.ProcessRestartDelay = processRestartDelay;
                _tempServiceConfig.CounterResetTime    = counterResetTime;

                _tempServiceConfig.DependOnService = _dependOnServiceObservableCollection.Select(x => x.ServiceName).ToArray();
                _tempServiceConfig.DependOnGroup   = _dependOnGroupObservableCollection.ToArray();


                switch (ComboBoxProcessPriority.SelectedIndex)
                {
                case 0:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.Idle;
                    break;

                case 1:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.BelowNormal;
                    break;

                case 2:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.Normal;
                    break;

                case 3:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.AboveNormal;
                    break;

                case 4:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.High;
                    break;

                case 5:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.RealTime;
                    break;

                default:
                    _tempServiceConfig.ProcessPriority = ProcessPriorityClass.Normal;
                    break;
                }

                _tempServiceConfig.IsConsoleApplication = CheckBoxIsConsoleApp.IsChecked ?? false;
                _tempServiceConfig.UseCtrlC             = _tempServiceConfig.IsConsoleApplication &&
                                                          (RadioButtonUseCtrlC.IsChecked ?? true) &&
                                                          !(RadioButtonUseCtrlBreak.IsChecked ?? false);

                _tempServiceConfig.CanInteractWithDesktop = CheckBoxInteractDesk.IsChecked ?? false;
                _tempServiceConfig.UseEventLog            = CheckBoxUseEventLog.IsChecked ?? false;

                switch (ComboBoxStartType.SelectedIndex)
                {
                case 0:
                    _tempServiceConfig.DelayedStart = false;
                    _tempServiceConfig.StartType    = Advapi32.ServiceStartType.AutoStart;
                    break;

                case 1:
                    _tempServiceConfig.DelayedStart = true;
                    _tempServiceConfig.StartType    = Advapi32.ServiceStartType.AutoStart;
                    break;

                case 2:
                    _tempServiceConfig.DelayedStart = false;
                    _tempServiceConfig.StartType    = Advapi32.ServiceStartType.StartOnDemand;
                    break;

                case 3:
                    _tempServiceConfig.DelayedStart = false;
                    _tempServiceConfig.StartType    = Advapi32.ServiceStartType.Disabled;
                    break;

                default:
                    _tempServiceConfig.DelayedStart = false;
                    _tempServiceConfig.StartType    = Advapi32.ServiceStartType.AutoStart;
                    break;
                }

                //Apply service settings
                ApplyConfiguration();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, _resManager.GetString("error", CultureInfo.CurrentUICulture),
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 12
0
        private static int RunEditReturnExitCode(EditOptions opts)
        {
            //Check Admin right
            if (!DaemonMasterUtils.IsElevated())
            {
                Console.WriteLine("You must start the program with admin rights.");
                return(1);
            }

            //------------------------

            DmServiceDefinition serviceDefinition;

            try
            {
                if (string.IsNullOrWhiteSpace(opts.ServiceName))
                {
                    Console.WriteLine("The given service name is invalid.");
                    return(-1);
                }

                string realServiceName = opts.ServiceName;
                if (!RegistryManagement.IsDaemonMasterService(realServiceName))
                {
                    realServiceName = "DaemonMaster_" + realServiceName; //Check for the name of the old system TODO: remove later
                    if (!RegistryManagement.IsDaemonMasterService(realServiceName))
                    {
                        Console.WriteLine("Cannot found a DaemonMaster service with the given name.");
                        return(-1);
                    }
                }

                //Load data from registry
                serviceDefinition = RegistryManagement.LoadFromRegistry(realServiceName);
            }
            catch (Exception)
            {
                Console.WriteLine("Cannot found a service with the given service name."); //"\n" + e.Message + "\n StackTrace: " + e.StackTrace);
                return(1);
            }

            try
            {
                CheckAndSetCommonArguments(ref serviceDefinition, opts);

                //Edit service
                using (ServiceControlManager scm = ServiceControlManager.Connect(Advapi32.ServiceControlManagerAccessRights.Connect))
                {
                    using (ServiceHandle service = scm.OpenService(serviceDefinition.ServiceName, Advapi32.ServiceAccessRights.AllAccess))
                    {
                        if (service.QueryServiceStatus().currentState != Advapi32.ServiceCurrentState.Stopped)
                        {
                            Console.WriteLine("Service is not stopped, please stop it first.");
                            return(1);
                        }

                        service.ChangeConfig(serviceDefinition);
                    }
                }

                //Save arguments in registry
                RegistryManagement.SaveInRegistry(serviceDefinition);

                Console.WriteLine("Successful!");
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(1);
            }
        }