public static IEnumerable <DNSRecord> Get_DomainDNSRecord(Args_Get_DomainDNSRecord args = null) { if (args == null) { args = new Args_Get_DomainDNSRecord(); } var SearcherArguments = new Args_Get_DomainSearcher { LDAPFilter = @"(objectClass=dnsNode)", SearchBasePrefix = $@"DC={args.ZoneName},CN=MicrosoftDNS,DC=DomainDnsZones", Domain = args.Domain, Server = args.Server, Properties = args.Properties, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, Credential = args.Credential }; var DNSSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); SearchResult[] Results = null; List <DNSRecord> Outs = null; if (DNSSearcher != null) { if (args.FindOne) { Results = new SearchResult[] { DNSSearcher.FindOne() }; } else { var items = DNSSearcher.FindAll(); if (items != null) { Results = new SearchResult[items.Count]; items.CopyTo(Results, 0); } } if (Results != null) { foreach (var result in Results) { DNSRecord Out = null; try { var ldapProperty = ConvertLDAPProperty.Convert_LDAPProperty(result.Properties); Out = new DNSRecord { name = ldapProperty.name, distinguishedname = ldapProperty.distinguishedname, dnsrecord = ldapProperty.dnsrecord, whencreated = ldapProperty.whencreated, whenchanged = ldapProperty.whenchanged, ZoneName = args.ZoneName }; // convert the record and extract the properties DNSRecord Record = null; if (Out.dnsrecord is System.DirectoryServices.ResultPropertyValueCollection) { // TODO: handle multiple nested records properly? Record = Convert_DNSRecord((Out.dnsrecord as System.DirectoryServices.ResultPropertyValueCollection)[0] as byte[]); } else { Record = Convert_DNSRecord(Out.dnsrecord as byte[]); } if (Record != null) { if (Record.RecordType != null) { Out.RecordType = Record.RecordType; } else if (Record.UpdatedAtSerial != null) { Out.UpdatedAtSerial = Record.UpdatedAtSerial; } else if (Record.TTL != null) { Out.TTL = Record.TTL; } else if (Record.Age != null) { Out.Age = Record.Age; } else if (Record.TimeStamp != null) { Out.TimeStamp = Record.TimeStamp; } else if (Record.Data.IsNotNullOrEmpty()) { Out.Data = Record.Data; } else if (Record.ZoneName.IsNotNullOrEmpty()) { Out.ZoneName = Record.ZoneName; } else if (Record.name.IsNotNullOrEmpty()) { Out.name = Record.name; } else if (Record.distinguishedname.IsNotNullOrEmpty()) { Out.distinguishedname = Record.distinguishedname; } else if (Record.dnsrecord != null) { Out.dnsrecord = Record.dnsrecord; } else if (Record.whencreated != null) { Out.whencreated = Record.whencreated; } else if (Record.whenchanged != null) { Out.whenchanged = Record.whenchanged; } } } catch (Exception e) { Logger.Write_Warning($@"[Get-DomainDNSRecord] Error: {e}"); } if (Outs == null) { Outs = new List <DNSRecord>(); } Outs.Add(Out); } } DNSSearcher.Dispose(); } return(Outs); }
public static IEnumerable <object> Get_DomainGroup(Args_Get_DomainGroup args = null) { if (args == null) { args = new Args_Get_DomainGroup(); } var SearcherArguments = new Args_Get_DomainSearcher { Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var ObjectArguments = new Args_Get_DomainObject { Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); var Groups = new List <object>(); if (GroupSearcher != null) { if (args.MemberIdentity != null) { string[] OldProperties = null; if (args.Properties != null) { OldProperties = SearcherArguments.Properties; } ObjectArguments.Identity = args.MemberIdentity; ObjectArguments.Raw = true; var Objects = GetDomainObject.Get_DomainObject(ObjectArguments); if (Objects != null) { } foreach (SearchResult obj in Objects) { // convert the user/group to a directory entry var ObjectDirectoryEntry = obj.GetDirectoryEntry(); // cause the cache to calculate the token groups for the user/group ObjectDirectoryEntry.RefreshCache(new string[] { @"tokenGroups" }); foreach (byte[] tokenGroup in ObjectDirectoryEntry.Properties[@"tokenGroups"]) { // convert the token group sid var GroupSid = new System.Security.Principal.SecurityIdentifier(tokenGroup, 0).Value; // ignore the built in groups if (new Regex(@"^S-1-5-32-.*").Match(GroupSid).Success == false) { ObjectArguments.Identity = new string[] { GroupSid }; ObjectArguments.Raw = false; if (OldProperties != null) { ObjectArguments.Properties = OldProperties; } var Group = GetDomainObject.Get_DomainObject(ObjectArguments); if (Group != null) { Groups.AddRange(Group); } } } } } else { var IdentityFilter = ""; var Filter = ""; if (args.Identity != null) { foreach (var samName in args.Identity) { var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29"); if (new Regex(@"^S-1-").Match(IdentityInstance).Success) { IdentityFilter += $@"(objectsid={IdentityInstance})"; } else if (new Regex(@"^CN=").Match(IdentityInstance).Success) { IdentityFilter += $@"(distinguishedname={IdentityInstance})"; if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty()) { // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname // and rebuild the domain searcher var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); Logger.Write_Verbose($@"[Get-DomainGroup] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'"); SearcherArguments.Domain = IdentityDomain; GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (GroupSearcher == null) { Logger.Write_Warning($@"[Get-DomainGroup] Unable to retrieve domain searcher for '{IdentityDomain}'"); } } } else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success) { var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2"))); IdentityFilter += $@"(objectguid={GuidByteString})"; } else if (IdentityInstance.Contains(@"\")) { var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName { OutputType = ADSNameType.Canonical, Identity = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") } }); if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any()) { var GroupDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/')); var GroupName = IdentityInstance.Split(new char[] { '\\' })[1]; IdentityFilter += $@"(samAccountName={GroupName})"; SearcherArguments.Domain = GroupDomain; Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{GroupDomain}' from '{IdentityInstance}'"); GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); } } else { IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance}))"; } } } if (IdentityFilter != null && IdentityFilter.Trim() != "") { Filter += $@"(|{IdentityFilter})"; } if (args.AdminCount) { Logger.Write_Verbose(@"[Get-DomainGroup] Searching for adminCount=1"); Filter += "(admincount=1)"; } if (args.GroupScope != null) { switch (args.GroupScope.Value) { case GroupScope.DomainLocal: Filter = "(groupType:1.2.840.113556.1.4.803:=4)"; break; case GroupScope.NotDomainLocal: Filter = "(!(groupType:1.2.840.113556.1.4.803:=4))"; break; case GroupScope.Global: Filter = "(groupType:1.2.840.113556.1.4.803:=2)"; break; case GroupScope.NotGlobal: Filter = "(!(groupType:1.2.840.113556.1.4.803:=2))"; break; case GroupScope.Universal: Filter = "(groupType:1.2.840.113556.1.4.803:=8)"; break; case GroupScope.NotUniversal: Filter = "(!(groupType:1.2.840.113556.1.4.803:=8))"; break; default: break; } Logger.Write_Verbose($@"[Get-DomainGroup] Searching for group scope '{args.GroupScope.Value.ToString()}'"); } if (args.GroupProperty != null) { switch (args.GroupProperty.Value) { case GroupProperty.Security: Filter = "(groupType:1.2.840.113556.1.4.803:=2147483648)"; break; case GroupProperty.Distribution: Filter = "(!(groupType:1.2.840.113556.1.4.803:=2147483648))"; break; case GroupProperty.CreatedBySystem: Filter = "(groupType:1.2.840.113556.1.4.803:=1)"; break; case GroupProperty.NotCreatedBySystem: Filter = "(!(groupType:1.2.840.113556.1.4.803:=1))"; break; default: break; } Logger.Write_Verbose($@"[Get-DomainGroup] Searching for group property '{args.GroupProperty.Value.ToString()}'"); } if (args.LDAPFilter.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainGroup] Using additional LDAP filter: {args.LDAPFilter}"); Filter += $@"{args.LDAPFilter}"; } GroupSearcher.Filter = $@"(&(objectCategory=group){Filter})"; Logger.Write_Verbose($@"[Get-DomainGroup] filter string: {GroupSearcher.Filter}"); if (args.FindOne) { var result = GroupSearcher.FindOne(); if (args.Raw) { // return raw result objects Groups.Add(result); } else { Groups.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } else { var Results = GroupSearcher.FindAll(); foreach (SearchResult result in Results) { if (args.Raw) { // return raw result objects Groups.Add(result); } else { Groups.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } if (Results != null) { try { Results.Dispose(); } catch (Exception e) { Logger.Write_Verbose($@"[Get-DomainGroup] Error disposing of the Results object: {e}"); } } } GroupSearcher.Dispose(); } } return(Groups); }
public static IEnumerable <object> Get_DomainObject(Args_Get_DomainObject args = null) { if (args == null) { args = new Args_Get_DomainObject(); } var SearcherArguments = new Args_Get_DomainSearcher { Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var ObjectSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); var Objects = new List <object>(); if (ObjectSearcher != null) { var IdentityFilter = ""; var Filter = ""; if (args.Identity != null) { foreach (var samName in args.Identity) { var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29"); if (new Regex(@"^S-1-").Match(IdentityInstance).Success) { IdentityFilter += $@"(objectsid={IdentityInstance})"; } else if (new Regex(@"^(CN|OU|DC)=").Match(IdentityInstance).Success) { IdentityFilter += $@"(distinguishedname={IdentityInstance})"; if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty()) { // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname // and rebuild the domain searcher var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); Logger.Write_Verbose($@"[Get-DomainObject] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'"); SearcherArguments.Domain = IdentityDomain; ObjectSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (ObjectSearcher == null) { Logger.Write_Warning($@"[Get-DomainObject] Unable to retrieve domain searcher for '{IdentityDomain}'"); } } } else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success) { var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2"))); IdentityFilter += $@"(objectguid={GuidByteString})"; } else if (IdentityInstance.Contains(@"\")) { var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName { OutputType = ADSNameType.Canonical, Identity = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") } }); if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any()) { var ObjectDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/')); var ObjectName = IdentityInstance.Split(new char[] { '\\' })[1]; IdentityFilter += $@"(samAccountName={ObjectName})"; SearcherArguments.Domain = ObjectDomain; Logger.Write_Verbose($@"[Get-DomainObject] Extracted domain '{ObjectDomain}' from '{IdentityInstance}'"); ObjectSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); } } else if (IdentityInstance.Contains(@".")) { IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(dnshostname={IdentityInstance}))"; } else { IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(displayname={IdentityInstance}))"; } } } if (IdentityFilter != null && IdentityFilter.Trim() != "") { Filter += $@"(|{IdentityFilter})"; } if (args.LDAPFilter.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainObject] Using additional LDAP filter: {args.LDAPFilter}"); Filter += $@"{args.LDAPFilter}"; } // build the LDAP filter for the dynamic UAC filter value var uacs = args.UACFilter.ExtractValues(); foreach (var uac in uacs) { if (uac.IsNot()) { Filter += $@"(!(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()}))"; } else { Filter += $@"(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()})"; } } if (Filter != null && Filter != "") { ObjectSearcher.Filter = $@"(&{Filter})"; } Logger.Write_Verbose($@"[Get-DomainObject] Get-DomainComputer filter string: {ObjectSearcher.Filter}"); if (args.FindOne) { var result = ObjectSearcher.FindOne(); if (args.Raw) { // return raw result objects Objects.Add(result); } else { Objects.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } else { var Results = ObjectSearcher.FindAll(); foreach (SearchResult result in Results) { if (args.Raw) { // return raw result objects Objects.Add(result); } else { Objects.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } if (Results != null) { try { Results.Dispose(); } catch (Exception e) { Logger.Write_Verbose($@"[Get-DomainObject] Error disposing of the Results object: {e}"); } } } ObjectSearcher.Dispose(); } return(Objects); }
public static IEnumerable <object> Get_DomainGPO(Args_Get_DomainGPO args = null) { if (args == null) { args = new Args_Get_DomainGPO(); } var SearcherArguments = new Args_Get_DomainSearcher { Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var GPOSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); var GPOs = new List <object>(); if (GPOSearcher != null) { if (args.ComputerIdentity != null || args.UserIdentity != null) { var GPOAdsPaths = new List <string>(); string[] OldProperties = null; if (SearcherArguments.Properties != null) { OldProperties = SearcherArguments.Properties; } SearcherArguments.Properties = new[] { @"distinguishedname", @"dnshostname" }; string TargetComputerName = null; string ObjectDN = null; if (args.ComputerIdentity.IsNotNullOrEmpty()) { var Computer = GetDomainComputer.Get_DomainComputer(new Args_Get_DomainComputer(SearcherArguments) { Identity = new[] { args.ComputerIdentity }, FindOne = true }).First() as LDAPProperty; if (Computer == null) { Logger.Write_Verbose($@"[Get-DomainGPO] Computer '{args.ComputerIdentity}' not found!"); } ObjectDN = Computer.distinguishedname; TargetComputerName = Computer.dnshostname; } else { var User = GetDomainUser.Get_DomainUser(new Args_Get_DomainUser(SearcherArguments) { Identity = new[] { args.UserIdentity }, FindOne = true }) as LDAPProperty; if (User == null) { Logger.Write_Verbose($@"[Get-DomainGPO] User '{args.UserIdentity}' not found!"); } ObjectDN = User.distinguishedname; } // extract all OUs the target user/computer is a part of var ObjectOUs = new List <string>(); foreach (var item in ObjectDN.Split(',')) { if (item.StartsWith(@"OU=")) { ObjectOUs.Add(ObjectDN.Substring(ObjectDN.IndexOf($@"{item},"))); } } Logger.Write_Verbose($@"[Get-DomainGPO] object OUs: {ObjectOUs}"); if (ObjectOUs != null) { // find all the GPOs linked to the user/computer's OUs SearcherArguments.Properties = null; var InheritanceDisabled = false; foreach (var ObjectOU in ObjectOUs) { var ous = GetDomainOU.Get_DomainOU(new Args_Get_DomainOU(SearcherArguments) { Identity = new[] { ObjectOU } }); foreach (LDAPProperty ou in ous) { // extract any GPO links for this particular OU the computer is a part of if (ou.gplink.IsNotNullOrEmpty()) { foreach (var item in ou.gplink.Split(new[] { @"][" }, StringSplitOptions.None)) { if (item.StartsWith(@"LDAP")) { var Parts = item.Split(';'); var GpoDN = Parts[0]; var Enforced = Parts[1]; if (InheritanceDisabled) { // if inheritance has already been disabled and this GPO is set as "enforced" // then add it, otherwise ignore it if (Enforced == @"2") { GPOAdsPaths.Add(GpoDN); } } else { // inheritance not marked as disabled yet GPOAdsPaths.Add(GpoDN); } } } } //if this OU has GPO inheritence disabled, break so additional OUs aren't processed if (ou.gpoptions == 1) { InheritanceDisabled = true; } } } } if (TargetComputerName.IsNotNullOrEmpty()) { // find all the GPOs linked to the computer's site var ComputerSite = GetNetComputerSiteName.Get_NetComputerSiteName(new Args_Get_NetComputerSiteName { ComputerName = new[] { TargetComputerName } }).First().SiteName; if (ComputerSite.IsNotNullOrEmpty() && !ComputerSite.IsLikeMatch(@"Error*")) { var sites = GetDomainSite.Get_DomainSite(new Args_Get_DomainSite(SearcherArguments) { Identity = new[] { ComputerSite } }); foreach (LDAPProperty site in sites) { if (site.gplink.IsNotNullOrEmpty()) { // extract any GPO links for this particular site the computer is a part of foreach (var item in site.gplink.Split(new[] { @"][" }, StringSplitOptions.None)) { if (item.StartsWith(@"LDAP")) { GPOAdsPaths.Add(item.Split(';')[0]); } } } } } } // find any GPOs linked to the user/computer's domain var ObjectDomainDN = ObjectDN.Substring(ObjectDN.IndexOf(@"DC=")); SearcherArguments.Properties = null; SearcherArguments.LDAPFilter = $@"(objectclass=domain)(distinguishedname={ObjectDomainDN})"; var objs = GetDomainObject.Get_DomainObject(new Args_Get_DomainObject(SearcherArguments)); foreach (LDAPProperty obj in objs) { if (obj.gplink.IsNotNullOrEmpty()) { // extract any GPO links for this particular domain the computer is a part of foreach (var item in obj.gplink.Split(new[] { @"][" }, StringSplitOptions.None)) { if (item.StartsWith(@"LDAP")) { GPOAdsPaths.Add(item.Split(';')[0]); } } } } Logger.Write_Verbose($@"[Get-DomainGPO] GPOAdsPaths: {GPOAdsPaths}"); // restore the old properites to return, if set if (OldProperties != null) { SearcherArguments.Properties = OldProperties; } else { SearcherArguments.Properties = null; } foreach (var path in GPOAdsPaths.Where(x => x != null && x != "")) { // use the gplink as an ADS path to enumerate all GPOs for the computer SearcherArguments.SearchBase = path; SearcherArguments.LDAPFilter = @"(objectCategory=groupPolicyContainer)"; objs = GetDomainObject.Get_DomainObject(new Args_Get_DomainObject(SearcherArguments)); foreach (LDAPProperty obj in objs) { GPOs.Add(new GPO(obj)); } } } else { var IdentityFilter = @""; var Filter = @""; if (args.Identity != null) { foreach (var item in args.Identity) { var IdentityInstance = item.Replace(@"(", @"\28").Replace(@")", @"\29"); if (IdentityInstance.IsRegexMatch(@"LDAP://|^CN=.*")) { IdentityFilter += $@"(distinguishedname={IdentityInstance})"; if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty()) { // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname // and rebuild the domain searcher var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); Logger.Write_Verbose($@"[Get-DomainGPO] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'"); SearcherArguments.Domain = IdentityDomain; GPOSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (GPOSearcher == null) { Logger.Write_Warning($@"[Get-DomainGPO] Unable to retrieve domain searcher for '{IdentityDomain}'"); } } } else if (IdentityInstance.IsRegexMatch(@"{.*}")) { IdentityFilter += $@"(name={IdentityInstance})"; } else { try { var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2"))); IdentityFilter += $@"(objectguid={GuidByteString})"; } catch { IdentityFilter += $@"(displayname={IdentityInstance})"; } } } } if (IdentityFilter != null && IdentityFilter.Trim() != @"") { Filter += $@"(|{IdentityFilter})"; } if (args.LDAPFilter.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainGPO] Using additional LDAP filter: {args.LDAPFilter}"); Filter += $@"{args.LDAPFilter}"; } GPOSearcher.Filter = $@"(&(objectCategory=groupPolicyContainer){Filter})"; Logger.Write_Verbose($@"[Get-DomainGPO] filter string: {GPOSearcher.Filter}"); SearchResult[] Results = null; if (args.FindOne) { Results = new SearchResult[] { GPOSearcher.FindOne() }; } else { var items = GPOSearcher.FindAll(); if (items != null) { Results = new SearchResult[items.Count]; items.CopyTo(Results, 0); } } if (Results != null) { foreach (var result in Results) { if (args.Raw) { // return raw result objects GPOs.Add(result); } else { GPO GPO; if (args.SearchBase.IsNotNullOrEmpty() && args.SearchBase.IsRegexMatch(@"^GC://")) { GPO = new GPO(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); try { var GPODN = GPO.distinguishedname; var GPODomain = GPODN.Substring(GPODN.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); var gpcfilesyspath = $@"\\{GPODomain}\SysVol\{GPODomain}\Policies\{GPO.cn}"; GPO.gpcfilesyspath = gpcfilesyspath; } catch { Logger.Write_Verbose($@"[Get-DomainGPO] Error calculating gpcfilesyspath for: {GPO.distinguishedname}"); } } else { GPO = new GPO(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } GPOs.Add(GPO); } } } } GPOSearcher.Dispose(); } return(GPOs); }
public static IEnumerable <DNSZone> Get_DomainDNSZone(Args_Get_DomainDNSZone args = null) { if (args == null) { args = new Args_Get_DomainDNSZone(); } var SearcherArguments = new Args_Get_DomainSearcher { LDAPFilter = @"(objectClass=dnsZone)", Domain = args.Domain, Server = args.Server, Properties = args.Properties, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, Credential = args.Credential }; var DNSSearcher1 = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); SearchResult[] Results = null; List <DNSZone> Outs = null; if (DNSSearcher1 != null) { if (args.FindOne) { Results = new SearchResult[] { DNSSearcher1.FindOne() }; } else { var items = DNSSearcher1.FindAll(); if (items != null) { Results = new SearchResult[items.Count]; items.CopyTo(Results, 0); } } if (Results != null) { foreach (var result in Results) { var Out = new DNSZone(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); Outs.Add(Out); } } DNSSearcher1.Dispose(); } SearcherArguments.SearchBasePrefix = @"CN=MicrosoftDNS,DC=DomainDnsZones"; var DNSSearcher2 = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (DNSSearcher2 != null) { try { if (args.FindOne) { Results = new SearchResult[] { DNSSearcher2.FindOne() }; } else { var items = DNSSearcher2.FindAll(); if (items != null) { Results = new SearchResult[items.Count]; items.CopyTo(Results, 0); } } if (Results != null) { foreach (var result in Results) { var Out = new DNSZone(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); Outs.Add(Out); } } } catch { Logger.Write_Verbose(@"[Get-DomainDNSZone] Error accessing 'CN=MicrosoftDNS,DC=DomainDnsZones'"); } DNSSearcher2.Dispose(); } return(Outs); }
public static IEnumerable <object> Get_DomainSite(Args_Get_DomainSite args = null) { if (args == null) { args = new Args_Get_DomainSite(); } var SearcherArguments = new Args_Get_DomainSearcher { SearchBasePrefix = @"CN=Sites,CN=Configuration", Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var SiteSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); var Sites = new List <object>(); if (SiteSearcher != null) { var IdentityFilter = @""; var Filter = @""; if (args.Identity != null) { foreach (var item in args.Identity) { var IdentityInstance = item.Replace(@"(", @"\28").Replace(@")", @"\29"); if (IdentityInstance.IsRegexMatch(@"^CN=.*")) { IdentityFilter += $@"(distinguishedname={IdentityInstance})"; if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty()) { // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname // and rebuild the domain searcher var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); Logger.Write_Verbose($@"[Get-DomainSite] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'"); SearcherArguments.Domain = IdentityDomain; SiteSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (SiteSearcher == null) { Logger.Write_Warning($@"[Get-DomainSite] Unable to retrieve domain searcher for '{IdentityDomain}'"); } } } else { try { var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2"))); IdentityFilter += $@"(objectguid={GuidByteString})"; } catch { IdentityFilter += $@"(name={IdentityInstance})"; } } } } if (IdentityFilter != null && IdentityFilter.Trim() != @"") { Filter += $@"(|{IdentityFilter})"; } if (args.GPLink.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainSite] Searching for sites with {args.GPLink} set in the gpLink property"); Filter += $@"(gplink=*{args.GPLink}*)"; } if (args.LDAPFilter.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainSite] Using additional LDAP filter: {args.LDAPFilter}"); Filter += $@"{args.LDAPFilter}"; } SiteSearcher.Filter = $@"(&(objectCategory=site){Filter})"; Logger.Write_Verbose($@"[Get-DomainSite] Get-DomainSite filter string: {SiteSearcher.Filter}"); SearchResult[] Results = null; if (args.FindOne) { Results = new SearchResult[] { SiteSearcher.FindOne() }; } else { var items = SiteSearcher.FindAll(); if (items != null) { Results = new SearchResult[items.Count]; items.CopyTo(Results, 0); } } if (Results != null) { foreach (var result in Results) { if (args.Raw) { // return raw result objects Sites.Add(result); } else { var Site = ConvertLDAPProperty.Convert_LDAPProperty(result.Properties); Sites.Add(Site); } } } SiteSearcher.Dispose(); } return(Sites); }
public static IEnumerable <object> Get_DomainComputer(Args_Get_DomainComputer args = null) { if (args == null) { args = new Args_Get_DomainComputer(); } var SearcherArguments = new Args_Get_DomainSearcher { Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var CompSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); var Computers = new List <object>(); if (CompSearcher != null) { var IdentityFilter = @""; var Filter = @""; if (args.Identity != null) { foreach (var samName in args.Identity) { var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29"); if (new Regex(@"^S-1-").Match(IdentityInstance).Success) { IdentityFilter += $@"(objectsid={IdentityInstance})"; } else if (new Regex(@"^CN=").Match(IdentityInstance).Success) { IdentityFilter += $@"(distinguishedname={IdentityInstance})"; if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty()) { // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname // and rebuild the domain searcher var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); Logger.Write_Verbose($@"[Get-DomainComputer] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'"); SearcherArguments.Domain = IdentityDomain; CompSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (CompSearcher == null) { Logger.Write_Warning($@"[Get-DomainComputer] Unable to retrieve domain searcher for '{IdentityDomain}'"); } } } else if (IdentityInstance.Contains(@".")) { IdentityFilter += $@"(|(name={IdentityInstance})(dnshostname={IdentityInstance}))"; } else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success) { var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2"))); IdentityFilter += $@"(objectguid={GuidByteString})"; } else { IdentityFilter += $@"(name={IdentityInstance})"; } } } if (IdentityFilter != null && IdentityFilter.Trim() != "") { Filter += $@"(|{IdentityFilter})"; } if (args.Unconstrained) { Logger.Write_Verbose(@"[Get-DomainComputer] Searching for computers with for unconstrained delegation"); Filter += @"(userAccountControl:1.2.840.113556.1.4.803:=524288)"; } if (args.TrustedToAuth) { Logger.Write_Verbose(@"[Get-DomainComputer] Searching for computers that are trusted to authenticate for other principals"); Filter += @"(msds-allowedtodelegateto=*)"; } if (args.Printers) { Logger.Write_Verbose("[Get-DomainComputer] Searching for printers"); Filter += @"(objectCategory=printQueue)"; } if (args.SPN.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainComputer] Searching for computers with SPN: {args.SPN}"); Filter += $@"(servicePrincipalName={args.SPN})"; } if (args.OperatingSystem.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainComputer] Searching for computers with operating system: {args.OperatingSystem}"); Filter += $@"(operatingsystem={args.OperatingSystem})"; } if (args.ServicePack.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainComputer] Searching for computers with service pack: {args.ServicePack}"); Filter += $@"(operatingsystemservicepack={args.ServicePack})"; } if (args.SiteName.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainComputer] Searching for computers with site name: {args.SiteName}"); Filter += $@"(serverreferencebl={args.SiteName})"; } if (args.LDAPFilter.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainComputer] Using additional LDAP filter: {args.LDAPFilter}"); Filter += $@"{args.LDAPFilter}"; } // build the LDAP filter for the dynamic UAC filter value var uacs = args.UACFilter.ExtractValues(); foreach (var uac in uacs) { if (uac.IsNot()) { Filter += $@"(!(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()}))"; } else { Filter += $@"(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()})"; } } CompSearcher.Filter = $@"(&(samAccountType=805306369){Filter})"; Logger.Write_Verbose($@"[Get-DomainComputer] Get-DomainComputer filter string: {CompSearcher.Filter}"); if (args.FindOne) { var result = CompSearcher.FindOne(); var Up = true; if (args.Ping) { Up = TestConnection.Ping(result.Properties["dnshostname"][0] as string, 1); } if (Up) { if (args.Raw) { // return raw result objects Computers.Add(result); } else { Computers.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } } else { var Results = CompSearcher.FindAll(); foreach (SearchResult result in Results) { var Up = true; if (args.Ping) { Up = TestConnection.Ping(result.Properties["dnshostname"][0] as string, 1); } if (Up) { if (args.Raw) { // return raw result objects Computers.Add(result); } else { Computers.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } } if (Results != null) { try { Results.Dispose(); } catch (Exception e) { Logger.Write_Verbose($@"[Get-DomainComputer] Error disposing of the Results object: {e}"); } } } CompSearcher.Dispose(); } return(Computers); }
public static IEnumerable <object> Get_DomainUser(Args_Get_DomainUser args = null) { if (args == null) { args = new Args_Get_DomainUser(); } var SearcherArguments = new Args_Get_DomainSearcher { Domain = args.Domain, Properties = args.Properties, SearchBase = args.SearchBase, Server = args.Server, SearchScope = args.SearchScope, ResultPageSize = args.ResultPageSize, ServerTimeLimit = args.ServerTimeLimit, SecurityMasks = args.SecurityMasks, Tombstone = args.Tombstone, Credential = args.Credential }; var UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); var Users = new List <object>(); if (UserSearcher != null) { var IdentityFilter = ""; var Filter = ""; if (args.Identity != null) { foreach (var samName in args.Identity) { var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29"); if (new Regex(@"^S-1-").Match(IdentityInstance).Success) { IdentityFilter += $@"(objectsid={IdentityInstance})"; } else if (new Regex(@"^CN=").Match(IdentityInstance).Success) { IdentityFilter += $@"(distinguishedname={IdentityInstance})"; if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty()) { // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname // and rebuild the domain searcher var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @"."); Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'"); SearcherArguments.Domain = IdentityDomain; UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); if (UserSearcher == null) { Logger.Write_Warning($@"[Get-DomainUser] Unable to retrieve domain searcher for '{IdentityDomain}'"); } } } else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success) { var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2"))); IdentityFilter += $@"(objectguid={GuidByteString})"; } else if (IdentityInstance.Contains(@"\")) { var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName { OutputType = ADSNameType.Canonical, Identity = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") } }); if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any()) { var UserDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/')); var UserName = IdentityInstance.Split(new char[] { '\\' })[1]; IdentityFilter += $@"(samAccountName={UserName})"; SearcherArguments.Domain = UserDomain; Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{UserDomain}' from '{IdentityInstance}'"); UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments); } } else { IdentityFilter += $@"(samAccountName={IdentityInstance})"; } } } if (IdentityFilter != null && IdentityFilter.Trim() != "") { Filter += $@"(|{IdentityFilter})"; } if (args.SPN) { Logger.Write_Verbose(@"[Get-DomainUser] Searching for non-null service principal names"); Filter += "(servicePrincipalName=*)"; } if (args.AllowDelegation) { Logger.Write_Verbose(@"[Get-DomainUser] Searching for users who can be delegated"); // negation of "Accounts that are sensitive and not trusted for delegation" Filter += "(!(userAccountControl:1.2.840.113556.1.4.803:=1048574))"; } if (args.DisallowDelegation) { Logger.Write_Verbose(@"[Get-DomainUser] Searching for users who are sensitive and not trusted for delegation"); Filter += "(userAccountControl:1.2.840.113556.1.4.803:=1048574)"; } if (args.AdminCount) { Logger.Write_Verbose(@"[Get-DomainUser] Searching for adminCount=1"); Filter += "(admincount=1)"; } if (args.TrustedToAuth) { Logger.Write_Verbose("[Get-DomainUser] Searching for users that are trusted to authenticate for other principals"); Filter += "(msds-allowedtodelegateto=*)"; } if (args.PreauthNotRequired) { Logger.Write_Verbose("[Get-DomainUser] Searching for user accounts that do not require kerberos preauthenticate"); Filter += "(userAccountControl:1.2.840.113556.1.4.803:=4194304)"; } if (args.LDAPFilter.IsNotNullOrEmpty()) { Logger.Write_Verbose($@"[Get-DomainUser] Using additional LDAP filter: {args.LDAPFilter}"); Filter += $@"{args.LDAPFilter}"; } // build the LDAP filter for the dynamic UAC filter value var uacs = args.UACFilter.ExtractValues(); foreach (var uac in uacs) { if (uac.IsNot()) { Filter += $@"(!(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()}))"; } else { Filter += $@"(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()})"; } } UserSearcher.Filter = $@"(&(samAccountType=805306368){Filter})"; Logger.Write_Verbose($@"[Get-DomainUser] filter string: {UserSearcher.Filter}"); if (args.FindOne) { var result = UserSearcher.FindOne(); if (args.Raw) { // return raw result objects Users.Add(result); } else { Users.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } else { var Results = UserSearcher.FindAll(); foreach (SearchResult result in Results) { if (args.Raw) { // return raw result objects Users.Add(result); } else { Users.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties)); } } if (Results != null) { try { Results.Dispose(); } catch (Exception e) { Logger.Write_Verbose($@"[Get-DomainUser] Error disposing of the Results object: {e}"); } } } UserSearcher.Dispose(); } return(Users); }