/// <summary> /// Tries to connect to the host specified. The connection is used WMI. /// </summary> /// <param name="target">Host to Connect</param> public void Connect(TargetInfo target) { try { Credentials credentials = target.IsLocalTarget() ? null : target.credentials; ConnectionOptions options = this.GetConnectionOptions(credentials); this.ConnectionScope = this.GetManagementScope(options, target.GetAddress()); } catch (UnauthorizedAccessException unauthorizedAccessException) { string errorMessage = string.Format(INVALID_CREDENTIALS_ERROR_MESSAGE, target.GetAddress(), target.credentials.GetDomain(), target.credentials.GetUserName()); throw new InvalidCredentialsException(target.credentials, errorMessage, unauthorizedAccessException); } catch (COMException comException) { string errorMessage = string.Format(PROVIDER_CONNECTING_ERROR_MESSAGE, target.GetAddress(), comException.Message); throw new CannotConnectToHostException(target, errorMessage, comException); } catch (Exception ex) { string errorMessage = string.Format(PROVIDER_CONNECTING_ERROR_MESSAGE, target.GetAddress(), ex.Message); throw new ProbeException(errorMessage, ex); } }
private RegistryKey TryToOpenRemoteKey(TargetInfo targetInfo, string registryHiveAsString, string registryKey) { var keyPath = this.CombineHiveAndKey(registryHiveAsString, registryKey); RegistryKey registryHive = null; try { var hive = (RegistryHive)Enum.Parse(typeof(RegistryHive), registryHiveAsString); var isLocal = targetInfo.GetAddress().Equals("127.0.0.1") || targetInfo.GetAddress().Trim().ToLower().Equals("localhost"); registryHive = RegistryKey.OpenRemoteBaseKey(hive, isLocal ? string.Empty : targetInfo.GetAddress()); //RegistrySecurity rs = registryHive.GetAccessControl(AccessControlSections.Access); //rs.SetAccessRuleProtection(true, true); //this line you need to set ACL on a remote machines registry key. } catch (UnauthorizedAccessException) { throw new RegistryKeyEffectiveRightsAccessDenied(targetInfo.GetAddress(), keyPath); } var remoteKey = string.IsNullOrEmpty(registryKey) ? registryHive : registryHive.OpenSubKey(registryKey); if (remoteKey == null) { throw new RegistryKeyEffectiveRightsNotFoundException(targetInfo.GetAddress(), keyPath); } return(remoteKey); }
public TargetCheckingResult Check(TargetInfo targetInfo) { var targetAvailable = false; string errorMessage = null; try { new WMIConnectionProvider("cimv2").Connect(targetInfo); targetAvailable = true; } catch (UnauthorizedAccessException) { errorMessage = string.Format( "Unable to connect to host. The target machine ({0}) denied access to the user ({1}).", targetInfo.GetAddress(), targetInfo.credentials.GetFullyQualifiedUsername()); } catch (CannotConnectToHostException ex) { errorMessage = string.Format( "Unable to connect to host. The target machine ({0}) returned the following error: {1}.", targetInfo.GetAddress(), ex.Message); } catch (Exception ex1) { errorMessage = string.Format( "An unknown error occurred while trying to connect to host ({0}): {1}.", targetInfo.GetAddress(), ex1.Message); } return new TargetCheckingResult() { IsTargetAvailable = targetAvailable, ErrorMessage = errorMessage }; }
/// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="regHive"></param> /// <param name="regKey"></param> /// <param name="userSID"></param> /// <returns></returns> public virtual bool IsThereDACLOnRegistryKeyForUser( TargetInfo targetInfo, string registryHive, string registryKey, string userSID) { var queryHash = GetHashCodeForQuery(targetInfo.GetAddress(), registryHive, registryKey, userSID); if (this.TargetRegistryKeyUsers.ContainsKey(queryHash)) { return(this.TargetRegistryKeyUsers[queryHash]); } IntPtr token = LogOn(targetInfo); var person = WindowsIdentity.Impersonate(token); this.TargetRegistryKeyUsers.Add(queryHash, true); try { GetUserDaclForRegistryKeyOnTarget(targetInfo, registryHive, registryKey, userSID); return(true); } catch (UserDACLNotFoundOnRegistryException) { this.TargetRegistryKeyUsers[queryHash] = false; return(false); } finally { person.Undo(); } }
private string GetAuditPol(TargetInfo targetInfo) { string output = string.Empty; string error = string.Empty; var psi = new ProcessStartInfo("paexec.exe", @"\\" + targetInfo.GetAddress() + " auditpol.exe /get /r /category:*"); psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = false; var reg = Process.Start(psi); using (StreamReader myOutput = reg.StandardOutput) { output = myOutput.ReadToEnd(); } using (StreamReader myError = reg.StandardError) { error = myError.ReadToEnd(); } if (reg.ExitCode != 0) { throw new Exception(error); } return(output); }
private uint GetUserDaclForRegistryKeyOnTarget(TargetInfo address, string regHive, string regKey, string userSID) { RegistryKey remoteKey = this.TryToOpenRemoteKey(address, regHive, regKey); AuthorizationRuleCollection DACLs = null; try { DACLs = remoteKey.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); } catch (ArgumentException) { //throw new Exception(string.Format("An error occurred while trying to get effective rights on target '{0}':\r\n'{1}'", address, ex.Message)); throw new Exception(string.Format("User \"{0}\" do not have access to the registry key permissions", address.credentials.GetFullyQualifiedUsername())); } catch (Exception ex) { throw new Exception(string.Format("An error occurred while trying to get effective rights on target \"{0}\":\r\n'{1}'", address, ex.Message)); } uint userDACL = this.GetUserDACLfromAllRegistryKeyDACLs(DACLs, userSID); if (userDACL == 0) { this.RaiseDACLNotFoundException(address.GetAddress(), userSID, regHive.ToString(), regKey); } return(userDACL); }
public TargetCheckingResult Check(TargetInfo targetInfo) { string errorMessage = null; var targetAvailable = false; var sshConnectionProvider = new SSHConnectionProvider(); try { sshConnectionProvider.Connect(targetInfo); targetAvailable = true; } catch (SshConnectingException sshException) { errorMessage = sshException.Message; } catch (Exception genericException) { errorMessage = string.Format( "An unknown error occurred while trying to connect to target machine ({0}): {1}.", targetInfo.GetAddress(), genericException.Message); } finally { sshConnectionProvider.Disconnect(); } return(new TargetCheckingResult() { IsTargetAvailable = targetAvailable, ErrorMessage = errorMessage }); }
/// <summary> /// Tries to connect to the specified host trought WMI. /// </summary> /// <param name="target">Host to Connect</param> public void Connect(TargetInfo target) { try { var targetAddress = target.GetAddress(); var credentials = target.IsLocalTarget() ? null : target.credentials; var options = this.GetConnectionOptions(credentials); this.ConnectionScope = this.GetManagementScope(options, targetAddress); } catch (UnauthorizedAccessException unauthorizedAccessException) { var credentials = target.credentials; string errorMessage = string.Format(INVALID_CREDENTIALS_ERROR_MESSAGE, target.GetAddress(), credentials.GetDomain(), credentials.GetUserName() + " FullyQualified: '" + credentials.GetFullyQualifiedUsername()); throw new InvalidCredentialsException(target.credentials, errorMessage, unauthorizedAccessException); } catch (COMException comException) { string errorMessage = string.Format(PROVIDER_CONNECTING_ERROR_MESSAGE, target.GetAddress(), comException.Message); throw new CannotConnectToHostException(target, errorMessage, comException); } catch (Exception ex) { string errorMessage = string.Format(PROVIDER_CONNECTING_ERROR_MESSAGE, target.GetAddress(), ex.Message); throw new ProbeException(errorMessage, ex); } }
public TargetCheckingResult Check(TargetInfo targetInfo) { string errorMessage = null; var targetAvailable = false; var sshConnectionProvider = new SSHConnectionProvider(); try { sshConnectionProvider.Connect(targetInfo); targetAvailable = true; } catch (SshConnectingException sshException) { errorMessage = sshException.Message; } catch (Exception genericException) { errorMessage = string.Format( "An unknown error occurred while trying to connect to target machine ({0}): {1}.", targetInfo.GetAddress(), genericException.Message); } finally { sshConnectionProvider.Disconnect(); } return new TargetCheckingResult() { IsTargetAvailable = targetAvailable, ErrorMessage = errorMessage }; }
private SshCommandLineRunner CreateSshCommandLineRunner(TargetInfo target) { var hostAddress = target.GetAddress(); var sshPort = target.GetPort(); var username = target.credentials.GetUserName(); var password = target.credentials.GetPassword(); return(new SshCommandLineRunner(hostAddress, username, password, sshPort)); }
public SystemInformation GetSystemInformationFrom(TargetInfo target) { var sshExec = new SshExec(target.GetAddress(), target.credentials.GetUserName(), target.credentials.GetPassword()); sshExec.Connect(target.GetPort()); var collectedUnixSystemInformation = SystemInformationCollector.getSysInfo(sshExec); return this.CreateSystemInformationInstance(collectedUnixSystemInformation); }
public void Should_be_possible_to_get_files_from_given_directory_path_using_FileContentSystemDataSource() { FakeTarget = ProbeHelper.CreateFakeTarget(); var fileContentSystemDataSource = new FileContentSystemDataSource(FakeTarget.GetAddress()); /*IList<string> returnedFiles = fileContentSystemDataSource.GetValues(GetFakeWmiParameters()); Assert.AreEqual(2, returnedFiles.Count, "The returned file count is unexpected."); Assert.AreEqual(FAKE_DIR_PATH, returnedFiles[0], "The fake directory was unexpected."); Assert.AreEqual(FAKE_FILE_PATH, returnedFiles[1], "The fake file path was unexpected."); */ }
public SystemInformation GetSystemInformationFrom(TargetInfo target) { var hostAddress = target.GetAddress(); var username = target.credentials.GetUserName(); var password = target.credentials.GetPassword(); var commandRunner = new SshCommandLineRunner(hostAddress, username, password, target.GetPort()); var collectedUnixSystemInformation = SystemInformationCollector.getSysInfo(commandRunner); return CreateSystemInformationInstance(collectedUnixSystemInformation); }
public void Should_be_possible_to_get_files_from_given_directory_path_using_FileContentSystemDataSource() { FakeTarget = ProbeHelper.CreateFakeTarget(); var fileContentSystemDataSource = new FileContentSystemDataSource(FakeTarget.GetAddress()); /*IList<string> returnedFiles = fileContentSystemDataSource.GetValues(GetFakeWmiParameters()); * * Assert.AreEqual(2, returnedFiles.Count, "The returned file count is unexpected."); * Assert.AreEqual(FAKE_DIR_PATH, returnedFiles[0], "The fake directory was unexpected."); * Assert.AreEqual(FAKE_FILE_PATH, returnedFiles[1], "The fake file path was unexpected."); */ }
public SystemInformation GetSystemInformationFrom(TargetInfo target) { var hostAddress = target.GetAddress(); var username = target.credentials.GetUserName(); var password = target.credentials.GetPassword(); var commandRunner = new SshCommandLineRunner(hostAddress, username, password, target.GetPort()); var collectedUnixSystemInformation = SystemInformationCollector.getSysInfo(commandRunner); return(CreateSystemInformationInstance(collectedUnixSystemInformation)); }
public virtual void Connect(TargetInfo target) { var connectionPort = target.GetPort(ConnectionType.Telnet); this.TelnetConnection = new TelnetConnection(target.GetAddress(), connectionPort); this.TelnetConnection.TimeOutLoginMs = 1000; this.TelnetConnection.TimeOutReadMs = 30000; this.TelnetConnection.CiscoLogin(target.credentials.GetUserName(), target.credentials.GetPassword()); string adminPass = target.credentials.GetAdminPassword(); if (!String.IsNullOrEmpty(adminPass)) this.TelnetConnection.CiscoEnable(adminPass); }
private void CreateObjectCollector() { if (base.ObjectCollector == null) { base.ObjectCollector = new FileContentSystemDataSource(TargetInfo.GetAddress()); var wmiConnectionScope = this.FileDataSource = new FileObjectCollector() { WmiDataProvider = CreateWmiDataProvider() }; } }
private IntPtr LogOn(TargetInfo targetInfo) { IntPtr token = IntPtr.Zero; var logonMode = LOGON32_LOGON_NEW_CREDENTIALS; // LOGON32_LOGON_INTERACTIVE // Getting Credentials... var username = targetInfo.credentials.GetUserName(); var password = targetInfo.credentials.GetPassword(); var domain = targetInfo.credentials.GetDomain(); if (string.IsNullOrWhiteSpace(domain)) { domain = targetInfo.GetAddress(); } bool isSuccess = LogonUser(username, domain, password, logonMode, LOGON32_PROVIDER_DEFAULT, ref token); if (!isSuccess) { throw new WinLogonAccessDenied(targetInfo.GetAddress()); } return(token); }
public TargetCheckingResult Check(TargetInfo targetInfo) { var targetAvailable = false; string errorMessage = null; try { new WMIConnectionProvider("cimv2").Connect(targetInfo); targetAvailable = true; } catch (UnauthorizedAccessException) { errorMessage = string.Format( "Unable to connect to host. The target machine ({0}) denied access to the user ({1}).", targetInfo.GetAddress(), targetInfo.credentials.GetFullyQualifiedUsername()); } catch (CannotConnectToHostException ex) { errorMessage = string.Format( "Unable to connect to host. The target machine ({0}) returned the following error: {1}.", targetInfo.GetAddress(), ex.Message); } catch (Exception ex1) { errorMessage = string.Format( "An unknown error occurred while trying to connect to host ({0}): {1}.", targetInfo.GetAddress(), ex1.Message); } return(new TargetCheckingResult() { IsTargetAvailable = targetAvailable, ErrorMessage = errorMessage }); }
public virtual void Connect(TargetInfo target) { this.CreateSSHExec(target); try { this.SSHExec.Connect(target.GetPort()); } catch (JSchException ex) { throw new SshConnectingException( string.Format( "Unable to connect to target machine {0} through port {1} using the user {2}. Check the target address (or host name), port number and that ssh service is running at target machine.", target.GetAddress(), target.GetPort(), target.credentials.GetFullyQualifiedUsername())); } }
private IConnectionManager GetConnectionMangerWithUnavailableBehavior() { TargetInfo fakeTargetInfo = ProbeHelper.CreateFakeTarget(); IList <IConnectionProvider> fakeContext = ProbeHelper.CreateFakeContext(); string errorMessage = string.Format("Error connecting to {0}", fakeTargetInfo.GetAddress()); MockRepository mock = new MockRepository(); IConnectionManager connectionManagerWithInvalidCredentials = mock.DynamicMock <IConnectionManager>(); Expect.Call(connectionManagerWithInvalidCredentials.Connect <RegistryConnectionProvider>(fakeContext, fakeTargetInfo)) .IgnoreArguments().Throw(new CannotConnectToHostException(fakeTargetInfo, errorMessage)); mock.ReplayAll(); return(connectionManagerWithInvalidCredentials); }
public virtual void Connect(TargetInfo target) { this.SshCommandLineRunner = CreateSshCommandLineRunner(target); try { this.SshCommandLineRunner.Connect(); } catch (Exception ex) { throw new SshConnectingException( string.Format( "Unable to connect to target machine {0} through port {1} using the user {2}. Check the target address (or host name), port number and that ssh service is running at target machine. Error Message: '{3}'", target.GetAddress(), target.GetPort(), target.credentials.GetFullyQualifiedUsername(), ex.Message)); } }
protected override void ConfigureObjectCollector() { if (base.ObjectCollector == null) { base.ObjectCollector = new LockoutPolicyObjectCollector() { TargetHostName = TargetInfo.GetAddress() } } ; if (base.ItemTypeGenerator == null) { base.ItemTypeGenerator = new LockoutPolicyItemTypeGenerator(); } }
public virtual void Connect(TargetInfo target) { var connectionPort = target.GetPort(ConnectionType.Telnet); this.TelnetConnection = new TelnetConnection(target.GetAddress(), connectionPort); this.TelnetConnection.TimeOutLoginMs = 1000; this.TelnetConnection.TimeOutReadMs = 30000; this.TelnetConnection.CiscoLogin(target.credentials.GetUserName(), target.credentials.GetPassword()); string adminPass = target.credentials.GetAdminPassword(); if (!String.IsNullOrEmpty(adminPass)) { this.TelnetConnection.CiscoEnable(adminPass); } }
public static WmiDataProvider CreateWmiDataProviderForFileSearching(TargetInfo targetInfo) { var wmiNamespace = getNamespaceForTargetAddress(targetInfo.GetAddress()); var username = string.Empty; var password = string.Empty; if (targetInfo.IsThereCredential()) { username = targetInfo.credentials.GetFullyQualifiedUsername(); password = targetInfo.credentials.GetPassword(); } var connectionOptions = CreateConnectionOptions(username, password); var wmiConnectionScope = new ManagementScope(wmiNamespace, connectionOptions); wmiConnectionScope.Connect(); return new WmiDataProvider(wmiConnectionScope); }
protected override void ConfigureObjectCollector() { if (base.ObjectCollector == null) { base.ObjectCollector = new AccessTokenObjectCollector() { TargetHostName = TargetInfo.GetAddress() } } ; if (this.WMIConnectionProvider == null) { this.WMIConnectionProvider = new WMIConnectionProvider("cimv2"); this.OpenWmiConnection(); } this.CreateItemTypeGeneratorInstance(); }
private void ConnectToTarget(TargetInfo targetInfo) { if (targetInfo.IsLocalTarget()) { return; } try { string remoteUNC = string.Format(@"\\{0}", targetInfo.GetAddress()); string userName = targetInfo.IsThereCredential() ? targetInfo.credentials.GetFullyQualifiedUsername() : string.Empty; string password = string.IsNullOrEmpty(userName) ? string.Empty : targetInfo.credentials.GetPassword(); WinNetUtils.connectToRemote(remoteUNC, userName, password); } catch (Exception ex) { throw ex; } }
public void Connect(TargetInfo target) { var binding = new BasicHttpBinding(); binding.MaxBufferSize = 2147483647; binding.MaxBufferPoolSize = 2147483647; binding.MaxReceivedMessageSize = 2147483647; binding.ReaderQuotas.MaxNameTableCharCount = 2147483647; binding.ReaderQuotas.MaxStringContentLength = 2147483647; binding.ReaderQuotas.MaxArrayLength = 2147483647; //binding.MaxReceivedMessageSize = 1000000; binding.SendTimeout = TimeSpan.FromMinutes(10); this.connectionProvider = new ScanWSClient( binding, new System.ServiceModel.EndpointAddress(target.GetAddress())); connectionProvider.Open(); }
public static WmiDataProvider CreateWmiDataProviderForFileSearching(TargetInfo targetInfo) { var wmiNamespace = getNamespaceForTargetAddress(targetInfo.GetAddress()); var username = string.Empty; var password = string.Empty; if (targetInfo.IsThereCredential()) { username = targetInfo.credentials.GetFullyQualifiedUsername(); password = targetInfo.credentials.GetPassword(); } var connectionOptions = CreateConnectionOptions(username, password); var wmiConnectionScope = new ManagementScope(wmiNamespace, connectionOptions); wmiConnectionScope.Connect(); return(new WmiDataProvider(wmiConnectionScope)); }
private string GetPolAdtEv(TargetInfo targetInfo) { string build = @"QUERY \\" + targetInfo.GetAddress() + @"\HKLM\Security\Policy\PolAdtEv\"; string parms = @build; string output = string.Empty; string error = string.Empty; ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms); psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; psi.UseShellExecute = false; var reg = Process.Start(psi); using (StreamReader myOutput = reg.StandardOutput) { output = myOutput.ReadToEnd(); } using (StreamReader myError = reg.StandardError) { error = myError.ReadToEnd(); } if (error != string.Empty) { throw new GetPolAdtEvException(error); } output = output.Replace(@"HKEY_LOCAL_MACHINE\Security\Policy\PolAdtEv", string.Empty); output = output.Replace("(Default)", string.Empty); output = output.Replace("REG_NONE", string.Empty); output = output.Replace(Environment.NewLine, string.Empty); return(output.Trim()); }
private void ConnectToTarget(TargetInfo targetInfo) { if (targetInfo.IsLocalTarget()) return; try { string remoteUNC = string.Format(@"\\{0}", targetInfo.GetAddress()); string userName = targetInfo.IsThereCredential() ? targetInfo.credentials.GetFullyQualifiedUsername() : string.Empty; string password = string.IsNullOrEmpty(userName) ? string.Empty : targetInfo.credentials.GetPassword(); WinNetUtils.connectToRemote(remoteUNC, userName, password); } catch (Exception ex) { throw ex; } }
private void CreateSSHExec(TargetInfo target) { var credentials = target.credentials; this.SSHExec = new SshExec(target.GetAddress(), credentials.GetUserName(), credentials.GetPassword()); }
public virtual IEnumerable <String> GetFileLinesContentFromHost(string localFilepath) { var adminShareFilePath = this.GetAdministrativeSharePathFromLocalFilepath(TargetInfo.GetAddress(), localFilepath); if (string.IsNullOrWhiteSpace(adminShareFilePath)) { return new string[] { } } ; return(System.IO.File.ReadAllLines(adminShareFilePath)); }
private SshCommandLineRunner CreateSshCommandLineRunner(TargetInfo target) { var hostAddress = target.GetAddress(); var sshPort = target.GetPort(); var username = target.credentials.GetUserName(); var password = target.credentials.GetPassword(); return new SshCommandLineRunner(hostAddress, username, password, sshPort); }
private string GetPolAdtEv(TargetInfo targetInfo) { string build = @"QUERY \\" + targetInfo.GetAddress() + @"\HKLM\Security\Policy\PolAdtEv\"; string parms = @build; string output = string.Empty; string error = string.Empty; ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms); psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; psi.UseShellExecute = false; var reg = Process.Start(psi); using (StreamReader myOutput = reg.StandardOutput) { output = myOutput.ReadToEnd(); } using (StreamReader myError = reg.StandardError) { error = myError.ReadToEnd(); } if (error != string.Empty) throw new Exception(error); output = output.Replace(@"HKEY_LOCAL_MACHINE\Security\Policy\PolAdtEv", string.Empty); output = output.Replace("(Default)", string.Empty); output = output.Replace("REG_NONE", string.Empty); output = output.Replace(Environment.NewLine, string.Empty); return output.Trim(); }
public virtual Dictionary<AuditEventPolicies, AuditEventStatus> GetAuditEventPolicies(TargetInfo targetInfo) { Dictionary<AuditEventPolicies, AuditEventStatus> retList = new Dictionary<AuditEventPolicies, AuditEventStatus>(); LSA_UNICODE_STRING systemName = string2LSAUS(targetInfo.GetAddress()); LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES(); IntPtr policyHandle = IntPtr.Zero; IntPtr pAuditEventsInfo = IntPtr.Zero; IntPtr pAuditCategoryGuid = IntPtr.Zero; IntPtr pAuditSubCategoryGuids = IntPtr.Zero; IntPtr pAuditPolicies = IntPtr.Zero; UInt32 lretVal = LsaOpenPolicy(ref systemName, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out policyHandle); uint retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) { throw new System.ComponentModel.Win32Exception((int)retVal); } try { lretVal = LsaQueryInformationPolicy(policyHandle, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pAuditEventsInfo); retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) { throw new System.ComponentModel.Win32Exception((int)retVal); } // EventAuditingOptions: The index of each array element corresponds to an audit event type value in the POLICY_AUDIT_EVENT_TYPE enumeration type. // Each POLICY_AUDIT_EVENT_OPTIONS variable in the array can specify the following auditing options. // POLICY_AUDIT_EVENT_UNCHANGED, POLICY_AUDIT_EVENT_SUCCESS, POLICY_AUDIT_EVENT_FAILURE, POLICY_AUDIT_EVENT_NONE POLICY_AUDIT_EVENTS_INFO myAuditEventsInfo = new POLICY_AUDIT_EVENTS_INFO(); myAuditEventsInfo = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pAuditEventsInfo, myAuditEventsInfo.GetType()); for (UInt32 policyAuditEventType = 0; policyAuditEventType < myAuditEventsInfo.MaximumAuditEventCount; policyAuditEventType++) { pAuditCategoryGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID))); if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)policyAuditEventType, pAuditCategoryGuid)) { int causingError = GetLastError(); throw new System.ComponentModel.Win32Exception(causingError); } String categoryName = String.Empty; AuditLookupCategoryName(pAuditCategoryGuid, ref categoryName); UInt32 status = 0; IntPtr itemPtr = new IntPtr(myAuditEventsInfo.EventAuditingOptions.ToInt64() + (Int64)policyAuditEventType * (Int64)Marshal.SizeOf(typeof(UInt32))); status = (UInt32)Marshal.PtrToStructure(itemPtr, status.GetType()); retList.Add((AuditEventPolicies)policyAuditEventType, (AuditEventStatus)(status & 0x3)); Marshal.FreeHGlobal(pAuditCategoryGuid); pAuditCategoryGuid = IntPtr.Zero; } } finally { if (pAuditEventsInfo != IntPtr.Zero) { LsaFreeMemory(pAuditEventsInfo); } if (pAuditCategoryGuid != IntPtr.Zero) { Marshal.FreeHGlobal(pAuditCategoryGuid); } LsaClose(policyHandle); } return retList; }
public ProbeResult Execute( IList<IConnectionProvider> connectionContext, TargetInfo target, CollectInfo collectInfo) { this.ExecutionLogBuilder = new ExecutionLogBuilder(); this.ExecutionLogBuilder.TryConnectToHost(target.GetAddress()); this.OpenConnectionProvider(connectionContext, target); ExecuteAfterOpenConnectionProvider(); this.ExecutionLogBuilder.ConnectedToHostWithUserName(target.credentials.GetFullyQualifiedUsername()); this.ConfigureObjectCollector(); ProbeResultBuilder probeResultBuilder = this.CollectInformation(collectInfo); probeResultBuilder.AddExecutionLogs(this.ExecutionLogBuilder.BuildExecutionLogs()); return probeResultBuilder.ProbeResult; }
/// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="regHive"></param> /// <param name="regKey"></param> /// <param name="userSID"></param> /// <returns></returns> public virtual bool IsThereDACLOnRegistryKeyForUser( TargetInfo targetInfo, string registryHive, string registryKey, string userSID) { var queryHash = GetHashCodeForQuery(targetInfo.GetAddress(), registryHive, registryKey, userSID); if (this.TargetRegistryKeyUsers.ContainsKey(queryHash)) return this.TargetRegistryKeyUsers[queryHash]; IntPtr token = LogOn(targetInfo); var person = WindowsIdentity.Impersonate(token); this.TargetRegistryKeyUsers.Add(queryHash, true); try { GetUserDaclForRegistryKeyOnTarget(targetInfo, registryHive, registryKey, userSID); return true; } catch (UserDACLNotFoundOnRegistryException) { this.TargetRegistryKeyUsers[queryHash] = false; return false; } finally { person.Undo(); } }
private IntPtr LogOn(TargetInfo targetInfo) { IntPtr token = IntPtr.Zero; var logonMode = LOGON32_LOGON_NEW_CREDENTIALS; // LOGON32_LOGON_INTERACTIVE // Getting Credentials... var username = targetInfo.credentials.GetUserName(); var password = targetInfo.credentials.GetPassword(); var domain = targetInfo.credentials.GetDomain(); if (string.IsNullOrWhiteSpace(domain)) domain = targetInfo.GetAddress(); bool isSuccess = LogonUser(username, domain, password, logonMode, LOGON32_PROVIDER_DEFAULT, ref token); if (!isSuccess) throw new WinLogonAccessDenied(targetInfo.GetAddress()); return token; }
public virtual Dictionary <AuditEventPolicies, AuditEventStatus> GetAuditEventPolicies(TargetInfo targetInfo) { Dictionary <AuditEventPolicies, AuditEventStatus> retList = new Dictionary <AuditEventPolicies, AuditEventStatus>(); LSA_UNICODE_STRING systemName = string2LSAUS(targetInfo.GetAddress()); LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES(); IntPtr policyHandle = IntPtr.Zero; IntPtr pAuditEventsInfo = IntPtr.Zero; IntPtr pAuditCategoryGuid = IntPtr.Zero; IntPtr pAuditSubCategoryGuids = IntPtr.Zero; IntPtr pAuditPolicies = IntPtr.Zero; UInt32 lretVal = LsaOpenPolicy(ref systemName, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out policyHandle); uint retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) { throw new System.ComponentModel.Win32Exception((int)retVal); } try { lretVal = LsaQueryInformationPolicy(policyHandle, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pAuditEventsInfo); retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) { throw new System.ComponentModel.Win32Exception((int)retVal); } // EventAuditingOptions: The index of each array element corresponds to an audit event type value in the POLICY_AUDIT_EVENT_TYPE enumeration type. // Each POLICY_AUDIT_EVENT_OPTIONS variable in the array can specify the following auditing options. // POLICY_AUDIT_EVENT_UNCHANGED, POLICY_AUDIT_EVENT_SUCCESS, POLICY_AUDIT_EVENT_FAILURE, POLICY_AUDIT_EVENT_NONE POLICY_AUDIT_EVENTS_INFO myAuditEventsInfo = new POLICY_AUDIT_EVENTS_INFO(); myAuditEventsInfo = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pAuditEventsInfo, myAuditEventsInfo.GetType()); for (UInt32 policyAuditEventType = 0; policyAuditEventType < myAuditEventsInfo.MaximumAuditEventCount; policyAuditEventType++) { pAuditCategoryGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID))); if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)policyAuditEventType, pAuditCategoryGuid)) { int causingError = GetLastError(); throw new System.ComponentModel.Win32Exception(causingError); } String categoryName = String.Empty; AuditLookupCategoryName(pAuditCategoryGuid, ref categoryName); UInt32 status = 0; IntPtr itemPtr = new IntPtr(myAuditEventsInfo.EventAuditingOptions.ToInt64() + (Int64)policyAuditEventType * (Int64)Marshal.SizeOf(typeof(UInt32))); status = (UInt32)Marshal.PtrToStructure(itemPtr, status.GetType()); retList.Add((AuditEventPolicies)policyAuditEventType, (AuditEventStatus)(status & 0x3)); Marshal.FreeHGlobal(pAuditCategoryGuid); pAuditCategoryGuid = IntPtr.Zero; } } finally { if (pAuditEventsInfo != IntPtr.Zero) { LsaFreeMemory(pAuditEventsInfo); } if (pAuditCategoryGuid != IntPtr.Zero) { Marshal.FreeHGlobal(pAuditCategoryGuid); } LsaClose(policyHandle); } return(retList); }
public virtual Dictionary<string, uint> GetRegKeyDACLs(TargetInfo targetInfo, string regHive, string regKey) { IntPtr token = LogOn(targetInfo); var person = WindowsIdentity.Impersonate(token); RegistryKey remoteKey = null; try { remoteKey = this.TryToOpenRemoteKey(targetInfo, regHive, regKey); } finally { person.Undo(); } try { var regKeyAccessControl = remoteKey.GetAccessControl(AccessControlSections.Access); var typeOfSID = typeof(System.Security.Principal.SecurityIdentifier); var DACLs = regKeyAccessControl.GetAccessRules(true, true, typeOfSID); var result = new Dictionary<string, uint>(); foreach (RegistryAccessRule dacl in DACLs) { var userDACL = (uint)dacl.RegistryRights; if (userDACL <= Int32.MaxValue) { var userSid = dacl.IdentityReference.Value; if (result.ContainsKey(userSid)) result[userSid] += userDACL; else result.Add(userSid, userDACL); } } return result; } catch (Exception ex) { throw new Exception(string.Format("An error occurred while trying to get effective rights on target '{0}':\r\n'{1}'", targetInfo.GetAddress(), ex.Message)); } //finally //{ // person.Undo(); //} }
private uint GetUserDaclForRegistryKeyOnTarget(TargetInfo address, string regHive, string regKey, string userSID) { RegistryKey remoteKey = this.TryToOpenRemoteKey(address, regHive, regKey); AuthorizationRuleCollection DACLs = null; try { DACLs = remoteKey.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); } catch (ArgumentException) { //throw new Exception(string.Format("An error occurred while trying to get effective rights on target '{0}':\r\n'{1}'", address, ex.Message)); throw new Exception(string.Format("User \"{0}\" do not have access to the registry key permissions", address.credentials.GetFullyQualifiedUsername())); } catch (Exception ex) { throw new Exception(string.Format("An error occurred while trying to get effective rights on target \"{0}\":\r\n'{1}'", address, ex.Message)); } uint userDACL = this.GetUserDACLfromAllRegistryKeyDACLs(DACLs, userSID); if (userDACL == 0) this.RaiseDACLNotFoundException(address.GetAddress(), userSID, regHive.ToString(), regKey); return userDACL; }
public virtual Dictionary <string, uint> GetRegKeyDACLs(TargetInfo targetInfo, string regHive, string regKey) { IntPtr token = LogOn(targetInfo); var person = WindowsIdentity.Impersonate(token); RegistryKey remoteKey = null; try { remoteKey = this.TryToOpenRemoteKey(targetInfo, regHive, regKey); } finally { person.Undo(); } try { var regKeyAccessControl = remoteKey.GetAccessControl(AccessControlSections.Access); var typeOfSID = typeof(System.Security.Principal.SecurityIdentifier); var DACLs = regKeyAccessControl.GetAccessRules(true, true, typeOfSID); var result = new Dictionary <string, uint>(); foreach (RegistryAccessRule dacl in DACLs) { var userDACL = (uint)dacl.RegistryRights; if (userDACL <= Int32.MaxValue) { var userSid = dacl.IdentityReference.Value; if (result.ContainsKey(userSid)) { result[userSid] += userDACL; } else { result.Add(userSid, userDACL); } } } return(result); } catch (Exception ex) { throw new Exception(string.Format("An error occurred while trying to get effective rights on target '{0}':\r\n'{1}'", targetInfo.GetAddress(), ex.Message)); } //finally //{ // person.Undo(); //} }
private RegistryKey TryToOpenRemoteKey(TargetInfo targetInfo, string registryHiveAsString, string registryKey) { var keyPath = this.CombineHiveAndKey(registryHiveAsString, registryKey); RegistryKey registryHive = null; try { var hive = (RegistryHive)Enum.Parse(typeof(RegistryHive), registryHiveAsString); var isLocal = targetInfo.GetAddress().Equals("127.0.0.1") || targetInfo.GetAddress().Trim().ToLower().Equals("localhost"); registryHive = RegistryKey.OpenRemoteBaseKey(hive, isLocal ? string.Empty : targetInfo.GetAddress()); //RegistrySecurity rs = registryHive.GetAccessControl(AccessControlSections.Access); //rs.SetAccessRuleProtection(true, true); //this line you need to set ACL on a remote machines registry key. } catch (UnauthorizedAccessException) { throw new RegistryKeyEffectiveRightsAccessDenied(targetInfo.GetAddress(), keyPath); } var remoteKey = string.IsNullOrEmpty(registryKey) ? registryHive : registryHive.OpenSubKey(registryKey); if (remoteKey == null) throw new RegistryKeyEffectiveRightsNotFoundException(targetInfo.GetAddress(), keyPath); return remoteKey; }
public virtual Dictionary<AuditEventSubcategories, AuditEventStatus> GetAuditEventSubcategoriesPolicy(TargetInfo targetInfo) { Dictionary<AuditEventSubcategories, AuditEventStatus> retList = new Dictionary<AuditEventSubcategories, AuditEventStatus>(); string target = @"\\" + targetInfo.GetAddress(); LSA_UNICODE_STRING systemName = string2LSAUS(target); LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES(); IntPtr policyHandle = IntPtr.Zero; IntPtr pAuditEventsInfo = IntPtr.Zero; IntPtr pAuditCategoryId = IntPtr.Zero; IntPtr pAuditSubCategoryGuids = IntPtr.Zero; IntPtr pAuditPolicies = IntPtr.Zero; UInt32 lretVal = LsaOpenPolicy(ref systemName, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out policyHandle); UInt32 retVal = LsaNtStatusToWinError(lretVal); if (retVal == (UInt32)0) { try { lretVal = LsaQueryInformationPolicy(policyHandle, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pAuditEventsInfo); retVal = LsaNtStatusToWinError(lretVal); if (retVal == 0) { POLICY_AUDIT_EVENTS_INFO myAuditEventsInfo = new POLICY_AUDIT_EVENTS_INFO(); myAuditEventsInfo = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pAuditEventsInfo, myAuditEventsInfo.GetType()); for (var policyAuditEventType = 0; policyAuditEventType < myAuditEventsInfo.MaximumAuditEventCount; policyAuditEventType++) { pAuditCategoryId = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID))); if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)policyAuditEventType, pAuditCategoryId)) { int causingError = GetLastError(); throw new System.ComponentModel.Win32Exception(causingError); } UInt32 nSubCats = 0; pAuditSubCategoryGuids = IntPtr.Zero; if (!AuditEnumerateSubCategories(pAuditCategoryId, false, ref pAuditSubCategoryGuids, out nSubCats)) { int causingError = GetLastError(); throw new System.ComponentModel.Win32Exception(causingError); } Marshal.FreeHGlobal(pAuditCategoryId); pAuditCategoryId = IntPtr.Zero; pAuditPolicies = IntPtr.Zero; if (nSubCats > 0) { if (!AuditQuerySystemPolicy(pAuditSubCategoryGuids, nSubCats, out pAuditPolicies)) { int causingError = GetLastError(); throw new System.ComponentModel.Win32Exception(causingError); } for (var subcategoryIndex = 0; subcategoryIndex < nSubCats; subcategoryIndex++) { AUDIT_POLICY_INFORMATION currentPolicy = new AUDIT_POLICY_INFORMATION(); IntPtr itemPtr = new IntPtr(pAuditPolicies.ToInt64() + (Int64)subcategoryIndex * (Int64)Marshal.SizeOf(currentPolicy)); currentPolicy = (AUDIT_POLICY_INFORMATION)Marshal.PtrToStructure(itemPtr, currentPolicy.GetType()); String subCategoryName = String.Empty; Marshal.StructureToPtr(currentPolicy, itemPtr, true); AuditLookupSubCategoryName(itemPtr, ref subCategoryName); AuditEventSubcategories value; if (subcategoriesDictionary.TryGetValue(subCategoryName, out value)) { retList.Add(value, (AuditEventStatus)(currentPolicy.AuditingInformation & 0x3)); } } if (pAuditPolicies != IntPtr.Zero) { AuditFree(pAuditPolicies); pAuditPolicies = IntPtr.Zero; } } if (pAuditSubCategoryGuids != IntPtr.Zero) { AuditFree(pAuditSubCategoryGuids); pAuditSubCategoryGuids = IntPtr.Zero; } nSubCats = 0; } } else { throw new System.ComponentModel.Win32Exception((int)retVal); } } finally { if (pAuditPolicies != IntPtr.Zero) { AuditFree(pAuditPolicies); pAuditPolicies = IntPtr.Zero; } if (pAuditSubCategoryGuids != IntPtr.Zero) { AuditFree(pAuditSubCategoryGuids); pAuditSubCategoryGuids = IntPtr.Zero; } if (pAuditEventsInfo != IntPtr.Zero) { LsaFreeMemory(pAuditEventsInfo); } if (pAuditCategoryId != IntPtr.Zero) { Marshal.FreeHGlobal(pAuditCategoryId); } LsaClose(policyHandle); } } else { throw new System.ComponentModel.Win32Exception((int)retVal); } return retList; }