예제 #1
0
        public static Exception UnlockWithNumericalPassword(ManagementObject encryptableVolume, string numericalPassword, out int returnValueUnlockWithNumericalPassword)
        {
            ManagementBaseObject outParams = null;
            int       returnValue          = -1;
            Exception ex = Util.HandleExceptions(delegate
            {
                string deviceId = BitlockerUtil.GetDeviceId(encryptableVolume);
                Exception ex2;
                if (!BitlockerLockUtil.IsVolumeLocked(encryptableVolume, out ex2))
                {
                    returnValue = 0;
                    throw new VolumeLockedFindException(deviceId, ex2.Message, ex2);
                }
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "UnlockWithNumericalPassword", new string[]
                {
                    "NumericalPassword"
                }, new object[]
                {
                    numericalPassword
                }, out outParams);
            });

            returnValueUnlockWithNumericalPassword = returnValue;
            Util.AssertReturnValueExceptionInconsistency(returnValueUnlockWithNumericalPassword, "UnlockWithNumericalPassword", ex);
            return(Util.ReturnWMIErrorExceptionOnExceptionOrError(returnValueUnlockWithNumericalPassword, "UnlockWithNumericalPassword", ex));
        }
예제 #2
0
        public static Exception LockDataVolume(ManagementObject encryptableVolume, out int returnValueLock)
        {
            ManagementBaseObject outParams = null;
            int       returnValue          = -1;
            Exception ex = Util.HandleExceptions(delegate
            {
                string deviceId = BitlockerUtil.GetDeviceId(encryptableVolume);
                Exception ex2;
                if (BitlockerLockUtil.IsVolumeLocked(encryptableVolume, out ex2))
                {
                    if (ex2 != null)
                    {
                        throw new VolumeLockedFindException(deviceId, ex2.Message, ex2);
                    }
                }
                else
                {
                    returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "Lock", null, null, out outParams);
                    if (BitlockerLockUtil.IsVolumeLocked(encryptableVolume, out ex2) && ex2 != null)
                    {
                        throw new VolumeLockedFindException(deviceId, ex2.Message, ex2);
                    }
                }
            });

            returnValueLock = returnValue;
            Util.AssertReturnValueExceptionInconsistency(returnValueLock, "LockDataVolume", ex);
            return(Util.ReturnWMIErrorExceptionOnExceptionOrError(returnValueLock, "LockDataVolume", ex));
        }
예제 #3
0
        public static Dictionary <string, string> GetMountPointVolumeIDMappings(out Exception ex)
        {
            Dictionary <string, string> mountPointVolumeIdMappings = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            ex = null;
            ManagementObjectCollection mountPointToVolumeMappings = WMIUtil.GetManagementObjectCollection("Win32_MountPoint", "\\ROOT\\CIMV2", out ex);

            if (mountPointToVolumeMappings == null)
            {
                return(null);
            }
            ex = Util.HandleExceptions(delegate
            {
                using (ManagementObjectCollection mountPointToVolumeMappings = mountPointToVolumeMappings)
                {
                    foreach (ManagementBaseObject managementBaseObject in mountPointToVolumeMappings)
                    {
                        ManagementObject managementObject = (ManagementObject)managementBaseObject;
                        using (managementObject)
                        {
                            string input   = managementObject.GetPropertyValue("Volume").ToString();
                            string input2  = managementObject.GetPropertyValue("Directory").ToString();
                            string pattern = "\"(.*)\"";
                            Match match    = Regex.Match(input, pattern);
                            Match match2   = Regex.Match(input2, pattern);
                            if (match.Success && match2.Success)
                            {
                                mountPointVolumeIdMappings.Add(Util.RemoveEscapeCharacters(match2.Groups[1].Value), Util.RemoveEscapeCharacters(match.Groups[1].Value));
                            }
                        }
                    }
                }
            });
            return(mountPointVolumeIdMappings);
        }
예제 #4
0
        public static Exception Resume(ManagementObject encryptableVolume, out int returnValueResume)
        {
            Exception ex          = null;
            int       returnValue = -1;

            returnValueResume = -1;
            if (encryptableVolume == null)
            {
                return(new EncryptableVolumeArgNullException("Resume"));
            }
            string volume = encryptableVolume.GetPropertyValue("DeviceId").ToString();

            if (BitlockerLockUtil.IsVolumeLocked(encryptableVolume, out ex))
            {
                ex = new VolumeLockedException(volume);
                return(ex);
            }
            ex = Util.HandleExceptions(delegate
            {
                ManagementBaseObject managementBaseObject = null;
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "ResumeConversion", null, null, out managementBaseObject);
            });
            returnValueResume = returnValue;
            Util.AssertReturnValueExceptionInconsistency(returnValueResume, "Resume", ex);
            return(Util.ReturnWMIErrorExceptionOnExceptionOrError(returnValueResume, "Resume", ex));
        }
예제 #5
0
        public static Exception AddNumericalPassword(ManagementObject encryptableVolume, string numericalPassword, out int returnValueNumericalPassword)
        {
            Exception ex = null;

            if (BitlockerLockUtil.IsVolumeLocked(encryptableVolume, out ex))
            {
                returnValueNumericalPassword = 0;
                return(ex);
            }
            int returnValue = -1;
            ManagementBaseObject outParams = null;

            ex = Util.HandleExceptions(delegate
            {
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "ProtectKeyWithNumericalPassword", new string[]
                {
                    "FriendlyName",
                    "NumericalPassword"
                }, new object[]
                {
                    "FriendlyName",
                    numericalPassword
                }, out outParams);
            });
            returnValueNumericalPassword = returnValue;
            Util.AssertReturnValueExceptionInconsistency(returnValueNumericalPassword, "AddNumericalPassword", ex);
            return(Util.ReturnWMIErrorExceptionOnExceptionOrError(returnValueNumericalPassword, "AddNumericalPassword", ex));
        }
예제 #6
0
        public static Exception AddCertificateBasedKeyProtectors(ManagementObject encryptableVolume, out int returnValueCertificate)
        {
            int returnValue = -1;

            returnValueCertificate = -1;
            Exception result = null;
            ArrayList bitlockerCertThumbPrints = BitlockerUtil.GetBitlockerCertThumbPrints(out result);

            if (bitlockerCertThumbPrints == null)
            {
                return(new BitlockerCertificatesNotFoundException());
            }
            using (IEnumerator enumerator = bitlockerCertThumbPrints.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    string bitlockerCertThumbPrint = (string)enumerator.Current;
                    result = Util.HandleExceptions(delegate
                    {
                        ManagementBaseObject managementBaseObject = null;
                        returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "ProtectKeyWithCertificateThumbprint", new string[]
                        {
                            "FriendlyName",
                            "CertThumbprint"
                        }, new object[]
                        {
                            bitlockerCertThumbPrint,
                            bitlockerCertThumbPrint
                        }, out managementBaseObject);
                    });
                }
            }
            returnValueCertificate = returnValue;
            return(result);
        }
예제 #7
0
        public static Exception Decrypt(ManagementObject encryptableVolume, out int returnValueDecrypt)
        {
            ManagementBaseObject outParams = null;
            int       returnValue          = -1;
            Exception ex = Util.HandleExceptions(delegate
            {
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "Decrypt", null, null, out outParams);
            });

            returnValueDecrypt = returnValue;
            Util.AssertReturnValueExceptionInconsistency(returnValueDecrypt, "Decrypt", ex);
            return(Util.ReturnWMIErrorExceptionOnExceptionOrError(returnValueDecrypt, "Decrypt", ex));
        }
예제 #8
0
        public Runtime(IOutputSink outputSink, IEnumerable <string> commands, IEnumerable <string> commandGroups, bool filter, string computerName, string userName, string password)
        {
            OutputSink    = outputSink;
            Commands      = commands;
            CommandGroups = commandGroups;
            FilterResults = filter;
            ComputerName  = computerName;
            UserName      = userName;
            Password      = password;

            // test a remote connection first if a remote system is specified
            if (!string.IsNullOrEmpty(computerName))
            {
                try
                {
                    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                    {
                        OutputSink.WriteHost($"[*] Running commands remotely against the host '{computerName}' with credentials -> user:{UserName} , password:{Password}\r\n");

                        var options = new ConnectionOptions();
                        options.Username         = UserName;
                        options.Password         = Password;
                        options.Impersonation    = ImpersonationLevel.Impersonate;
                        options.EnablePrivileges = true;

                        var scope = new ManagementScope($"\\\\{computerName}\\root\\cimv2", options);
                        scope.Connect();
                    }
                    else
                    {
                        OutputSink.WriteHost($"[*] Running commands remotely against the host '{computerName}' with current user credentials\r\n");

                        var scope = new ManagementScope($"\\\\{computerName}\\root\\cimv2");
                        scope.Connect();
                    }
                    InitializeCommands();
                }
                catch (Exception e)
                {
                    OutputSink.WriteError($"Error connecting to \"{computerName}\" : {e.Message}");
                    Environment.Exit(1);
                }

                wmiRegProv = WMIUtil.WMIRegConnection(computerName, userName, password);
            }
            else
            {
                InitializeCommands();
            }
        }
예제 #9
0
        private void AddTableRow(DataTable table, ManagementBaseObject entry)
        {
            DataRow row = table.NewRow();

            row["EntryType"]   = GetEventTypeString(((SmoothyInterface.Util.NTLogEvent.EventTypeValues)(System.Convert.ToInt32(entry["EventType"]))));
            row["TimeWritten"] = WMIUtil.ToDateTime(((string)(entry["TimeWritten"])));
            row["Category"]    = ((ushort)(entry["Category"]));
            row["Source"]      = ((string)(entry["SourceName"]));
            row["EventID"]     = ((uint)(entry["EventIdentifier"]));
            row["Index"]       = ((uint)(entry["RecordNumber"]));
            row["Message"]     = String.Empty;

            table.Rows.Add(row);

            UpdateCounters(entry);
        }
예제 #10
0
        public static int GetBitlockerEncryptionPercentage(ManagementObject encryptableVolume, out int returnValueEncryptionPercentage, out Exception ex)
        {
            ManagementBaseObject outParams         = null;
            int encryptionPercentageWMIReturnValue = -1;
            int returnValue = -1;

            ex = null;
            ex = Util.HandleExceptions(delegate
            {
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "GetConversionStatus", null, null, out outParams);
                if (returnValue == 0)
                {
                    int.TryParse(outParams["EncryptionPercentage"].ToString(), out encryptionPercentageWMIReturnValue);
                }
            });
            returnValueEncryptionPercentage = returnValue;
            return(encryptionPercentageWMIReturnValue);
        }
예제 #11
0
        public static bool IsVolumeLocked(ManagementObject encryptableVolume, out Exception ex)
        {
            ManagementBaseObject outParams = null;
            bool success = false;

            ex = Util.HandleExceptions(delegate
            {
                if (WMIUtil.CallWMIMethod(encryptableVolume, "GetLockStatus", null, null, out outParams) == 0)
                {
                    int num = Convert.ToInt32(outParams["LockStatus"]);
                    if (Enum.IsDefined(typeof(BitlockerLockUtil.LockStatus), num))
                    {
                        BitlockerLockUtil.LockStatus lockStatus = (BitlockerLockUtil.LockStatus)num;
                        success = (lockStatus == BitlockerLockUtil.LockStatus.Locked);
                    }
                }
            });
            Util.ThrowIfNotNull(ex);
            return(success);
        }
예제 #12
0
        public static Exception Encrypt(ManagementObject encryptableVolume, bool usedOnly, out int returnValueEncrypt)
        {
            Exception ex          = null;
            int       returnValue = -1;

            if (BitlockerLockUtil.IsVolumeLocked(encryptableVolume, out ex))
            {
                returnValueEncrypt = 0;
                return(ex);
            }
            ex = Util.HandleExceptions(delegate
            {
                ManagementBaseObject managementBaseObject = null;
                if (Util.IsOperatingSystemWin8OrHigher() && usedOnly)
                {
                    returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "Encrypt", new string[]
                    {
                        "EncryptionMethod",
                        "EncryptionFlags"
                    }, new object[]
                    {
                        4,
                        1
                    }, out managementBaseObject);
                    return;
                }
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "Encrypt", new string[]
                {
                    "EncryptionMethod"
                }, new object[]
                {
                    4
                }, out managementBaseObject);
            });
            returnValueEncrypt = returnValue;
            Util.AssertReturnValueExceptionInconsistency(returnValueEncrypt, "Encrypt", ex);
            return(Util.ReturnWMIErrorExceptionOnExceptionOrError(returnValueEncrypt, "Encrypt", ex));
        }
예제 #13
0
        public static BitlockerUtil.BitlockerConversionState GetBitlockerConversionState(ManagementObject encryptableVolume, out int returnValueConversionState, out Exception ex)
        {
            BitlockerUtil.BitlockerConversionState bitlockerConversionState = BitlockerUtil.BitlockerConversionState.Unknown;
            ManagementBaseObject outParams = null;

            ex = null;
            int returnValue = -1;

            ex = Util.HandleExceptions(delegate
            {
                returnValue = WMIUtil.CallWMIMethod(encryptableVolume, "GetConversionStatus", null, null, out outParams);
                if (returnValue == 0)
                {
                    int num = Convert.ToInt32(outParams["ConversionStatus"]);
                    if (Enum.IsDefined(typeof(BitlockerUtil.BitlockerConversionState), num))
                    {
                        bitlockerConversionState = (BitlockerUtil.BitlockerConversionState)num;
                    }
                }
            });
            returnValueConversionState = returnValue;
            return(bitlockerConversionState);
        }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = null;

        if (startInfo.Parameters != null)
        {
            parameters = HandlerUtils.Deserialize <CommandHandlerParameters>(startInfo.Parameters);
        }

        try
        {
            OnLogMessage("Execute", $"Running Handler As User [{System.Security.Principal.WindowsIdentity.GetCurrent().Name}]");

            Validate();

            // Replace Any "Special" Handler Variables In Arguments or ReplaceWith elements
            variables            = HandlerUtils.GatherVariables(this, startInfo);
            parameters.Arguments = HandlerUtils.ReplaceHandlerVariables(parameters.Arguments, variables);
            if (parameters.Expressions != null)
            {
                foreach (RegexArguments expression in parameters.Expressions)
                {
                    expression.ReplaceWith = HandlerUtils.ReplaceHandlerVariables(expression.ReplaceWith, variables);
                }
            }

            String args = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);

            bool isDryRun = startInfo.IsDryRun && !(config.SupportsDryRun);
            if (startInfo.IsDryRun && config.SupportsDryRun)
            {
                OnLogMessage("Execute", "DryRun Flag is set, but plan config indicates the command supports DryRun.  Command will execute.");
            }

            if (String.IsNullOrEmpty(config.RunOn))
            {
                SecurityContext runAs = startInfo.RunAs;
                if (runAs != null && runAs.HasCrypto)
                {
                    runAs = startInfo.RunAs.GetCryptoValues(startInfo.RunAs.Crypto, false);
                }
                result = LocalProcess.RunCommand(config.Command, args, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, SynapseLogger, null, isDryRun, config.ReturnStdout, runAs?.Domain, runAs?.UserName, runAs?.Password);
            }
            else
            {
                result = WMIUtil.RunCommand(config.Command, args, config.RunOn, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, config.KillRemoteProcessOnTimeout, SynapseLogger, config.RunOn, isDryRun, config.ReturnStdout);
            }

            if (result.Status == StatusType.None)
            {
                result.Status = HandlerUtils.GetStatusType(result.ExitCode, config.ValidExitCodes);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            throw e;
        }

        OnLogMessage(config.RunOn, "Command finished with exit code = " + result.ExitCode + ".  Returning status [" + result.Status + "].");

        return(result);
    }
예제 #15
0
        public static ManagementObjectCollection GetEncryptableVolumes()
        {
            Exception ex;

            return(WMIUtil.GetManagementObjectCollection("Win32_EncryptableVolume", "\\ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption", out ex));
        }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = null;

        if (startInfo.Parameters != null)
        {
            parameters = HandlerUtils.Deserialize <ScriptHandlerParameters>(startInfo.Parameters);
        }
        String script = null;

        try
        {
            String command      = null;
            String args         = null;
            bool   isTempScript = false;

            OnLogMessage("Execute", $"Running Handler As User [{System.Security.Principal.WindowsIdentity.GetCurrent().Name}]");

            Validate();

            // Replace Any "Special" Handler Variables In Arguments or ReplaceWith elements
            variables            = HandlerUtils.GatherVariables(this, startInfo);
            parameters.Arguments = HandlerUtils.ReplaceHandlerVariables(parameters.Arguments, variables);
            if (parameters.Expressions != null)
            {
                foreach (RegexArguments expression in parameters.Expressions)
                {
                    expression.ReplaceWith = HandlerUtils.ReplaceHandlerVariables(expression.ReplaceWith, variables);
                }
            }

            switch (config.Type)
            {
            case ScriptType.Powershell:
                command = "powershell.exe";
                if (!String.IsNullOrWhiteSpace(parameters.Script))
                {
                    isTempScript = false;
                    script       = parameters.Script;
                }
                else
                {
                    isTempScript = true;
                    script       = CreateTempScriptFile(parameters.ScriptBlock, "ps1");
                }
                args = config.Arguments + @" -File """ + script + @"""";
                if (!String.IsNullOrWhiteSpace(parameters.Arguments))
                {
                    String scriptArgs = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);
                    args += " " + scriptArgs;
                }
                break;

            case ScriptType.Batch:
                command = "cmd.exe";
                if (!String.IsNullOrWhiteSpace(parameters.Script))
                {
                    isTempScript = false;
                    script       = parameters.Script;
                }
                else
                {
                    isTempScript = true;
                    script       = CreateTempScriptFile(parameters.ScriptBlock, "bat");
                }
                args = config.Arguments + @" """ + script + @"""";
                if (!String.IsNullOrWhiteSpace(parameters.Arguments))
                {
                    String scriptArgs = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);
                    args += " " + scriptArgs;
                }

                break;

            default:
                throw new Exception("Unknown ScriptType [" + config.Type.ToString() + "] Received.");
            }

            bool isDryRun = startInfo.IsDryRun && !(config.SupportsDryRun);
            if (startInfo.IsDryRun && config.SupportsDryRun)
            {
                OnLogMessage("Execute", "DryRun Flag is set, but plan config indicates the script supports DryRun.  Script will execute.");
            }

            if (String.IsNullOrEmpty(config.RunOn))
            {
                SecurityContext runAs = startInfo.RunAs;
                if (runAs != null && runAs.HasCrypto)
                {
                    runAs = startInfo.RunAs.GetCryptoValues(startInfo.RunAs.Crypto, false);
                }
                result = LocalProcess.RunCommand(command, args, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, SynapseLogger, null, isDryRun, config.ReturnStdout, runAs?.Domain, runAs?.UserName, runAs?.Password);
            }
            else
            {
                result = WMIUtil.RunCommand(command, args, config.RunOn, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, config.KillRemoteProcessOnTimeout, SynapseLogger, config.RunOn, isDryRun, config.ReturnStdout);
            }

            if (result.Status == StatusType.None)
            {
                result.Status = HandlerUtils.GetStatusType(result.ExitCode, config.ValidExitCodes);
            }

            if (File.Exists(script) && isTempScript)
            {
                File.Delete(script);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            if (File.Exists(script))
            {
                File.Delete(script);
            }
            throw e;
        }

        OnLogMessage(config.RunOn, "Command finished with exit code = " + result.ExitCode + ".  Returning status [" + result.Status + "].");
        return(result);
    }