public static UserImpersonation Impersonate(string username, string domain, string password)
        {
            var imp = new UserImpersonation(username, domain, password);

            imp.Impersonate();
            return(imp);
        }
Esempio n. 2
0
        public static RemoteUpdateConfiguration GetUpdateConfiguration()
        {
            var updateConfiguration = new RemoteUpdateConfiguration();

            const string updatesLastCheckedKey      = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Detect";
            const string updatesLastCheckedValue    = "LastSuccessTime";
            const string updatesLastInstalledKey    = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Install";
            const string updatesLastInstalledValue  = "LastSuccessTime";
            const string updatesConfigurationKey    = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update";
            const string updatesConfigurationAltKey = @"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU";
            const string updatesConfigurationValue  = "AUOptions";

            var managementScope            = new ManagementScope($@"\\{RemoteUpdate.ComputerName}\root\CIMV2");
            ManagementBaseObject inParams  = null;
            ManagementBaseObject outParams = null;

            try
            {
                using (var wmiRegistry = new ManagementClass(managementScope, new ManagementPath("StdRegProv"), null))
                {
                    // Get date and time of last update check.
                    inParams = wmiRegistry.GetMethodParameters("GetStringValue");
                    inParams["sSubKeyName"] = updatesLastCheckedKey;
                    inParams["sValueName"]  = updatesLastCheckedValue;
                    outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                    if (outParams["sValue"] != null)
                    {
                        updateConfiguration.LastUpdateCheck = DateTime.SpecifyKind(DateTime.Parse((string)outParams["sValue"]), DateTimeKind.Utc).ToLocalTime();
                    }

                    // Get date and time of last installed update.
                    inParams["sSubKeyName"] = updatesLastInstalledKey;
                    inParams["sValueName"]  = updatesLastInstalledValue;
                    outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                    if (outParams["sValue"] != null)
                    {
                        updateConfiguration.LastUpdateInstall = DateTime.SpecifyKind(DateTime.Parse((string)outParams["sValue"]), DateTimeKind.Utc).ToLocalTime();
                    }

                    // Get update configuration (automatic or manual).
                    inParams = wmiRegistry.GetMethodParameters("GetDWORDValue");
                    inParams["sSubKeyName"] = updatesConfigurationAltKey;
                    inParams["sValueName"]  = updatesConfigurationValue;
                    outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                    if (outParams["uValue"] != null)
                    {
                        updateConfiguration.AuOptionCode = (int)(UInt32)outParams["uValue"];
                    }
                    if (updateConfiguration.AuOptionCode <= 0)
                    {
                        inParams["sSubKeyName"] = updatesConfigurationKey;
                        inParams["sValueName"]  = updatesConfigurationValue;
                        outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                        if (outParams["uValue"] != null)
                        {
                            updateConfiguration.AuOptionCode = (int)(UInt32)outParams["uValue"];
                        }
                    }
                }
            }

            catch (ManagementException ex) when(ex.ErrorCode == ManagementStatus.NotFound)
            {
                // Target OS might not support WMI StdRegProv.  Attempt to gather data using remote registry.
                updateConfiguration = new RemoteUpdateConfiguration();
                const string serviceName      = "RemoteRegistry";
                bool         isLocal          = RemoteUpdate.ComputerName.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
                bool         isServiceRunning = true;

                // If the target computer is remote, then start the Remote Registry service.
                using (
                    GlobalVar.UseAlternateCredentials
                    ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                    : null)
                    using (var sc = new ServiceController(serviceName, RemoteUpdate.ComputerName))
                    {
                        try
                        {
                            if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                            {
                                isServiceRunning = false;
                                sc.Start();
                            }
                        }
                        catch (Exception)
                        {
                        }

                        try
                        {
                            using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, RemoteUpdate.ComputerName))
                            {
                                using (RegistryKey subKey = key.OpenSubKey(updatesLastCheckedKey))
                                {
                                    if (subKey != null && subKey.GetValue("LastSuccessTime") != null)
                                    {
                                        updateConfiguration.LastUpdateCheck = DateTime.SpecifyKind(DateTime.Parse(subKey.GetValue("LastSuccessTime").ToString()), DateTimeKind.Utc).ToLocalTime();
                                    }
                                }
                                using (RegistryKey subKey = key.OpenSubKey(updatesLastInstalledKey))
                                {
                                    if (subKey != null && subKey.GetValue("LastSuccessTime") != null)
                                    {
                                        updateConfiguration.LastUpdateInstall = DateTime.SpecifyKind(DateTime.Parse(subKey.GetValue("LastSuccessTime").ToString()), DateTimeKind.Utc).ToLocalTime();
                                    }
                                }
                                using (RegistryKey subKey = key.OpenSubKey(updatesConfigurationAltKey))
                                {
                                    if (subKey != null)
                                    {
                                        updateConfiguration.AuOptionCode = (subKey.GetValue("AUOptions") != null) ? int.Parse(subKey.GetValue("AUOptions").ToString()) : 0;
                                    }
                                }
                                if (updateConfiguration.AuOptionCode <= 0)
                                {
                                    using (RegistryKey subKey = key.OpenSubKey(updatesConfigurationKey))
                                    {
                                        if (subKey != null)
                                        {
                                            updateConfiguration.AuOptionCode = (subKey.GetValue("AUOptions") != null) ? int.Parse(subKey.GetValue("AUOptions").ToString()) : 0;
                                        }
                                    }
                                }
                            }

                            if (updateConfiguration.AuOptionCode < 4)
                            {
                                updateConfiguration.IsAutomaticUpdatesEnabled = false;
                            }
                            else
                            {
                                updateConfiguration.IsAutomaticUpdatesEnabled = true;
                            }
                        }
                        catch
                        {
                        }

                        // Cleanup.
                        if (!isLocal && !isServiceRunning)
                        {
                            try
                            {
                                if (sc != null)
                                {
                                    sc.Stop();
                                }
                            }

                            catch (Exception)
                            {
                            }
                        }
                    }
            }
            catch
            {
                // Do nothing.
            }
            finally
            {
                if (inParams != null)
                {
                    inParams.Dispose();
                }
                if (outParams != null)
                {
                    outParams.Dispose();
                }

                if (updateConfiguration.AuOptionCode < 4)
                {
                    updateConfiguration.IsAutomaticUpdatesEnabled = false;
                }
                else
                {
                    updateConfiguration.IsAutomaticUpdatesEnabled = true;
                }
            }

            return(updateConfiguration);
        }
        public static List <RemoteApplication> GetInstalledApplications()
        {
            var apps       = new List <RemoteApplication>();
            var taskResult = new TaskResult();

            Result = taskResult;

            const string uninstallKey       = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            const string uninstallKey32on64 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";

            var managementScope            = new ManagementScope($@"\\{ComputerName}\root\CIMV2");
            ManagementBaseObject inParams  = null;
            ManagementBaseObject outParams = null;

            try
            {
                using (var wmiRegistry = new ManagementClass(managementScope, new ManagementPath("StdRegProv"), null))
                {
                    List <string> subKeys       = null;
                    List <string> subKeys32on64 = null;
                    var           uninstallKeys = new List <string>();

                    // Get uninstall subkeys.
                    inParams = wmiRegistry.GetMethodParameters("EnumKey");
                    inParams["sSubKeyName"] = uninstallKey;
                    outParams = wmiRegistry.InvokeMethod("EnumKey", inParams, null);
                    if (outParams["sNames"] != null)
                    {
                        subKeys = new List <string>((string[])outParams["sNames"]).Select(x => $@"{uninstallKey}\{x}").ToList();
                    }

                    // Get 32-bit on 64-bit uninstall subkeys.
                    inParams["sSubKeyName"] = uninstallKey32on64;
                    outParams = wmiRegistry.InvokeMethod("EnumKey", inParams, null);
                    if (outParams["sNames"] != null)
                    {
                        subKeys32on64 = new List <string>((string[])outParams["sNames"]).Select(x => $@"{uninstallKey32on64}\{x}").ToList();
                    }

                    // Combine lists of keys.
                    if (subKeys != null)
                    {
                        uninstallKeys.AddRange(subKeys);
                    }
                    if (subKeys32on64 != null)
                    {
                        uninstallKeys.AddRange(subKeys32on64);
                    }

                    // Enumerate keys.
                    foreach (string subKey in uninstallKeys)
                    {
                        // Get SystemComponent (DWORD) value.  Skip key if this value exists and is set to '1'.
                        inParams = wmiRegistry.GetMethodParameters("GetDWORDValue");
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "SystemComponent";
                        outParams = wmiRegistry.InvokeMethod("GetDWORDValue", inParams, null);
                        if (outParams["uValue"] != null && (UInt32)outParams["uValue"] == 1)
                        {
                            continue;
                        }

                        // Get ParentKeyName (String) value.  Skip key if this value exists.
                        inParams = wmiRegistry.GetMethodParameters("GetStringValue");
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "ParentKeyName";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null && ((string)outParams["sValue"]).Length > 0)
                        {
                            continue;
                        }

                        // Get ReleaseType (String) value.  Skip key if this value contains 'Update' or 'Hotfix'.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "ReleaseType";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null && (((string)outParams["sValue"]).Contains("Update") || ((string)outParams["sValue"]).Equals("Hotfix")))
                        {
                            continue;
                        }

                        var app = new RemoteApplication();

                        // Get DisplayName (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "DisplayName";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.DisplayName = (string)outParams["sValue"];
                        }
                        else
                        {
                            continue;
                        }

                        // Get Publisher (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "Publisher";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.Publisher = (string)outParams["sValue"];
                        }

                        // Get DisplayVersion (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "DisplayVersion";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.Version = (string)outParams["sValue"];
                        }

                        // Get UninstallString (String) value.
                        inParams["sSubKeyName"] = subKey;
                        inParams["sValueName"]  = "UninstallString";
                        outParams = wmiRegistry.InvokeMethod("GetStringValue", inParams, null);
                        if (outParams["sValue"] != null)
                        {
                            app.UninstallPath = (string)outParams["sValue"];
                        }

                        apps.Add(app);
                    }
                }

                taskResult.DidTaskSucceed = true;
            }

            catch (ManagementException ex) when(ex.ErrorCode == ManagementStatus.NotFound)
            {
                // Target OS might not support WMI StdRegProv.  Attempt to gather data using remote registry.
                apps = new List <RemoteApplication>();
                const string serviceName      = "RemoteRegistry";
                bool         isLocal          = ComputerName.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
                bool         isServiceRunning = true;

                // If the target computer is remote, then start the Remote Registry service.
                using (
                    GlobalVar.UseAlternateCredentials
                    ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                    : null)
                    using (var sc = new ServiceController(serviceName, ComputerName))
                    {
                        try
                        {
                            if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                            {
                                isServiceRunning = false;
                                sc.Start();
                            }
                        }
                        catch (Exception)
                        {
                        }

                        try
                        {
                            using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName))
                            {
                                using (RegistryKey mainKey64 = key.OpenSubKey(uninstallKey))
                                    apps.AddRange(EnumerateUninstallKeys(mainKey64));
                                using (RegistryKey mainKey32 = key.OpenSubKey(uninstallKey32on64))
                                    apps.AddRange(EnumerateUninstallKeys(mainKey32));
                            }

                            taskResult.DidTaskSucceed = true;
                        }
                        catch
                        {
                            taskResult.DidTaskSucceed = false;
                        }


                        // Cleanup.
                        if (!isLocal && !isServiceRunning)
                        {
                            try
                            {
                                if (sc != null)
                                {
                                    sc.Stop();
                                }
                            }

                            catch (Exception)
                            {
                            }
                        }
                    }
            }

            catch
            {
                // Do nothing.
            }

            finally
            {
                if (inParams != null)
                {
                    inParams.Dispose();
                }
                if (outParams != null)
                {
                    outParams.Dispose();
                }
            }

            // Get Internet Explorer version.
            if (taskResult.DidTaskSucceed && apps.Count > 0)
            {
                try
                {
                    var internetExplorerVersion = FileVersionInfo.GetVersionInfo($@"\\{ComputerName}\C$\Program Files\Internet Explorer\iexplore.exe");
                    if (internetExplorerVersion != null && internetExplorerVersion.ProductVersion.Length > 0)
                    {
                        apps.Add(new RemoteApplication
                        {
                            DisplayName = "Internet Explorer",
                            Publisher   = "Microsoft Corporation",
                            Version     = internetExplorerVersion.ProductVersion
                        });
                    }
                }
                catch { }
            }

            return(apps);
        }
        private static bool GetSysRebootState()
        {
            bool isRebootPending = false;

            const string wuRegKey   = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired";
            const string cbsRegKey  = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending";
            const string pfroRegKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\FileRenameOperations";

            var managementScope            = new ManagementScope($@"\\{TargetComputer}\root\CIMV2");
            ManagementBaseObject inParams  = null;
            ManagementBaseObject outParams = null;

            try
            {
                using (var wmiRegistry = new ManagementClass(managementScope, new ManagementPath("StdRegProv"), null))
                {
                    inParams = wmiRegistry.GetMethodParameters("EnumValues");
                    inParams["sSubKeyName"] = wuRegKey;
                    outParams = wmiRegistry.InvokeMethod("EnumValues", inParams, null);
                    if ((UInt32)outParams["ReturnValue"] == 0)
                    {
                        isRebootPending = true;
                    }

                    inParams["sSubKeyName"] = cbsRegKey;
                    outParams = wmiRegistry.InvokeMethod("EnumValues", inParams, null);
                    if ((UInt32)outParams["ReturnValue"] == 0)
                    {
                        isRebootPending = true;
                    }

                    inParams["sSubKeyName"] = pfroRegKey;
                    outParams = wmiRegistry.InvokeMethod("EnumValues", inParams, null);
                    if ((UInt32)outParams["ReturnValue"] == 0 && (string[])outParams["sNames"] != null)
                    {
                        isRebootPending = true;
                    }
                }
            }

            catch (ManagementException ex) when(ex.ErrorCode == ManagementStatus.NotFound)
            {
                // Target OS might not support WMI StdRegProv.  Attempt to gather data using remote registry.
                isRebootPending = false;
                const string serviceName      = "RemoteRegistry";
                bool         isLocal          = TargetComputer.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
                bool         isServiceRunning = true;

                // If the target computer is remote, then start the Remote Registry service.
                using (
                    GlobalVar.UseAlternateCredentials
                    ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                    : null)
                    using (var sc = new ServiceController(serviceName, TargetComputer))
                    {
                        try
                        {
                            if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                            {
                                isServiceRunning = false;
                                sc.Start();
                            }
                        }
                        catch (Exception)
                        {
                        }

                        try
                        {
                            using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, TargetComputer))
                            {
                                using (RegistryKey subKey = key.OpenSubKey(wuRegKey))
                                {
                                    if (subKey != null)
                                    {
                                        isRebootPending = true;
                                    }
                                }
                                using (RegistryKey subKey = key.OpenSubKey(cbsRegKey))
                                {
                                    if (subKey != null)
                                    {
                                        isRebootPending = true;
                                    }
                                }
                                using (RegistryKey subKey = key.OpenSubKey(pfroRegKey))
                                {
                                    if (subKey != null && subKey.GetValueNames().Length > 0)
                                    {
                                        isRebootPending = true;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }

                        // Cleanup.
                        if (!isLocal && !isServiceRunning)
                        {
                            try
                            {
                                if (sc != null)
                                {
                                    sc.Stop();
                                }
                            }

                            catch (Exception)
                            {
                            }
                        }
                    }
            }

            catch
            {
                // Do nothing.
            }
            finally
            {
                if (inParams != null)
                {
                    inParams.Dispose();
                }
                if (outParams != null)
                {
                    outParams.Dispose();
                }
            }

            return(isRebootPending);
        }
Esempio n. 5
0
        public static List <RemoteLogonSession> GetLogonSessions()
        {
            // GetProcesses() first uses WMI to determine if the target computer is running a desktop or server OS.
            // If running a server OS, it uses the Remote Desktop Service API to retrieve logon sessions.
            // If running a desktop OS, it uses WMI to retrieve logon sessions.
            // It returns a List of RemoteLogonSession which will be bound to a DataGrid on this UserControl.

            var logonSessions = new List <RemoteLogonSession>();
            var taskResult    = new TaskResult();

            Result = taskResult;
            UInt32 productType = 1;

            // Determine whether operating system is server or desktop edition.
            var options = new ConnectionOptions();

            if (GlobalVar.UseAlternateCredentials)
            {
                options.Username  = GlobalVar.AlternateUsername;
                options.Password  = GlobalVar.AlternatePassword;
                options.Authority = $"NTLMDOMAIN:{GlobalVar.AlternateDomain}";
            }
            var scope    = new ManagementScope($@"\\{ComputerName}\root\CIMV2", options);
            var query    = new ObjectQuery("SELECT ProductType FROM Win32_OperatingSystem");
            var searcher = new ManagementObjectSearcher(scope, query);

            try
            {
                foreach (ManagementObject m in searcher.Get())
                {
                    productType = (m["ProductType"] != null) ? (UInt32)m["ProductType"] : 1;
                    break;
                }
            }
            catch
            {
                taskResult.DidTaskSucceed = false;
                return(logonSessions);
            }
            IsServerEdition = productType > 1 ? true : false;

            // If operating system is server edition, use Remote Desktop Services API to retrieve logon sessions.
            if (IsServerEdition)
            {
                try
                {
                    using (
                        GlobalVar.UseAlternateCredentials
                        ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                        : null)
                    {
                        IntPtr server = WtsApi.WTSOpenServer(ComputerName);
                        logonSessions.AddRange(WtsApi.GetWindowsUsers(server));

                        foreach (RemoteLogonSession logonSession in logonSessions)
                        {
                            query    = new ObjectQuery($"SELECT CreationDate FROM Win32_Process WHERE SessionId = {logonSession.SessionId}");
                            searcher = new ManagementObjectSearcher(scope, query);
                            DateTime logonTime = DateTime.Now;
                            foreach (ManagementObject m in searcher.Get())
                            {
                                DateTime procCreationDate = ManagementDateTimeConverter.ToDateTime(m["CreationDate"].ToString());
                                if (procCreationDate < logonTime)
                                {
                                    logonSession.LogonTime = procCreationDate;
                                }
                            }
                        }
                    }
                    taskResult.DidTaskSucceed = true;
                }
                catch
                {
                    taskResult.DidTaskSucceed = false;
                }
            }
            // If operating system is desktop edition, query Win32_Process for explorer.exe to determine logged on users.
            else
            {
                query    = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");
                searcher = new ManagementObjectSearcher(scope, query);

                try
                {
                    foreach (ManagementObject m in searcher.Get())
                    {
                        var logonSession = new RemoteLogonSession();
                        logonSession.SessionId = (UInt32)m["SessionId"];
                        var dmtfDateTime = m["CreationDate"].ToString();
                        logonSession.LogonTime = ManagementDateTimeConverter.ToDateTime(dmtfDateTime);

                        string[] argList   = new string[] { string.Empty, string.Empty };
                        int      returnVal = Convert.ToInt32(m.InvokeMethod("GetOwner", argList));
                        if (returnVal == 0)
                        {
                            logonSession.Username = argList[0];
                            logonSession.Domain   = argList[1];
                        }
                        else
                        {
                            logonSession.Username = string.Empty;
                        }

                        int index = logonSessions.FindIndex(item => item.SessionId == logonSession.SessionId);
                        if (index >= 0)
                        {
                            continue;
                        }
                        else
                        {
                            logonSessions.Add(logonSession);
                        }
                    }
                    taskResult.DidTaskSucceed = true;
                }
                catch
                {
                    taskResult.DidTaskSucceed = false;
                }
            }

            return(logonSessions);
        }
Esempio n. 6
0
        public static DialogResult StopService(RemoteService service)
        {
            var  dialog          = new DialogResult();
            bool didTaskSucceed  = false;
            bool didTimeoutOccur = false;

            using (
                GlobalVar.UseAlternateCredentials
                ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                : null)
                using (var sc = new ServiceController(service.Name, ComputerName))
                {
                    try
                    {
                        if (sc.Status != ServiceControllerStatus.Stopped)
                        {
                            sc.Stop();
                            sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
                            if (sc.Status == ServiceControllerStatus.StopPending)
                            {
                                didTimeoutOccur = true;
                            }
                            else
                            {
                                didTaskSucceed = true;
                            }
                        }
                        else
                        {
                            dialog.DialogBody = $"{service.DisplayName} is already stopped.";
                        }
                    }

                    catch
                    {
                    }
                }

            if (didTaskSucceed)
            {
                // Service started.  Build DialogResult to reflect success.
                dialog.DialogTitle     = "Success";
                dialog.DialogBody      = $"{service.DisplayName} is now stopped.";
                dialog.DialogIconPath  = "/Resources/success-48.png";
                dialog.ButtonIconPath  = "/Resources/checkmark-24.png";
                dialog.ButtonText      = "OK";
                dialog.IsCancelVisible = false;
            }
            else
            {
                // Service failed to start.  Build DialogResult to reflect failure.
                dialog.DialogTitle = "Error";
                if (string.IsNullOrEmpty(dialog.DialogBody))
                {
                    dialog.DialogBody = $"Failed to stop {service.DisplayName}.";
                }
                dialog.DialogIconPath  = "/Resources/error-48.png";
                dialog.ButtonIconPath  = "/Resources/checkmark-24.png";
                dialog.ButtonText      = "OK";
                dialog.IsCancelVisible = false;
                if (didTimeoutOccur)
                {
                    dialog.DialogBody = $"Timed out waiting for {service.DisplayName} to stop.";
                }
            }

            return(dialog);
        }
Esempio n. 7
0
        public static DialogResult StartService(RemoteService service)
        {
            // StartService() attempts to start the specified service.
            // It returns a DialogResult which will be used to display the results.
            var  dialog          = new DialogResult();
            bool didTaskSucceed  = false;
            bool didTimeoutOccur = false;

            using (
                GlobalVar.UseAlternateCredentials
                ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                : null)
                using (var sc = new ServiceController(service.Name, ComputerName))
                {
                    try
                    {
                        if (sc.Status == ServiceControllerStatus.Stopped)
                        {
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
                            if (sc.Status == ServiceControllerStatus.StartPending)
                            {
                                didTimeoutOccur = true;
                            }
                            else
                            {
                                didTaskSucceed = true;
                            }
                        }
                    }

                    catch
                    {
                        if (service.StartupType == "Disabled")
                        {
                            dialog.DialogBody = "You cannot start a service that is disabled.";
                        }
                        else
                        {
                            dialog.DialogBody = $"Failed to start {service.DisplayName}.";
                        }
                    }
                }

            if (didTaskSucceed)
            {
                // Service started.  Build DialogResult to reflect success.
                dialog.DialogTitle     = "Success";
                dialog.DialogBody      = $"{service.DisplayName} is now running.";
                dialog.DialogIconPath  = "/Resources/success-48.png";
                dialog.ButtonIconPath  = "/Resources/checkmark-24.png";
                dialog.ButtonText      = "OK";
                dialog.IsCancelVisible = false;
            }
            else
            {
                // Service failed to start.  Build DialogResult to reflect failure.
                dialog.DialogTitle     = "Error";
                dialog.DialogIconPath  = "/Resources/error-48.png";
                dialog.ButtonIconPath  = "/Resources/checkmark-24.png";
                dialog.ButtonText      = "OK";
                dialog.IsCancelVisible = false;
                if (didTimeoutOccur)
                {
                    dialog.DialogBody = $"Timed out waiting for {service.DisplayName} to start.";
                }
            }

            return(dialog);
        }
Esempio n. 8
0
        public static List <RemoteOdbc> GetOdbcDsn()
        {
            var odbcEntries = new List <RemoteOdbc>();

            const string odbcDataSources             = @"SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources";
            const string odbcDataSources32bitOn64bit = @"SOFTWARE\Wow6432Node\ODBC\ODBC.INI\ODBC Data Sources";
            const string odbcRoot             = @"SOFTWARE\ODBC\ODBC.INI";
            const string odbcRoot32bitOn64bit = @"SOFTWARE\Wow6432Node\ODBC\ODBC.INI";
            const string serviceName          = "RemoteRegistry";
            bool         isLocal          = RemoteSystemInfo.TargetComputer.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
            bool         isServiceRunning = true;

            // If the target computer is remote, then start the Remote Registry service.
            using (
                GlobalVar.UseAlternateCredentials
                ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                : null)
                using (var sc = new ServiceController(serviceName, RemoteSystemInfo.TargetComputer))
                {
                    try
                    {
                        if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                        {
                            isServiceRunning = false;
                            sc.Start();
                            sc.WaitForStatus(ServiceControllerStatus.Running);
                        }
                    }
                    catch (Exception)
                    {
                    }

                    try
                    {
                        using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, RemoteSystemInfo.TargetComputer))
                        {
                            if (RemoteSystemInfo.WindowsArchitecture == "64-bit")
                            {
                                using (RegistryKey subKey = key.OpenSubKey(odbcDataSources32bitOn64bit))
                                {
                                    if (subKey != null)
                                    {
                                        foreach (var value in subKey.GetValueNames())
                                        {
                                            odbcEntries.Add(new RemoteOdbc
                                            {
                                                DataSourceName     = value,
                                                DataSourceDriver   = subKey.GetValue(value).ToString(),
                                                ArchitectureString = "32-bit",
                                                Is32bitOn64bit     = true
                                            });
                                        }
                                    }
                                }
                                using (RegistryKey subKey = key.OpenSubKey(odbcDataSources))
                                {
                                    if (subKey != null)
                                    {
                                        foreach (var value in subKey.GetValueNames())
                                        {
                                            odbcEntries.Add(new RemoteOdbc
                                            {
                                                DataSourceName     = value,
                                                DataSourceDriver   = subKey.GetValue(value).ToString(),
                                                ArchitectureString = "64-bit",
                                                Is32bitOn64bit     = false
                                            });
                                        }
                                    }
                                }

                                using (RegistryKey subKey = key.OpenSubKey(odbcRoot))
                                {
                                    if (subKey != null)
                                    {
                                        foreach (var dataSource in odbcEntries)
                                        {
                                            if (dataSource.Is32bitOn64bit)
                                            {
                                                continue;
                                            }

                                            using (RegistryKey subSubKey = subKey.OpenSubKey(dataSource.DataSourceName))
                                            {
                                                if (subSubKey != null)
                                                {
                                                    foreach (var value in subSubKey.GetValueNames())
                                                    {
                                                        dataSource.Values.Add(new RemoteOdbcValue
                                                        {
                                                            OdbcValueName = value,
                                                            OdbcValueData = subSubKey.GetValue(value).ToString()
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                using (RegistryKey subKey = key.OpenSubKey(odbcRoot32bitOn64bit))
                                {
                                    if (subKey != null)
                                    {
                                        foreach (var dataSource in odbcEntries)
                                        {
                                            if (!dataSource.Is32bitOn64bit)
                                            {
                                                continue;
                                            }

                                            using (RegistryKey subSubKey = subKey.OpenSubKey(dataSource.DataSourceName))
                                            {
                                                if (subSubKey != null)
                                                {
                                                    foreach (var value in subSubKey.GetValueNames())
                                                    {
                                                        dataSource.Values.Add(new RemoteOdbcValue
                                                        {
                                                            OdbcValueName = value,
                                                            OdbcValueData = subSubKey.GetValue(value).ToString()
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                using (RegistryKey subKey = key.OpenSubKey(odbcDataSources))
                                {
                                    if (subKey != null)
                                    {
                                        foreach (var value in subKey.GetValueNames())
                                        {
                                            odbcEntries.Add(new RemoteOdbc
                                            {
                                                DataSourceName     = value,
                                                DataSourceDriver   = subKey.GetValue(value).ToString(),
                                                ArchitectureString = "32-bit",
                                                Is32bitOn64bit     = false
                                            });
                                        }
                                    }
                                }

                                using (RegistryKey subKey = key.OpenSubKey(odbcRoot))
                                {
                                    if (subKey != null)
                                    {
                                        foreach (var dataSource in odbcEntries)
                                        {
                                            using (RegistryKey subSubKey = subKey.OpenSubKey(dataSource.DataSourceName))
                                            {
                                                if (subSubKey != null)
                                                {
                                                    foreach (var value in subSubKey.GetValueNames())
                                                    {
                                                        dataSource.Values.Add(new RemoteOdbcValue
                                                        {
                                                            OdbcValueName = value,
                                                            OdbcValueData = subSubKey.GetValue(value).ToString()
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch { }

                    // Cleanup.
                    if (!isLocal && !isServiceRunning)
                    {
                        try
                        {
                            if (sc != null)
                            {
                                sc.Stop();
                            }
                        }

                        catch (Exception)
                        {
                        }
                    }
                }

            return(odbcEntries);
        }
        public static List <RemoteLogonHistory> GetLogonHistory()
        {
            var logonHistory = new List <RemoteLogonHistory>();

            Result = new TaskResult();

            const int logonEventId   = 4624;
            const int logoffEventIdA = 4634;
            const int logoffEventIdB = 4647;
            const int landeskRemoteControlEventId = 2;

            string queryString =
                "<QueryList><Query Id='1'>" +
                "<Select Path='Security'>" +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logonEventId + ")]] and " +
                "*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] and " +
                "*[EventData[Data[@Name='LogonGuid'] != '{00000000-0000-0000-0000-000000000000}']] and " +
                "*[EventData[Data[@Name='LogonProcessName'] != 'seclogo']]" +
                "</Select>" +
                "<Select Path='Security'>" +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logonEventId + ")]] and " +
                "*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] and " +
                "*[EventData[Data[@Name='TargetDomainName'] = '" + RemoteLogonSession.ComputerName.ToUpper().Trim() + "']]" +
                "</Select>" +
                "<Select Path='Security'>" +
                //"*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                //"(EventID=" + logoffEventIdA + ")]] and " +
                //"*[EventData[Data[@Name='LogonType'] and (Data='2' or Data='10')]] or " +
                "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and " +
                "(EventID=" + logoffEventIdB + ")]]" +
                "</Select>" +
                "<Select Path='Application'>" +
                "*[System[Provider[@Name='LANDESK Remote Control Service'] and (EventID=" + landeskRemoteControlEventId + ")]]" +
                "</Select>" +
                "</Query></QueryList>";

            try
            {
                var eventLogSession = new EventLogSession(RemoteLogonSession.ComputerName);
                var eventLogQuery   = new EventLogQuery("Security", PathType.LogName, queryString);
                eventLogQuery.ReverseDirection = true;
                eventLogQuery.Session          = eventLogSession;

                using (
                    GlobalVar.UseAlternateCredentials
                        ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                        : null)
                    using (var eventLogReader = new EventLogReader(eventLogQuery))
                    {
                        for (EventRecord eventLogRecord = eventLogReader.ReadEvent(); null != eventLogRecord; eventLogRecord = eventLogReader.ReadEvent())
                        {
                            string regexString;

                            switch (eventLogRecord.Id)
                            {
                            case (logonEventId):
                                regexString = @"An account was successfully logged on.*Logon Type:\s+(?<logonType>.*?)\r" +
                                              @".*\tAccount Name:\s+(?<accountName>.*?)\r" +
                                              @".*\tAccount Domain:\s+(?<accountDomain>.*?)\r" +
                                              @".*Network Information:.*Source Network Address:\s+(?<sourceIpAddress>.*?)\r";
                                break;

                            case (landeskRemoteControlEventId):
                                regexString = @"^Remote control action: (?<controlAction>\w+?) Remote Control  Initiated from (?<sourceHostname>.*?) by user " +
                                              @"(?<accountName>.*?), Security Type";
                                break;

                            case (logoffEventIdA):
                                regexString = @"An account was logged off" +
                                              @".*Subject:.*Account Name:\s+(?<accountName>.*?)\r" +
                                              @".*Account Domain:\s+(?<accountDomain>.*?)\r" +
                                              @".*Logon Type:\s+(?<logonType>.*?)\r";
                                break;

                            case (logoffEventIdB):
                                regexString = @"User initiated logoff" +
                                              @".*Subject:.*Account Name:\s+(?<accountName>.*?)\r" +
                                              @".*Account Domain:\s+(?<accountDomain>.*?)\r";
                                break;

                            default:
                                regexString = string.Empty;
                                break;
                            }
                            var match = Regex.Match(eventLogRecord.FormatDescription(), regexString, RegexOptions.Singleline);

                            if (match.Success)
                            {
                                switch (eventLogRecord.Id)
                                {
                                case (logonEventId):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = match.Groups["logonType"].Value,
                                        IpAddress   = match.Groups["sourceIpAddress"].Value
                                    });
                                    break;

                                case (landeskRemoteControlEventId):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonDomain = string.Empty,
                                        LogonType   = "LANDesk",
                                        LogonAction = match.Groups["controlAction"].Value,
                                        IpAddress   = match.Groups["sourceHostname"].Value
                                    });
                                    break;

                                case (logoffEventIdA):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = "Logoff"
                                    });
                                    break;

                                case (logoffEventIdB):
                                    logonHistory.Add(new RemoteLogonHistory
                                    {
                                        LogonTime   = eventLogRecord.TimeCreated.Value,
                                        LogonDomain = match.Groups["accountDomain"].Value,
                                        LogonName   = match.Groups["accountName"].Value,
                                        LogonType   = "Logoff"
                                    });
                                    break;
                                }
                            }
                        }

                        Result.DidTaskSucceed = true;
                    }
            }
            catch (UnauthorizedAccessException)
            {
                Result.DidTaskSucceed = false;
                Result.MessageBody    = "This feature is currently only supported on Windows Vista and Server 2008 or higher.";
            }
            catch
            {
                Result.DidTaskSucceed = false;
            }

            return(logonHistory);
        }
Esempio n. 10
0
        public static List <RemoteApplication> GetInstalledApplications()
        {
            var apps       = new List <RemoteApplication>();
            var taskResult = new TaskResult();

            Result = taskResult;

            const string uninstallKey64   = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            const string uninstallKey32   = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
            const string serviceName      = "RemoteRegistry";
            bool         isLocal          = ComputerName.ToUpper() == Environment.MachineName.ToUpper() ? true : false;
            bool         isServiceRunning = true;

            // If the target computer is remote, then start the Remote Registry service.
            using (
                GlobalVar.UseAlternateCredentials
                ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                : null)
                using (var sc = new ServiceController(serviceName, ComputerName))
                {
                    try
                    {
                        if (!isLocal && sc.Status != ServiceControllerStatus.Running)
                        {
                            isServiceRunning = false;
                            sc.Start();
                        }
                    }
                    catch (Exception)
                    {
                    }

                    try
                    {
                        using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName))
                        {
                            using (RegistryKey mainKey64 = key.OpenSubKey(uninstallKey64))
                                apps.AddRange(EnumerateUninstallKeys(mainKey64));
                            using (RegistryKey mainKey32 = key.OpenSubKey(uninstallKey32))
                                apps.AddRange(EnumerateUninstallKeys(mainKey32));
                        }

                        var internetExplorerVersion = FileVersionInfo.GetVersionInfo($@"\\{ComputerName}\C$\Program Files\Internet Explorer\iexplore.exe");
                        if (internetExplorerVersion != null && internetExplorerVersion.ProductVersion.Length > 0)
                        {
                            apps.Add(new RemoteApplication
                            {
                                DisplayName = "Internet Explorer",
                                Publisher   = "Microsoft Corporation",
                                Version     = internetExplorerVersion.ProductVersion
                            });
                        }

                        taskResult.DidTaskSucceed = true;
                    }
                    catch
                    {
                        taskResult.DidTaskSucceed = false;
                    }


                    // Cleanup.
                    if (!isLocal && !isServiceRunning)
                    {
                        try
                        {
                            if (sc != null)
                            {
                                sc.Stop();
                            }
                        }

                        catch (Exception)
                        {
                        }
                    }
                }

            return(apps);
        }