public Domain Read(Domain domain) { Forest currentForest = Forest.GetCurrentForest(); GlobalCatalog gc = currentForest.FindGlobalCatalog(); DirectorySearcher userSearcher = gc.GetDirectorySearcher(); userSearcher.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + domain.Name + "))"; SearchResult result = userSearcher.FindOne(); return(null); }
private DirectorySearcher CreateDirectorySearcher() { if (!string.IsNullOrEmpty(this.activeDirectorySettings.LdapConnectionString)) { return(new DirectorySearcher(new DirectoryEntry(this.activeDirectorySettings.LdapConnectionString))); } else { Forest currentForest = Forest.GetCurrentForest(); GlobalCatalog globalCatalog = currentForest.FindGlobalCatalog(); return(globalCatalog.GetDirectorySearcher()); } }
private void SearchForComputerName(int startingNumber, bool clearList = true) { buttonSearch.Enabled = false; GlobalCatalog globalCatalog = Forest.GetCurrentForest().FindGlobalCatalog(); DirectorySearcher directorySearcher = globalCatalog.GetDirectorySearcher(); if (clearList) { listBoxAvailableNames.Items.Clear(); } while (true) { string number = startingNumber.ToString(); while (number.Length < numericUpDownNumberLength.Value) { number = $"0{number}"; } directorySearcher.Filter = $"(&(ObjectCategory=computer)(name={textBoxComputerName.Text}{number}))"; SearchResultCollection searchResultCollection = directorySearcher.FindAll(); if (searchResultCollection.Count == 0) { listBoxAvailableNames.Items.Add($"{textBoxComputerName.Text}{number}"); Update(); if (listBoxAvailableNames.Items.Count == 10) { _lastSearchedNumber = startingNumber; break; } } startingNumber++; } buttonSearch.Enabled = true; }
//make this searching the GC public static bool LookUpAcctSid(string contextSystem, byte[] abSID, StringBuilder sbDomain) { SecurityIdentifier sid = new SecurityIdentifier(abSID, 0); string[] splits = contextSystem.Split('.'); string sDCs = ""; foreach (string split in splits) { sDCs = string.Concat(sDCs, "DC=", split, ","); } sDCs = sDCs.Substring(0, sDCs.Length - 1); //some hack to obtain the creds to establish a GC dirContext [Wei] string username = string.Empty; string password = string.Empty; DirectoryEntry.ObtainCreds(out username, out password, contextSystem.ToLower()); GlobalCatalog gc = GlobalCatalog.GetGlobalCatalog( new System.DirectoryServices.ActiveDirectory.DirectoryContext(DirectoryContextType.Domain, contextSystem.ToLower(), username, password)); if (gc == null) //cannot talk to GC { string contextldapPath = string.Concat("LDAP://", contextSystem.ToLower(), "/", sDCs); DirectoryEntry context = new DirectoryEntry(contextldapPath); string filter = string.Concat("(objectSid=", sid.ToString(), ")"); DirectorySearcher ds = new DirectorySearcher(context, filter); ds.SearchScope = SearchScope.Subtree; SearchResult de = ds.FindOne(); if (de == null) { //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!)"); return(false); } else { //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!)"); sbDomain.Append(contextSystem); return(true); } } else //search in GC { DirectorySearcher ds = gc.GetDirectorySearcher(); ds.Filter = string.Concat("(objectSid=", sid.ToString(), ")"); ds.SearchScope = SearchScope.Subtree; SearchResult sr = ds.FindOne(); if (sr == null) { //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!) (in GC)"); return(false); } else { //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!) (in GC)"); sbDomain.Append(contextSystem); return(true); } } }
public static List <string> SearchLDAP(Utilities.Options.Arguments arguments) { try { bool searchGlobalCatalog = true; List <string> ComputerNames = new List <string>(); string description = null; string filter = null; //https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx //https://ldapwiki.com/wiki/Active%20Directory%20Computer%20Related%20LDAP%20Query switch (arguments.ldap) { case "all": description = "all enabled computers with \"primary\" group \"Domain Computers\""; filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"); break; case "dc": description = "all enabled Domain Controllers (not read-only DCs)"; filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(userAccountControl:1.2.840.113556.1.4.803:=8192))"); break; case "exclude-dc": description = "all enabled computers that are not Domain Controllers or read-only DCs"; filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(userAccountControl:1.2.840.113556.1.4.803:=8192))(!(userAccountControl:1.2.840.113556.1.4.803:=67100867)))"); break; case "servers": searchGlobalCatalog = false; //operatingSystem attribute is not replicated in Global Catalog description = "all enabled servers"; filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(operatingSystem=*server*))"); break; case "servers-exclude-dc": searchGlobalCatalog = false; //operatingSystem attribute is not replicated in Global Catalog description = "all enabled servers excluding Domain Controllers or read-only DCs"; filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(operatingSystem=*server*)(!(userAccountControl:1.2.840.113556.1.4.803:=8192))(!(userAccountControl:1.2.840.113556.1.4.803:=67100867)))"); break; default: Console.WriteLine("[!] Invalid LDAP filter: {0}", filter); Utilities.Options.Usage(); //Environment.Exit(0); return(null); } if (searchGlobalCatalog) { try { DirectoryEntry entry = null; DirectorySearcher globalCatalogSearcher = null; if (!String.IsNullOrEmpty(arguments.dc) && !String.IsNullOrEmpty(arguments.domain)) { try { string directoryEntry = $"GC://{arguments.dc}/DC={arguments.domain.Replace(".", ",DC=")}"; Console.WriteLine($"[+] Attempting to connect to Global Catalog: {directoryEntry}"); entry = new DirectoryEntry(directoryEntry); globalCatalogSearcher = new DirectorySearcher(entry); } catch (Exception ex) { Console.WriteLine($"[!] LDAP Error connecting to Global Catalog: {ex.Message.Trim()}"); string directoryEntry = $"LDAP://{arguments.dc}/DC={arguments.domain.Replace(".", ",DC=")}"; Console.WriteLine($"[+] Querying DC without Global Catalog: {directoryEntry}"); entry = new DirectoryEntry(directoryEntry); globalCatalogSearcher = new DirectorySearcher(entry); } } else { Forest currentForest = Forest.GetCurrentForest(); GlobalCatalog globalCatalog = currentForest.FindGlobalCatalog(); globalCatalogSearcher = globalCatalog.GetDirectorySearcher(); } globalCatalogSearcher.PropertiesToLoad.Add("dnshostname"); globalCatalogSearcher.Filter = filter; globalCatalogSearcher.SizeLimit = int.MaxValue; globalCatalogSearcher.PageSize = int.MaxValue; Console.WriteLine("[+] Performing LDAP query against Global Catalog for {0}...", description); Console.WriteLine("[+] This may take some time depending on the size of the environment"); foreach (SearchResult resEnt in globalCatalogSearcher.FindAll()) { //sometimes objects with empty attributes throw errors try { string ComputerName = resEnt.Properties["dnshostname"][0].ToString().ToUpper(); ComputerNames.Add(ComputerName); } catch { /*nothing*/ } } globalCatalogSearcher.Dispose(); } catch (Exception ex) { if (arguments.verbose) { Console.WriteLine("[!] LDAP Error searching Global Catalog: {0}", ex.Message); } } } else { try { DirectoryEntry entry = null; DirectorySearcher mySearcher = null; if (!String.IsNullOrEmpty(arguments.dc) && !String.IsNullOrEmpty(arguments.domain)) { string directoryEntry = $"LDAP://{arguments.dc}/DC={arguments.domain.Replace(".", ",DC=")}"; Console.WriteLine($"[+] Performing LDAP query against {directoryEntry} for {description}..."); Console.WriteLine("[+] This may take some time depending on the size of the environment"); entry = new DirectoryEntry(directoryEntry); mySearcher = new DirectorySearcher(entry); } else { entry = new DirectoryEntry(); mySearcher = new DirectorySearcher(entry); } mySearcher.PropertiesToLoad.Add("dnshostname"); mySearcher.Filter = filter; mySearcher.SizeLimit = int.MaxValue; mySearcher.PageSize = int.MaxValue; Console.WriteLine("[+] Performing LDAP query against the current domain for {0}...", description); Console.WriteLine("[+] This may take some time depending on the size of the environment"); foreach (SearchResult resEnt in mySearcher.FindAll()) { //sometimes objects with empty attributes throw errors try { string ComputerName = resEnt.Properties["dnshostname"][0].ToString().ToUpper(); ComputerNames.Add(ComputerName); } catch { /*nothing*/ } } mySearcher.Dispose(); } catch (Exception ex) { if (arguments.verbose) { Console.WriteLine("[!] LDAP Error: {0}", ex.Message); } } } //localhost returns false positives ComputerNames.RemoveAll(u => u.Contains(System.Environment.MachineName.ToUpper())); Console.WriteLine("[+] LDAP Search Results: {0}", ComputerNames.Count.ToString()); return(ComputerNames); } catch (Exception ex) { if (arguments.verbose) { Console.WriteLine("[!] LDAP Error: {0}", ex.Message); } return(null); } }
private static void SearchForComputerTest(DirectoryEntry de, string prevPrefix = "", int prevCnt = 0, int prevLength = 0) { Console.Write($"Search for computer{(prevPrefix != "" ? $" [{prevPrefix}]" : "")}: "); string prefix = Console.ReadLine(); if (string.IsNullOrEmpty(prefix)) { prefix = prevPrefix; } Console.Write($"Starting number{(prevCnt != 0 ? $"[{prevCnt}]" : "")}: "); int cnt = GetIntFromConsoleRead(); if (cnt == 0) { if (prevCnt == 0) { Console.WriteLine("Defaulting to 1"); cnt = 1; } else { cnt = prevCnt; } } Console.Write($"Number length{(prevLength != 0 ? $"[{prevLength}]" : "")}: "); int length = GetIntFromConsoleRead(); GlobalCatalog gc = Forest.GetCurrentForest().FindGlobalCatalog(); DirectorySearcher ds = gc.GetDirectorySearcher(); List <string> openNamesList = new List <string>(); int startingCnt = cnt; while (true) { string scnt = cnt.ToString(); while (scnt.Length < length) { scnt = $"0{scnt}"; } ds.Filter = $"(&(ObjectCategory=computer)(name={prefix}{scnt}))"; //DirectorySearcher ds = new DirectorySearcher(de,$"(&(ObjectCategory=computer)(name={Console.ReadLine()}))"); SearchResultCollection resultCollection = ds.FindAll(); if (resultCollection.Count == 0) { openNamesList.Add($"{prefix}{scnt}"); if (openNamesList.Count == 10) { break; } } cnt++; } Console.WriteLine($"Search finished in {ds.SearchRoot.Path}"); Console.WriteLine("Available names:"); foreach (string s in openNamesList) { Console.WriteLine($" {s}"); } Console.WriteLine($"\nSearch again?"); ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); if (consoleKeyInfo.Key == ConsoleKey.Y) { Console.WriteLine(); SearchForComputerTest(de, prefix, startingCnt, length); } }
public static List <string> SearchLDAP(string filter, bool verbose) { try { List <string> ComputerNames = new List <string>(); string description = ""; Forest currentForest = Forest.GetCurrentForest(); GlobalCatalog globalCatalog = currentForest.FindGlobalCatalog(); DirectorySearcher globalCatalogSearcher = globalCatalog.GetDirectorySearcher(); //DirectoryEntry entry = new DirectoryEntry(); //DirectorySearcher mySearcher = new DirectorySearcher(entry); globalCatalogSearcher.PropertiesToLoad.Add("dnshostname"); //https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx //https://ldapwiki.com/wiki/Active%20Directory%20Computer%20Related%20LDAP%20Query switch (filter) { case "all": description = "all enabled computers with \"primary\" group \"Domain Computers\""; globalCatalogSearcher.Filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"); break; case "dc": description = "all enabled Domain Controllers (not read-only DCs)"; globalCatalogSearcher.Filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(userAccountControl:1.2.840.113556.1.4.803:=8192))"); break; case "exclude-dc": description = "all enabled computers that are not Domain Controllers or read-only DCs"; globalCatalogSearcher.Filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(userAccountControl:1.2.840.113556.1.4.803:=8192))(!(userAccountControl:1.2.840.113556.1.4.803:=67100867)))"); break; case "servers": description = "all enabled servers"; globalCatalogSearcher.Filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(operatingSystem=*server*))"); break; case "servers-exclude-dc": description = "all enabled servers excluding Domain Controllers or read-only DCs"; globalCatalogSearcher.Filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(operatingSystem=*server*)(!(userAccountControl:1.2.840.113556.1.4.803:=8192))(!(userAccountControl:1.2.840.113556.1.4.803:=67100867)))"); break; default: Console.WriteLine("[!] Invalid LDAP filter: {0}", filter); Utilities.Options.Usage(); Environment.Exit(0); break; } globalCatalogSearcher.SizeLimit = int.MaxValue; globalCatalogSearcher.PageSize = int.MaxValue; Console.WriteLine("[+] Performing LDAP query for {0}...", description); Console.WriteLine("[+] This may take some time depending on the size of the environment"); foreach (SearchResult resEnt in globalCatalogSearcher.FindAll()) { string ComputerName = resEnt.Properties["dnshostname"][0].ToString(); ComputerNames.Add(ComputerName); } //localhost returns false positives ComputerNames.RemoveAll(u => u.Contains(System.Environment.MachineName)); Console.WriteLine("[+] LDAP Search Results: {0}", ComputerNames.Count.ToString()); globalCatalogSearcher.Dispose(); return(ComputerNames); } catch (Exception ex) { if (verbose) { Console.WriteLine("[!] LDAP Error: {0}", ex.Message); } return(null); } }