Beispiel #1
0
        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);
        }
Beispiel #2
0
 /// <summary>
 /// Initialize new instance of this active directory context.
 /// </summary>
 /// <param name="gcHostname">The Global Catelog Hostname a Domain Controller.
 /// If no hostname is provided, the current context is used.
 /// </param>
 public Context(string gcHostname = "")
 {
     if (string.IsNullOrEmpty(gcHostname))
     {
         var context = new DirectoryContext(DirectoryContextType.Forest);
         this.gcHostname = GlobalCatalog.FindOne(context).Name;
     }
     else
     {
         this.gcHostname = gcHostname;
     }
 }
Beispiel #3
0
 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());
     }
 }
Beispiel #4
0
        /// <summary>
        /// Initialize new instance of this active directory context.
        /// </summary>
        /// <param name="gcHostname">The Global Catalog Hostname a Domain Controller.
        /// If no hostname is provided, the current context is used.
        /// <param name="searchType">Whether the searches will be done as GC (default) or LDAP.
        /// Global Catalog will ensure that the results are searched for in the entire catalog (whether in the host
        /// or other domains in the forest)
        /// But, if the host controller happens to contains the search entities, LDAP can be faster.</param>
        /// </param>
        public Context(string gcHostname = "", SearchType searchType = SearchType.GlobalCatalog)
        {
            if (string.IsNullOrEmpty(gcHostname))
            {
                var context = new DirectoryContext(DirectoryContextType.Forest);
                this.gcHostname = GlobalCatalog.FindOne(context).Name;
            }
            else
            {
                this.gcHostname = gcHostname;
            }

            searchProtocol = searchType == SearchType.GlobalCatalog ? "GC" : "LDAP";
        }
Beispiel #5
0
        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;
        }
Beispiel #6
0
        public static void GetGlobalCatalogConfigData()
        {
            Console.WriteLine("<--GLOBAL CATALOG CONFIGURATION DATA-->\n");

            // Get a forest context
            DirectoryContext forestContext = new DirectoryContext(
                DirectoryContextType.Forest);

            GlobalCatalog gc;

            try
            {
                // bind to a global catalog server in the forest
                gc = GlobalCatalog.FindOne(forestContext);
                Console.WriteLine("Finding one global catalog " +
                                  "in the current forest:");
                Console.WriteLine("Name: {0}", gc);
                Console.WriteLine("Site: {0}", gc.SiteName);

                // list roles held by the GC
                Console.WriteLine("\nRoles:");
                foreach (ActiveDirectoryRole role in gc.Roles)
                {
                    Console.WriteLine("\t{0}", role);
                }

                // list partitions hosted by the GC
                Console.WriteLine("\nPartitions hosted by this global catalog:");
                foreach (string partition in gc.Partitions)
                {
                    Console.WriteLine("\t{0}", partition);
                }
            }
            catch (ActiveDirectoryObjectNotFoundException e)
            {
                // gc not found
                Console.WriteLine(e.Message);
            }
        }
Beispiel #7
0
        public static void GCSample()
        {
            Console.WriteLine();
            Console.WriteLine("<---------GLOBAL CATALOG INFO---------->\n");

            // Find one global catalog within the current forest
            GlobalCatalog gc;

            try
            {
                gc = GlobalCatalog.FindOne(forestContext);
                Console.WriteLine("Finding one global catalog " +
                                  "in the current forest:");
                Console.WriteLine("Name: {0}", gc);
                Console.WriteLine("Site: {0}", gc.SiteName);

                // roles held by the GC
                Console.WriteLine();
                Console.WriteLine("Roles:");
                foreach (ActiveDirectoryRole role in gc.Roles)
                {
                    Console.WriteLine(role);
                }

                // partitions hosted by the GC
                Console.WriteLine();
                Console.WriteLine("Partitions hosted by this global catalog:");
                foreach (string partition in gc.Partitions)
                {
                    Console.WriteLine(partition);
                }
            }
            catch (ActiveDirectoryObjectNotFoundException e)
            {
                // gc not found
                Console.WriteLine(e.Message);
            }
            Console.WriteLine();
        }
        public void TestForestGlobalCatalog()
        {
            using (Forest forest = Forest.GetForest(ActiveDirectoryContext))
            {
                int count = 0;
                GlobalCatalogCollection gcCollection = forest.FindAllGlobalCatalogs();
                foreach (GlobalCatalog gc in gcCollection)
                {
                    count++;
                }

                Assert.True(count > 0);
                Assert.True(gcCollection.Contains(gcCollection[0]));
                Assert.Equal(0, gcCollection.IndexOf(gcCollection[0]));

                gcCollection = forest.FindAllGlobalCatalogs(forest.Sites[0].Name);
                count        = 0;
                foreach (GlobalCatalog gc in gcCollection)
                {
                    count++;
                }

                Assert.True(count > 0);
                Assert.True(gcCollection.Contains(gcCollection[0]));
                Assert.Equal(0, gcCollection.IndexOf(gcCollection[0]));

                GlobalCatalog globalCatalog = forest.FindGlobalCatalog(forest.Sites[0].Name);

                DirectoryContext forestContext = new DirectoryContext(
                    DirectoryContextType.Forest,
                    forest.Name,
                    LdapConfiguration.Configuration.UserName,
                    LdapConfiguration.Configuration.Password);

                Assert.Equal(globalCatalog.Name, GlobalCatalog.FindOne(forestContext, forest.Sites[0].Name).Name);
            }
        }
 // Methods
 public bool Contains(GlobalCatalog globalCatalog)
 {
 }
Beispiel #10
0
        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 int IndexOf(GlobalCatalog globalCatalog) {}
	public void CopyTo(GlobalCatalog[] globalCatalogs, int index) {}
	// Methods
	public bool Contains(GlobalCatalog globalCatalog) {}
Beispiel #14
0
        //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 int IndexOf(GlobalCatalog globalCatalog)
 {
 }
Beispiel #16
0
        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);
            }
        }
Beispiel #17
0
        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);
            }
        }