Exemple #1
0
        private void button6_Click(object sender, EventArgs e)
        {
            FwkGlobalCatalog        wFwkGlobalCatalog = new FwkGlobalCatalog();
            List <FwkGlobalCatalog> list        = new List <FwkGlobalCatalog>();
            GlobalCatalogCollection cataloglist = null;

            try
            {
                cataloglist = adADWrapper.GlobalCatalogs(txtDomainC.Text);
            }
            catch (Exception ex)
            {
                lblResult.Text = Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex);
                return;
            }
            foreach (GlobalCatalog gc in cataloglist)
            {
                wFwkGlobalCatalog            = new FwkGlobalCatalog();
                wFwkGlobalCatalog.IPAddress  = gc.IPAddress;
                wFwkGlobalCatalog.Name       = gc.Name;
                wFwkGlobalCatalog.DomainName = gc.Domain.Name;

                list.Add(wFwkGlobalCatalog);
            }

            dataGridView1.DataSource = list;
            dataGridView1.Refresh();
        }
Exemple #2
0
 private void showForestCatalogs(ref GlobalCatalogCollection gcc)
 {
     foreach (GlobalCatalog gc in gcc)
     {
         try
         {
             Console.WriteLine("\t\tGlobalCatalog: {0} {1}, {2}", gc.Name, gc.IPAddress, gc.ToString());
         }
         catch (System.Net.Sockets.SocketException se)
         {
             Console.WriteLine("\t\tERROR: Getting IP: Host not reachable? {0}", se.Message);
         }
     }
 }
Exemple #3
0
        /// <summary>
        /// There are various sources of domains which we need to check
        /// Try to lazy-enumerate this, so that expensive functions aren't called if they're not necessary
        /// </summary>
        /// <param name="username">The full user name (not stripped, should contain domain if available)</param>
        /// <returns>An Enumerable of domains which can be tried</returns>
        private static IEnumerable <Domain> GetAllDomainPossibilities(string username = "")
        {
            //Skip checking username if none is supplied.
            if (!string.IsNullOrEmpty(username))
            {
                // First we try for the domain in the username
                var parsedDomainName   = username.GetDomain();
                var domainFromUsername = GetDomain(parsedDomainName);
                if (domainFromUsername != null)
                {
                    yield return(domainFromUsername);
                }
            }

            // The we try the domain in web.config, if there is one
            string defaultDomainName = ConfigurationManager.AppSettings["ActiveDirectoryDefaultDomain"];

            if (!string.IsNullOrEmpty(defaultDomainName))
            {
                var domainFromConfig = GetDomain(defaultDomainName);
                if (domainFromConfig != null)
                {
                    yield return(domainFromConfig);
                }
            }

            // Finally try the global catalogue
            GlobalCatalogCollection gcc = Forest.GetCurrentForest().FindAllGlobalCatalogs();

            Log.Information("Searching in {count} global catalogs", gcc.Count);

            // Else try all global catalogs in the current forest.
            foreach (GlobalCatalog gc in gcc)
            {
                Log.Information("Trying GlobalCatalogue {globalCatalog} domain {domain}", gc.Name, gc.Domain.Name);
                yield return(gc.Domain);
            }
        }
        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);
            }
        }
Exemple #5
0
        public void DiscoverForest()
        {
            if (forest != null)
            {
                Console.WriteLine("Forest Name: {0}", forest.Name);
                Console.WriteLine("\tForest Mode: {0}", GetForestMode());
                Console.WriteLine("\tForest FSMO Master DC: {0}", GetFSMOMaster());

                if (Utils.Config.Forest.GCs)
                {
                    GlobalCatalogCollection gcc = forest.FindAllDiscoverableGlobalCatalogs();
                    Console.WriteLine("\tForest GCs (Discoverable): ");
                    showForestCatalogs(ref gcc);

                    gcc = forest.FindAllGlobalCatalogs();
                    Console.WriteLine("\tForest GCs (All): ");
                    showForestCatalogs(ref gcc);
                }
                if (Utils.Config.Forest.Sites)
                {
                    Console.WriteLine("\tForest Sites: "); GetForestSites();
                }
                if (Utils.Config.Forest.Trusts)
                {
                    Console.WriteLine("\tForest Trust: "); GetTrustRelationships();
                }
                if (Utils.Config.Forest.Domains)
                {
                    Console.WriteLine("\tForest Root Domain: {0}", GetRootDomain());
                    Console.WriteLine("\tDomains in Forest:"); GetDomainsInForest();
                }
            }
            else
            {
                Console.WriteLine("Forest object not set");
            }
        }
        /// <summary>
        /// There are various sources of domains which we need to check
        /// Try to lazy-enumerate this, so that expensive functions aren't called if they're not necessary
        /// </summary>
        /// <param name="username">The full user name (not stripped, should contain domain if available)</param>
        /// <returns>An Enumerable of domains which can be tried</returns>
        private static IEnumerable <Domain> GetAllDomainPossibilities(string username = "")
        {
            //Skip checking username if none is supplied.
            if (!string.IsNullOrEmpty(username))
            {
                // First we try for the domain in the username
                var parsedDomainName = username.GetDomain();
                if (!string.IsNullOrEmpty(parsedDomainName))
                {
                    var domainFromUsername = GetDomain(parsedDomainName);
                    if (domainFromUsername != null)
                    {
                        yield return(domainFromUsername);
                    }
                }
                else
                {
                    Log.Verbose("AD: Username {UserName} contains no domain part", username);
                }
            }

            // The we try the domain in web.config, if there is one
            string defaultDomainName = ConfigurationManager.AppSettings["ActiveDirectoryDefaultDomain"];

            if (!string.IsNullOrEmpty(defaultDomainName))
            {
                Log.Verbose("AD: Default domain set as {DomainName}", defaultDomainName);

                var domainFromConfig = GetDomain(defaultDomainName);
                if (domainFromConfig != null)
                {
                    yield return(domainFromConfig);

                    yield break;
                }
            }
            else
            {
                Log.Verbose("AD: No default domain setting in web.config");
            }

            // Finally try the global catalogue if haven't found the default domain
            GlobalCatalogCollection gcc = Forest.GetCurrentForest().FindAllGlobalCatalogs();

            Log.Information("Searching in {count} global catalogs", gcc.Count);

            // Else try all global catalogs in the current forest.
            foreach (GlobalCatalog gc in gcc)
            {
                Domain domain = null;
                try
                {
                    Log.Information("Checking GlobalCatalogue {globalCatalog}", gc.Name);
                    domain = gc.Domain;
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to get domain from catalog {globalCatalog}", gc.Name);
                }
                if (domain != null)
                {
                    yield return(domain);
                }
            }
        }
        /// <summary>
        /// function for login single password
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>0= Success, 1=Login Fail, 3=Cannot found user account,4=Found multiple instance of the specified account</returns>
        public int LoginWithActiveDirectory(string username, string password)
        {
            string distinguishedName = string.Empty;
            string userDomainName    = string.Empty;

            IntPtr token = GetLogonToken(ParameterServices.ActiveDirectoryLogin,
                                         ParameterServices.ActiveDirectoryPassword, ParameterServices.ServiceAccountDomainName);

            WindowsImpersonationContext impersonateContext;

            impersonateContext = WindowsIdentity.Impersonate(token);

            if (globalCatalogCache.Count == 0)
            {
                try
                {
                    Forest curentForest = Forest.GetCurrentForest();
                    GlobalCatalogCollection catalogs = curentForest.FindAllGlobalCatalogs();
                    foreach (GlobalCatalog catalog in catalogs)
                    {
                        globalCatalogCache.Enqueue(catalog.Name);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                }

                string[] globalCatalogs = ParameterServices.GlobalCatalogs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string catalog in globalCatalogs)
                {
                    globalCatalogCache.Enqueue(catalog);
                }
            }

            object catalogName;

            while (globalCatalogCache.Count != 0)
            {
                catalogName = globalCatalogCache.Peek();
                logger.Info("Global Catalog: " + catalogName);
                DirectoryEntry entry = new DirectoryEntry();
                try
                {
                    entry.Path = string.Format("GC://{0}", catalogName);

                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.Filter = "(SAMAccountName=" + username + ")";
                    search.PropertiesToLoad.Add("distinguishedName");
                    SearchResultCollection results = search.FindAll();
                    int result = results.Count;

                    if (result == 0)
                    {
                        logger.Error("Username :"******" => Unable to login. The system cannot found account.");
                        return(3);
                    }
                    else if (result > 1)
                    {
                        logger.Error("Username :"******" => Unable to login. The system has found multiple instance of the specified account.");
                        return(4);
                    }
                    else
                    {
                        distinguishedName = results[0].Properties["distinguishedName"][0].ToString();
                        string pattern = "(,dc=([^,]+))+";
                        Match  m       = Regex.Match(distinguishedName, pattern, RegexOptions.IgnoreCase);

                        for (int i = 0; i < m.Groups[2].Captures.Count; i++)
                        {
                            userDomainName += m.Groups[2].Captures[i].Value;
                            if (i != m.Groups[2].Captures.Count - 1)
                            {
                                userDomainName += ".";
                            }
                        }
                        logger.Info("Domain User : "******"Server : " + catalogName + " => " + ex.ToString());
                }
                finally
                {
                    entry.Close();
                }
                break;
            }
            if (globalCatalogCache.Count == 0)
            {
                throw new Exception("No global catalog server functioning.");
            }
            impersonateContext.Undo();
            try
            {
                int    returnedToken;
                IntPtr tokenUser;
                if (LogonUser(username, userDomainName, password, 2, 0, out returnedToken)) //Logon type = Interactive
                {
                    // The attempt was successful. Get the token.
                    tokenUser = new IntPtr(returnedToken);

                    WindowsImpersonationContext userImpersonate;
                    userImpersonate = WindowsIdentity.Impersonate(tokenUser);
                    userImpersonate.Undo();
                    return(0);
                }
                logger.Error("Wrong password => Username : "******", Domain : " + userDomainName);
                logger.Info("Username : "******", Password :"******", Domain : " + userDomainName);
                return(1);
            }
            catch (Exception ex)
            {
                logger.Error("Username : "******", Domain: " + userDomainName + " => " + ex.ToString());
                return(1);
            }
        }