Exemple #1
0
        public static List <LdapEntry> Children(this LdapEntry entry, LdapConnection connection)
        {
            //string filter = "(&(objectclass=user))";
            List <LdapEntry>  entryList = new List <LdapEntry>();
            LdapSearchResults lsc       = connection.Search(entry.DN, LdapConnection.SCOPE_ONE, "objectClass=*", null, false);

            if (lsc == null)
            {
                return(entryList);
            }

            while (lsc.HasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = lsc.Next();

                    if (nextEntry.IsUser() || nextEntry.IsOrganizationalUnit())
                    {
                        entryList.Add(nextEntry);
                    }
                }
                catch (LdapException e)
                {
                    continue;
                }
            }
            return(entryList);
        }
Exemple #2
0
        public List <LdapEntry> ExecuteSearch(string searchBase, string filter = "")
        {
            var results = new List <LdapEntry>();

            var lcm  = LdapConnectionManager.Instance;
            var conn = lcm.GetConnection();
            var sb   = searchBase + config.searchBase;

            LdapControl[] requestControls = new LdapControl[1];

            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn"); //samaccountname
            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;

            cons.SetControls(requestControls);
            conn.Constraints = cons;

            LdapSearchResults resps = (LdapSearchResults)conn.Search(sb, LdapConnection.ScopeSub, filter, null, false, (LdapSearchConstraints)null);

            //var resps = SendSearch(searchBase, type, filter);

            while (resps.HasMore())
            {
                /* Get next returned entry.  Note that we should expect a Ldap-
                 * Exception object as well just in case something goes wrong
                 */
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = resps.Next();
                    results.Add(nextEntry);
                }
                catch (Exception e)
                {
                    if (e is LdapReferralException)
                    {
                        continue;
                    }
                    else
                    {
                        logger.Error("Search stopped with exception " + e.ToString());
                        break;
                    }
                }

                /* Print out the returned Entries distinguished name.  */
                logger.Debug(nextEntry.Dn);
            }

            return(results);
        }
Exemple #3
0
        public LdapAuthenticationResult AuthenticateUser(string userName, string password)
        {
            using (var cn = new LdapConnection())
            {
                cn.Connect(_options.Host, 389);
                try
                {
                    cn.Bind($"{_options.Dn}\\" + userName, password);
                }
                catch
                {
                    return(LdapAuthenticationResult.Fail("USERANDPASSWORDDOESNTMATCH",
                                                         "User and password doesn't match"));
                }

                var searchFilter      = string.Format(_options.SearchFilter, userName);
                LdapSearchResults lsc = cn.Search(_options.Base,
                                                  LdapConnection.SCOPE_SUB,
                                                  searchFilter,
                                                  null,
                                                  false);

                var entry = lsc.Next();
                if (entry == null)
                {
                    return(LdapAuthenticationResult.Fail("ENTRYNOTFOUND", "Entry not found"));
                }
                try
                {
                    var sub = entry.getAttribute(_options.SubjectAttr)?.StringValue;
                    if (string.IsNullOrEmpty(sub))
                    {
                        return(LdapAuthenticationResult.Fail("SUBNOTFOUND", "The user has not a subject"));
                    }
                    else
                    {
                        var claims = new List <Claim>();
                        claims.Add(new Claim(JwtClaimTypes.Subject, sub));
                        claims.Add(new Claim("ldap_accountname", userName));
                        claims.Add(new Claim(ClaimTypes.NameIdentifier, sub));
                        var identity = new ClaimsIdentity(claims, "LDAP");
                        identity.AddClaims(claims);
                        var principal = new ClaimsPrincipal(identity);
                        return(LdapAuthenticationResult.Success(principal));
                    }
                }
                catch
                {
                    return(LdapAuthenticationResult.Fail("ERROR", "En error occured"));
                }
            }
        }
Exemple #4
0
 private static void ProcessResults(LdapSearchResults searchResults, ICollection <LdapEntry> results)
 {
     while (searchResults.HasMore())
     {
         try
         {
             LdapEntry entry = searchResults.Next();
             results.Add(entry);
         }
         catch (LdapException ldapException)
         {
             if (!(ldapException is LdapReferralException))
             {
                 break;
             }
         }
     }
 }
        public User Login(string username, string password)
        {
            //TODO временно
            _connection.UserDefinedServerCertValidationDelegate += new Novell.Directory.Ldap.RemoteCertificateValidationCallback(MySSLHandler);

            _connection.Connect(_config.Url, _config.Port);
            _connection.Bind(_config.BindDn, _config.BindCredentials);

            // string searchFilter = $"(&(objectClass=User)(extensionAttribute1=*)(sAMAccountName={username}))";// string.Format(_config.SearchFilter, username);
            string            searchFilter = string.Format(_config.SearchFilter, $"(sAMAccountName={username})");
            LdapSearchResults result       = _connection.Search(
                _config.SearchBase,
                LdapConnection.SCOPE_SUB,
                searchFilter,
                new[] { MemberOfAttribute, DisplayNameAttribute, SamAccountNameAttribute, "sn", "givenName", "distinguishedName", "cn" },
                false
                );

            if (!result.HasMore())
            {
                return(null);
            }
            LdapEntry user = result.Next();

            if (user != null)
            {
                _connection.Bind(user.DN, password);
                if (_connection.Bound)
                {
                    return(new User
                    {
                        DisplayName = $"{user.getAttribute("sn")?.StringValue ?? "noSN"} {user.getAttribute("givenName")?.StringValue ?? "noGivenName"}",
                        Sam = user.getAttribute(SamAccountNameAttribute)?.StringValue ?? "noSam",
                        IsAdmin = user.getAttribute(MemberOfAttribute)?.StringValueArray.Contains(_config.AdminCn) ?? false,
                        DistinguishedName = user.getAttribute("distinguishedName")?.StringValue ?? "noDn",
                        Subordinates = GetSubordinates(user.getAttribute("distinguishedName")?.StringValue)
                    });
                }
            }
            _connection.Disconnect();
            return(null);
        }
Exemple #6
0
        private static List <Claim> ValidaPermissaoGrupo(Ldap ldap, LoginData loginData, String usuarioDN, List <PermissionGroup> grupos)
        {
            LdapConnection ldapConnection = ldapConnection = new LdapConnection();

            ldapConnection.Connect(ldap.host, ldap.port);
            ldapConnection.Bind(ldap.ldapVersion, ldap.bindLogin, ldap.bindPassword);

            LdapSearchConstraints cons = new LdapSearchConstraints();

            String[] atributos = new String[] { "member" };

            List <Claim> claims = new List <Claim>();

            try
            {
                foreach (PermissionGroup grupo in grupos)
                {
                    String            groupDN       = GetDNGrupo(ldapConnection, ldap, grupo.Name);
                    LdapSearchResults searchResults = ldapConnection.Search(groupDN, LdapConnection.SCOPE_BASE, null, atributos, false, cons);

                    var nextEntry = searchResults.Next();
                    nextEntry.getAttributeSet();

                    try
                    {
                        if (nextEntry.getAttribute("member").StringValueArray.Where(x => x == usuarioDN).Count() > 0)
                        {
                            claims.AddRange(GetClaimType(grupo.AccessType));
                        }
                    }
                    catch { }
                }
            }
            catch (Exception erro) {
                GALibrary.GALogs.SaveLog("AD", "Erro ao validar permissao do usuario: " + erro.ToString(), 1, GALibrary.Models.DB.Context.Parameter.FirstOrDefault());
            }

            ldapConnection.Disconnect();
            return(claims);
        }
Exemple #7
0
        private async Task <List <Claim> > UserVerifyGroup(String userDN)
        {
            LdapSearchConstraints cons = new LdapSearchConstraints();

            String[] atributos = new String[] { "member" };

            List <Claim> claims           = new List <Claim>();
            var          permissionGroups = await permissionGroupRepository.GetList();

            try
            {
                foreach (PermissionGroup group in permissionGroups)
                {
                    String groupDN = await GetGroupDN(group.GroupName);

                    LdapSearchResults searchResults = ldapConnection.Search(groupDN, LdapConnection.SCOPE_BASE, null, atributos, false, cons);

                    var nextEntry = searchResults.Next();
                    nextEntry.getAttributeSet();

                    try
                    {
                        if (nextEntry.getAttribute("member").StringValueArray.Where(x => x == userDN).Count() > 0)
                        {
                            claims.AddRange(GetClaimType(group.AccessType));
                            claims.Add(new Claim("Reports", group.Id.ToString()));
                        }
                    }
                    catch { }
                }
            }
            catch (Exception error)
            {
                await log.SaveLogApplicationError(controllerName, "Erro ao verificar grupo de segurança: " + error.ToString());
            }

            ldapConnection.Disconnect();

            return(claims);
        }
Exemple #8
0
        public AppUser Login(string username, string password)
        {
            connection.Connect(config.Url, LdapConnection.DEFAULT_PORT);
            connection.Bind(config.BindDn, config.BindCredentials);

            string            searchFilter = string.Format(config.AuthFilter, username);
            LdapSearchResults result       = connection.Search(
                config.SearchBase,
                LdapConnection.SCOPE_SUB,
                searchFilter,
                new[] { MemberOfAttribute, DisplayNameAttribute, SAMAccountNameAttribute, TitleAttribute, MailAttribute },
                false
                );

            try
            {
                LdapEntry user = result.Next();
                if (user != null)
                {
                    connection.Bind(user.DN, password);
                    if (connection.Bound)
                    {
                        return(new AppUser
                        {
                            DisplayName = user.getAttribute(DisplayNameAttribute)?.StringValue ?? "",
                            Username = user.getAttribute(SAMAccountNameAttribute).StringValue,
                            Email = user.getAttribute(MailAttribute)?.StringValue ?? "",
                            Position = user.getAttribute(TitleAttribute)?.StringValue ?? ""
                        });
                    }
                }
            }
            catch
            {
                throw new Exception("Введён неправильный логин или пароль");
            }
            connection.Disconnect();
            return(null);
        }
 public IEnumerator <LdapEntry> GetEnumerator()
 {
     //List<LdapEntry> list = new List<LdapEntry>();
     while (_ldapSearchResults.HasMore())
     {
         LdapEntry entry;
         try
         {
             entry = _ldapSearchResults.Next();
             //Console.WriteLine($"#######{entry.getAttribute("Name").StringValue}");
         }
         catch (LdapException)
         {
             //IGNORE (https://stackoverflow.com/questions/46052873/a-list-of-all-users-ldap-referral-error-ldapreferralexception, https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bow8fjp.html)
             //Console.WriteLine($"{e.Message}");
             //_logger.Warn(e.Message, e);
             continue;
         }
         yield return(entry);
         //list.Add(entry);
     }
     //return list.GetEnumerator();
 }
Exemple #10
0
        private static User Get(IIdentity identity)
        {
            string[] fqdn = identity.Name.Split('\\');
            User     user = new User
            {
                Name               = fqdn.Last(),
                Domain             = fqdn.First(),
                AuthenticationType = identity.AuthenticationType,
                IsAuthenticated    = identity.IsAuthenticated
            };

            using (LdapConnection ldapConnection = new LdapConnection()
            {
                SecureSocketLayer = false
            })
            {
                ldapConnection.Connect("Server", 0);
                ldapConnection.Bind(LdapConnectionSettings.Current.User, LdapConnectionSettings.Current.Password);
                string filter = string.Format("UserFilter", user.Name);

                LdapSearchResults results = ldapConnection.Search(
                    "SearchBase",
                    LdapConnection.SCOPE_SUB,
                    filter,
                    Attributes.Value,
                    false);

                LdapEntry entry = results.HasMore() ? results.Next() : null;
                if (null == entry)
                {
                    return(user);
                }

                Fill(ref user, entry);
                return(user);
            }
        }
        private async Task <bool> ValidateCredentialsAsync(string uid, TTenant tenant)
        {
            _logger.Info("ValidateCredentialsAsync against ldap host");
            int ldapPort = await _settings.GetLdapServerPort(tenant?.Id);

            string ldapHost = await _settings.GetLdapHost(tenant?.Id);

            var loginDN = await _settings.GetLdapLoginDn(tenant?.Id);

            var loginPassword = await _settings.GetPassword(tenant?.Id);

            var ldapSearchBase = await _settings.GetLdapUserSearchBase(tenant?.Id);

            string searchLdapUser = uid;

            string searchFilter = "(objectclass=*)";
            string searchBase   = $"uid={searchLdapUser}, {ldapSearchBase}"; // "ou = scientists, dc = example, dc = com"; //"uid=gauss, dc=example, dc=com";

            LdapSearchConstraints constraints = new LdapSearchConstraints {
            };

            try
            {
                using (var cn = new LdapConnection())
                {
                    // connect
                    cn.Connect(ldapHost, ldapPort);
                    cn.Bind(loginDN, loginPassword);

                    LdapSearchResults searchResults = cn.Search(
                        searchBase,
                        LdapConnection.SCOPE_SUB,
                        searchFilter,
                        null,  // no specified attributes
                        false, // false = return attr and value
                        constraints);


                    while (searchResults.HasMore())
                    {
                        if (searchResults.Count == 1)
                        {
                            LdapEntry nextEntry = null;
                            try
                            {
                                nextEntry = searchResults.Next();
                            }
                            catch (LdapException e)
                            {
                                _logger.Error("Error: " + e.LdapErrorMessage);
                                //Exception is thrown, go for next entry
                                continue;
                            }

                            LdapEntries = new Dictionary <string, string>();

                            _logger.Debug(nextEntry.DN);

                            // Get the attribute set of the entry
                            LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            // Parse through the attribute set to get the attributes and the corresponding values
                            while (ienum.MoveNext())
                            {
                                LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                                string        attributeName = attribute.Name;
                                string        attributeVal  = attribute.StringValue;
                                _logger.Debug(attributeName + "value:" + attributeVal);
                                LdapEntries.Add(attributeName, attributeVal);
                            }
                            return(true);
                        }
                    }
                }
            }
            catch (LdapException ldapEx)
            {
                throw new AbpException(ldapEx.ToString()); // ocassional time outs
            }
            catch (Exception ex)
            {
                throw new AbpException(ex.ToString());
            }
            return(false);
        }
Exemple #12
0
        /// <summary>
        /// Executes the limited search.
        /// </summary>
        /// <returns>The limited search.</returns>
        /// <param name="searchBase">Search base.</param>
        /// <param name="filter">Filter.</param>
        /// <param name="start">Must be 1 or greater</param>
        /// <param name="end">End.</param>
        public List <LdapEntry> ExecuteLimitedSearch(string searchBase, string filter, int start, int end)
        {
            int sSize = getSearchSize(searchBase, filter);

            //int sSize = 1000;

            var results = new List <LdapEntry>();

            var lcm  = LdapConnectionManager.Instance;
            var conn = lcm.GetConnection();

            var sb = searchBase + config.searchBase;

            LdapControl[] requestControls = new LdapControl[2];

            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn"); //samaccountname

            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            logger.Debug("Search Size:" + sSize);

            requestControls[1] = new LdapVirtualListControl(start, 0, end, sSize);

            //requestControls[1] = new LdapVirtualListControl(filter,0, end, null);

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;

            cons.SetControls(requestControls);
            conn.Constraints = cons;


            // Send the search request - Synchronous Search is being used here
            logger.Debug("Calling Asynchronous Search...");
            LdapSearchResults res = (LdapSearchResults)conn.Search(sb, LdapConnection.ScopeSub, filter, null, false, (LdapSearchConstraints)null);

            // Loop through the results and print them out
            while (res.HasMore())
            {
                /* Get next returned entry.  Note that we should expect a Ldap-
                 * Exception object as well just in case something goes wrong
                 */
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = res.Next();
                    results.Add(nextEntry);
                }
                catch (Exception e)
                {
                    if (e is LdapReferralException)
                    {
                        continue;
                    }
                    else
                    {
                        logger.Error("Search stopped with exception " + e.ToString());
                        break;
                    }
                }

                /* Print out the returned Entries distinguished name.  */
                logger.Debug(nextEntry.Dn);
            }

            // Server should send back a control irrespective of the
            // status of the search request
            LdapControl[] controls = res.ResponseControls;
            if (controls == null)
            {
                logger.Debug("No controls returned");
            }
            else
            {
                // We are likely to have multiple controls returned
                for (int i = 0; i < controls.Length; i++)
                {
                    /* Is this the Sort Response Control. */
                    if (controls[i] is LdapSortResponse)
                    {
                        logger.Debug("Received Ldap Sort Control from " + "Server");

                        /* We could have an error code and maybe a string
                         * identifying erring attribute in the response control.
                         */
                        System.String bad    = ((LdapSortResponse)controls[i]).FailedAttribute;
                        int           result = ((LdapSortResponse)controls[i]).ResultCode;

                        // Print out error code (0 if no error) and any
                        // returned attribute
                        logger.Debug("Error code: " + result);
                        if ((System.Object)bad != null)
                        {
                            logger.Debug("Offending " + "attribute: " + bad);
                        }
                        else
                        {
                            logger.Debug("No offending " + "attribute " + "returned");
                        }
                    }

                    /* Is this a VLV Response Control */
                    if (controls[i] is LdapVirtualListResponse)
                    {
                        logger.Debug("Received VLV Response Control from " + "Server...");

                        /* Get all returned fields */
                        int           firstPosition = ((LdapVirtualListResponse)controls[i]).FirstPosition;
                        int           ContentCount  = ((LdapVirtualListResponse)controls[i]).ContentCount;
                        int           resultCode    = ((LdapVirtualListResponse)controls[i]).ResultCode;
                        System.String context       = ((LdapVirtualListResponse)controls[i]).Context;

                        /* Print out the returned fields.  Typically you would
                         * have used these fields to reissue another VLV request
                         * or to display the list on a GUI
                         */
                        logger.Debug("Result Code    => " + resultCode);
                        logger.Debug("First Position => " + firstPosition);
                        logger.Debug("Content Count  => " + ContentCount);
                        if ((System.Object)context != null)
                        {
                            logger.Debug("Context String => " + context);
                        }
                        else
                        {
                            logger.Debug("No Context String in returned" + " control");
                        }
                    }
                }
            }

            return(results);
        }
Exemple #13
0
        private int getSearchSize(string searchBase, string filter)
        {
            var results = new List <LdapEntry>();

            var lcm  = LdapConnectionManager.Instance;
            var conn = lcm.GetConnection();

            var sb = searchBase + config.searchBase;

            LdapControl[] requestControls = new LdapControl[2];

            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn"); //samaccountname

            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            requestControls[1] = new LdapVirtualListControl(1, 0, 1, config.maxResults);

            //requestControls[1] = new LdapVirtualListControl(sb,0, config.maxResults, null);

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;

            cons.SetControls(requestControls);
            conn.Constraints = cons;


            // Send the search request - Synchronous Search is being used here
            logger.Debug("Calling Asynchronous Search...");
            LdapSearchResults res = (LdapSearchResults)conn.Search(sb, LdapConnection.ScopeOne, filter, null, false,
                                                                   (LdapSearchConstraints)null);

            while (res.HasMore())
            {
                res.Next();
            }

            // Server should send back a control irrespective of the
            // status of the search request
            LdapControl[] controls = res.ResponseControls;
            if (controls == null)
            {
                logger.Debug("No controls returned");
            }
            else
            {
                // We are likely to have multiple controls returned
                for (int i = 0; i < controls.Length; i++)
                {
                    /* Is this a VLV Response Control */
                    if (controls[i] is LdapVirtualListResponse)
                    {
                        logger.Debug("Received VLV Response Control from " + "Server...");

                        /* Get all returned fields */
                        int           firstPosition = ((LdapVirtualListResponse)controls[i]).FirstPosition;
                        int           ContentCount  = ((LdapVirtualListResponse)controls[i]).ContentCount;
                        int           resultCode    = ((LdapVirtualListResponse)controls[i]).ResultCode;
                        System.String context       = ((LdapVirtualListResponse)controls[i]).Context;

                        /* Print out the returned fields.  Typically you would
                         * have used these fields to reissue another VLV request
                         * or to display the list on a GUI
                         */
                        logger.Debug("Result Code    => " + resultCode);
                        logger.Debug("First Position => " + firstPosition);
                        logger.Debug("Content Count  => " + ContentCount);
                        if ((System.Object)context != null)
                        {
                            logger.Debug("Context String => " + context);
                        }
                        else
                        {
                            logger.Debug("No Context String in returned" + " control");
                        }

                        return(ContentCount);
                    }
                }
            }

            return(-1);
        }
Exemple #14
0
            public List <DomainObject> GetDomainGroups(IEnumerable <string> Identities = null, string LDAPFilter = "",
                                                       IEnumerable <string> Properties = null, bool AdminCount   = false, string GroupScope = "",
                                                       string GroupProperty            = "", bool FindOne = false, int SearchScope = LdapConnection.SCOPE_SUB)
            {
                string Filter         = "";
                string IdentityFilter = ConvertIdentitiesToFilter(Identities, DomainObjectType.User, this.Domain);

                string[] Props = null;

                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += "(|" + IdentityFilter + ")";
                }
                if (AdminCount)
                {
                    Filter += "(admincount=1)";
                }
                if (GroupScope == "DomainLocal")
                {
                    Filter += "(groupType:1.2.840.113556.1.4.803:=4)";
                }
                else if (GroupScope == "NotDomainLocal")
                {
                    Filter += "(!(groupType:1.2.840.113556.1.4.803:=4))";
                }
                else if (GroupScope == "Global")
                {
                    Filter += "(groupType:1.2.840.113556.1.4.803:=2)";
                }
                else if (GroupScope == "NotGlobal")
                {
                    Filter += "(!(groupType:1.2.840.113556.1.4.803:=2))";
                }
                else if (GroupScope == "Universal")
                {
                    Filter += "(groupType:1.2.840.113556.1.4.803:=8)";
                }
                else if (GroupScope == "NotUniversal")
                {
                    Filter += "(!(groupType:1.2.840.113556.1.4.803:=8))";
                }

                if (GroupProperty == "Security")
                {
                    Filter += "(groupType:1.2.840.113556.1.4.803:=2147483648)";
                }
                else if (GroupProperty == "Distribution")
                {
                    Filter += "(!(groupType:1.2.840.113556.1.4.803:=2147483648))";
                }
                else if (GroupProperty == "CreatedBySystem")
                {
                    Filter += "(groupType:1.2.840.113556.1.4.803:=1)";
                }
                else if (GroupProperty == "NotCreatedBySystem")
                {
                    Filter += "(!(groupType:1.2.840.113556.1.4.803:=1))";
                }
                if (Properties != null)
                {
                    Props = Props.ToArray();
                }

                Filter += LDAPFilter;
                Filter  = "(&(objectCategory=group)" + Filter + ")";
                Console.WriteLine("Final Filter: {0}", Filter);
                Console.WriteLine(this.SearchBase);
                Console.WriteLine(SearchScope);
                LdapSearchResults   lsc     = this.Searcher.Search(this.SearchBase, SearchScope, Filter, Props, false);
                List <DomainObject> results = new List <DomainObject>();

                while (lsc.HasMore())
                {
                    try
                    {
                        results.Add(ConvertLDAPProperty(lsc.Next()));
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }

                return(results);
            }
Exemple #15
0
            public List <DomainObject> GetDomainUsers(IEnumerable <string> Identities = null, string LDAPFilter = "",
                                                      IEnumerable <string> Properties = null, bool SPN          = false, bool AllowDelegation = false,
                                                      bool DisallowDelegation         = false, bool AdminCount  = false, bool TrustedToAuth   = false,
                                                      bool PreauthNotRequired         = false, int SearchScope  = LdapConnection.SCOPE_SUB,
                                                      IEnumerable <UACEnum> UACFilter = null)
            {
                string Filter         = "";
                string IdentityFilter = ConvertIdentitiesToFilter(Identities, DomainObjectType.User, this.Domain);

                string[] Props = null;

                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += "(|" + IdentityFilter + ")";
                }

                if (SPN)
                {
                    Filter += "(servicePrincipalName=*)";
                }

                if (AllowDelegation)
                {
                    Filter += "(!(userAccountControl:1.2.840.113556.1.4.803:=1048574))";
                }

                if (DisallowDelegation)
                {
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=1048574)";
                }

                if (AdminCount)
                {
                    Filter += "(admincount=1)";
                }

                if (TrustedToAuth)
                {
                    Filter += "(msds-allowedtodelegateto=*)";
                }

                if (PreauthNotRequired)
                {
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=4194304)";
                }

                if (Properties != null)
                {
                    Props = Props.ToArray();
                }

                Filter += LDAPFilter;
                //805306368 = All User objects
                Filter = "(&(sAMAccountType=805306368)" + Filter + ")";

                Console.WriteLine("Final Filter: {0}", Filter);
                Console.WriteLine(this.SearchBase);
                Console.WriteLine(SearchScope);
                LdapSearchResults   lsc     = this.Searcher.Search(this.SearchBase, SearchScope, Filter, Props, false);
                List <DomainObject> results = new List <DomainObject>();


                while (lsc.HasMore())
                {
                    try
                    {
                        results.Add(ConvertLDAPProperty(lsc.Next()));
                    }
                    catch
                    {
                        continue;
                    }
                }

                return(results);
            }
Exemple #16
0
    public static void Main(String[] args)
    {
        if (args.Length != 5)
        {
            Console.WriteLine("Usage:   mono ClientSideSort <host name> " +
                              "<login dn> <password> <search base>\n"
                              + "         <search filter>");
            Console.WriteLine("Example: mono ClientSideSort Acme.com"
                              + " \"cn=admin,o=Acme\""
                              + " secret \"ou=sales,o=Acme\"\n"
                              + "         \"(objectclass=*)\"");
            Environment.Exit(0);
        }

        int            ldapPort     = LdapConnection.DEFAULT_PORT;
        int            searchScope  = LdapConnection.SCOPE_ONE;
        int            ldapVersion  = LdapConnection.Ldap_V3;
        String         ldapHost     = args[0];
        String         loginDN      = args[1];
        String         password     = args[2];
        String         searchBase   = args[3];
        String         searchFilter = args[4];
        LdapConnection conn         = new LdapConnection();

        try
        {
            // connect to the server
            conn.Connect(ldapHost, ldapPort);

            // bind to the server
            conn.Bind(ldapVersion, loginDN, password);

            LdapSearchResults searchResults = conn.Search(searchBase,
                                                          searchScope,
                                                          searchFilter,
                                                          new String[] { "cn", "uid", "sn" }, //attributes
                                                          false);                             // return attrs and values

            /* sortedResults will sort the entries according to the natural
             * ordering of LDAPEntry (by distiguished name).
             */

            ArrayList sortedResults = new ArrayList();


            while (searchResults.HasMore())
            {
                try
                {
                    sortedResults.Add(searchResults.Next());
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.ToString());
                    // Exception is thrown, go for next entry
                    continue;
                }
            }

            // print the sorted results
            Console.WriteLine("\n" +
                              "****************************\n" +
                              "Search results sorted by DN:\n" +
                              "****************************");
            sortedResults.Sort();
            IEnumerator i = sortedResults.GetEnumerator(0, sortedResults.Count - 1);
            while (i.MoveNext())
            {
                PrintEntry((LdapEntry)(i.Current));
            }

            /* resort the results an an array using a specific comparator */
            String[]             namesToSortBy = { "sn", "uid", "cn" };
            bool[]               sortAscending = { true, false, true };
            LdapCompareAttrNames myComparator  = new LdapCompareAttrNames(namesToSortBy, sortAscending);

            Object[] sortedSpecial = sortedResults.ToArray();
            Array.Sort(sortedSpecial, myComparator);

            // print the re-sorted results
            Console.WriteLine("\n" +
                              "*****************************************************\n" +
                              "Search results sorted by sn, uid(Descending), and cn:\n" +
                              "*****************************************************");
            for (int j = 0; j < sortedSpecial.Length; j++)
            {
                PrintEntry((LdapEntry)sortedSpecial[j]);
            }
            // disconnect with the server
            conn.Disconnect();
        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        Environment.Exit(0);
    }
Exemple #17
0
        static void Main(string[] args)
        {
            if (args.Length != 6)
            {
                Console.WriteLine("Usage:   mono Search <host name> <ldap port>  <login dn>" + " <password> <search base>" + " <search filter>");
                Console.WriteLine("Example: mono Search Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"" + "         \"(objectclass=*)\"");
                return;
            }

            string ldapHost     = args[0];
            int    ldapPort     = System.Convert.ToInt32(args[1]);
            String loginDN      = args[2];
            String password     = args[3];
            String searchBase   = args[4];
            String searchFilter = args[5];

            try
            {
                LdapConnection conn = new LdapConnection();
                Console.WriteLine("Connecting to:" + ldapHost);
                conn.Connect(ldapHost, ldapPort);
                conn.Bind(loginDN, password);
                LdapSearchResults lsc = conn.Search(searchBase,
                                                    LdapConnection.SCOPE_SUB,
                                                    searchFilter,
                                                    null,
                                                    false);

                while (lsc.HasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (LdapException e)
                    {
                        Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    }
                    Console.WriteLine("\n" + nextEntry.DN);
                    LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;
                        if (!Base64.isLDIFSafe(attributeVal))
                        {
                            byte[] tbyte = SupportClass.ToByteArray(attributeVal);
                            attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte));
                        }
                        Console.WriteLine(attributeName + "value:" + attributeVal);
                    }
                }
                conn.Disconnect();
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error:" + e.LdapErrorMessage);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
                return;
            }
        }
Exemple #18
0
    // read and print search results
    public static bool searchDynamicGroupEntry(LdapConnection lc,
                                               String searchBase)
    {
        bool status      = true;
        int  searchScope = LdapConnection.SCOPE_BASE;

        String[] attrList     = new String[] { "member" };
        String   searchFilter = "(objectclass=*)";


        /* Since reading members of a dynamic group could potentially involve
         * a significant directory search, we use a timeout. Setting
         * time out to 10 seconds
         */
        LdapSearchConstraints cons = new LdapSearchConstraints();

        cons.TimeLimit = 10000;

        try
        {
            LdapSearchResults searchResults =
                lc.Search(searchBase,
                          searchScope,
                          searchFilter,
                          attrList,                // return only "member" attr
                          false,                   // return attrs and values
                          cons);                   // time out value

            LdapEntry nextEntry = null;
            // Read and print search results.  We expect only one entry */
            if ((nextEntry = searchResults.Next()) != null)
            {
                LdapAttributeSet attributeSet  = nextEntry.getAttributeSet();
                IEnumerator      allAttributes = attributeSet.GetEnumerator();

                if (allAttributes.MoveNext())
                {
                    // found member(s) in this group
                    LdapAttribute attribute =
                        (LdapAttribute)allAttributes.Current;
                    String attributeName = attribute.Name;

                    IEnumerator allValues = attribute.StringValues;

                    if (allValues != null)
                    {
                        while (allValues.MoveNext())
                        {
                            String Value = (String)allValues.Current;
                            Console.WriteLine("            " + attributeName
                                              + " : " + Value);
                        }
                    }
                }
                else
                {
                    // no member(s) found in this group
                    Console.WriteLine("            No objects matched the "
                                      + " memberQueryURL filter.\n  ");
                }
            }
        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
            status = false;
        }
        return(status);
    }
Exemple #19
0
        public static void Test()
        {
            string ldapHost = TestSettings.ldapHost; // args[0];
            int    ldapPort = TestSettings.ldapPort; // System.Convert.ToInt32(args[1]);
            string loginDN  = TestSettings.loginDN;  // args[2];
            string password = TestSettings.password; // args[3];


            string searchBase = "DC=cor,DC=local"; // args[4];

            searchBase = null;
            searchBase = "DC=rootDSE";
            searchBase = "DC=cor,DC=local";
            searchBase = " ";
            // searchBase = "CN=Configuration,DC=cor,DC=local";
            /// searchBase = "CN=,DC=cor,DC=local";
            // searchBase = "rootDSE";

            string searchFilter = "(objectclass=*)";

            searchFilter = "(objectClass=*)";

            try
            {
                LdapConnection conn = new LdapConnection();
                Console.WriteLine("Connecting to:" + ldapHost);
                conn.Connect(ldapHost, ldapPort);



                conn.Bind(loginDN, password);

                //dsServiceName
                //CN = NTDS Settings,CN = COR - AD02,CN = Servers,CN = COR - ERLEN,CN = Sites,CN = Configuration,DC = cor,DC = local

                //serverName
                //CN = COR - AD02, CN = Servers, CN = COR - ERLEN, CN = Sites, CN = Configuration, DC = cor, DC = local

                //configurationNamingContext
                //CN = Configuration, DC = cor, DC = local

                //dnsHostName
                //cor - ad02.cor.local

                string defaultNamingContext       = GetDefaultNamingContext(conn);
                string configurationNamingContext = GetConfigurationNamingContext(conn);
                string dnsHostName = GetDnsHostName(conn);

                System.Console.WriteLine(defaultNamingContext);
                System.Console.WriteLine(configurationNamingContext);
                System.Console.WriteLine(dnsHostName);

                GetRootDSE(conn);



                string foo = conn.GetSchemaDN();
                System.Console.WriteLine(foo);


                LdapSearchResults lsc = conn.Search(searchBase,
                                                    LdapConnection.SCOPE_SUB,
                                                    searchFilter,
                                                    null,
                                                    false);

                while (lsc.HasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (LdapException e)
                    {
                        Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    }
                    Console.WriteLine("\n" + nextEntry.DN);
                    LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;
                        if (!Base64.isLDIFSafe(attributeVal))
                        {
                            byte[] tbyte = SupportClass.ToByteArray(attributeVal);
                            attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte));
                        }

                        if (string.Equals(attributeName, "defaultNamingContext", StringComparison.InvariantCultureIgnoreCase))
                        {
                            System.Console.WriteLine("yahoo");
                        }

                        Console.WriteLine(attributeName + "value:" + attributeVal);
                    }
                }
                conn.Disconnect();
                System.Console.WriteLine("disconnected");
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error:" + e.LdapErrorMessage);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
                return;
            }
        }
Exemple #20
0
    public static void  Main(System.String[] args)
    {
        /* Check if we have the correct number of command line arguments */
        if (args.Length != 4)
        {
            System.Console.Error.WriteLine("Usage:   mono VLVControl <host name> <login dn>" + " <password> <container>");
            System.Console.Error.WriteLine("Example: mono VLVControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\"");
            System.Environment.Exit(1);
        }

        /* Parse the command line arguments  */
        System.String  LdapHost    = args[0];
        System.String  loginDN     = args[1];
        System.String  password    = args[2];
        System.String  searchBase  = args[3];
        int            LdapPort    = LdapConnection.DEFAULT_PORT;
        int            LdapVersion = LdapConnection.Ldap_V3;
        LdapConnection conn        = new LdapConnection();

        try
        {
            // connect to the server
            conn.Connect(LdapHost, LdapPort);
            // bind to the server
            conn.Bind(LdapVersion, loginDN, password);
            System.Console.Out.WriteLine("Succesfully logged in to server: " + LdapHost);

            /* Set default filter - Change this line if you need a different set
             * of search restrictions. Read the "NDS and Ldap Integration Guide"
             * for information on support by Novell eDirectory of this
             * functionaliry.
             */
            System.String MY_FILTER = "cn=*";

            /* We are requesting that the givenname and cn fields for each
             * object be returned
             */
            System.String[] attrs = new System.String[2];
            attrs[0] = "givenname";
            attrs[1] = "cn";

            // We will be sending two controls to the server
            LdapControl[] requestControls = new LdapControl[2];

            /* Create the sort key to be used by the sort control
             * Results should be sorted based on the cn attribute.
             * See the "NDS and Ldap Integration Guide" for information on
             * Novell eDirectory support of this functionaliry.
             */
            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn");

            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            /* Create the VLV Control.
             * These two fields in the VLV Control identify the before and
             * after count of entries to be returned
             */
            int beforeCount = 0;
            int afterCount  = 2;

            /* The VLV control request can specify the index
             * using one of the two methods described below:
             *
             * TYPED INDEX: Here we request all objects that have cn greater
             * than or equal to the letter "a"
             */
            requestControls[1] = new LdapVirtualListControl("a", beforeCount, afterCount);

            /* The following code needs to be enabled to specify the index
             * directly
             *   int offset = 0; - offset of the index
             *   int contentCount = 3; - our estimate of the search result size
             *   requestControls[1] = new LdapVirtualListControl(offset,
             *                          beforeCount, afterCount, contentCount);
             */

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;
            cons.setControls(requestControls);
            conn.Constraints = cons;

            // Send the search request - Synchronous Search is being used here
            System.Console.Out.WriteLine("Calling Asynchronous Search...");
            LdapSearchResults res = conn.Search(searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchConstraints)null);

            // Loop through the results and print them out
            while (res.HasMore())
            {
                /* Get next returned entry.  Note that we should expect a Ldap-
                 * Exception object as well just in case something goes wrong
                 */
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = res.Next();
                }
                catch (LdapException e)
                {
                    if (e is LdapReferralException)
                    {
                        continue;
                    }
                    else
                    {
                        System.Console.Out.WriteLine("Search stopped with exception " + e.ToString());
                        break;
                    }
                }

                /* Print out the returned Entries distinguished name.  */
                System.Console.Out.WriteLine();
                System.Console.Out.WriteLine(nextEntry.DN);

                /* Get the list of attributes for the current entry */
                LdapAttributeSet findAttrs = nextEntry.getAttributeSet();

                /* Convert attribute list to Enumeration */
                System.Collections.IEnumerator enumAttrs = findAttrs.GetEnumerator();
                System.Console.Out.WriteLine("Attributes: ");

                /* Loop through all attributes in the enumeration */
                while (enumAttrs.MoveNext())
                {
                    LdapAttribute anAttr = (LdapAttribute)enumAttrs.Current;

                    /* Print out the attribute name */
                    System.String attrName = anAttr.Name;
                    System.Console.Out.WriteLine("" + attrName);

                    // Loop through all values for this attribute and print them
                    System.Collections.IEnumerator enumVals = anAttr.StringValues;
                    while (enumVals.MoveNext())
                    {
                        System.String aVal = (System.String)enumVals.Current;
                        System.Console.Out.WriteLine("" + aVal);
                    }
                }
            }

            // Server should send back a control irrespective of the
            // status of the search request
            LdapControl[] controls = res.ResponseControls;
            if (controls == null)
            {
                System.Console.Out.WriteLine("No controls returned");
            }
            else
            {
                // We are likely to have multiple controls returned
                for (int i = 0; i < controls.Length; i++)
                {
                    /* Is this the Sort Response Control. */
                    if (controls[i] is LdapSortResponse)
                    {
                        System.Console.Out.WriteLine("Received Ldap Sort Control from " + "Server");

                        /* We could have an error code and maybe a string
                         * identifying erring attribute in the response control.
                         */
                        System.String bad    = ((LdapSortResponse)controls[i]).FailedAttribute;
                        int           result = ((LdapSortResponse)controls[i]).ResultCode;

                        // Print out error code (0 if no error) and any
                        // returned attribute
                        System.Console.Out.WriteLine("Error code: " + result);
                        if ((System.Object)bad != null)
                        {
                            System.Console.Out.WriteLine("Offending " + "attribute: " + bad);
                        }
                        else
                        {
                            System.Console.Out.WriteLine("No offending " + "attribute " + "returned");
                        }
                    }

                    /* Is this a VLV Response Control */
                    if (controls[i] is LdapVirtualListResponse)
                    {
                        System.Console.Out.WriteLine("Received VLV Response Control from " + "Server...");

                        /* Get all returned fields */
                        int           firstPosition = ((LdapVirtualListResponse)controls[i]).FirstPosition;
                        int           ContentCount  = ((LdapVirtualListResponse)controls[i]).ContentCount;
                        int           resultCode    = ((LdapVirtualListResponse)controls[i]).ResultCode;
                        System.String context       = ((LdapVirtualListResponse)controls[i]).Context;


                        /* Print out the returned fields.  Typically you would
                         * have used these fields to reissue another VLV request
                         * or to display the list on a GUI
                         */
                        System.Console.Out.WriteLine("Result Code    => " + resultCode);
                        System.Console.Out.WriteLine("First Position => " + firstPosition);
                        System.Console.Out.WriteLine("Content Count  => " + ContentCount);
                        if ((System.Object)context != null)
                        {
                            System.Console.Out.WriteLine("Context String => " + context);
                        }
                        else
                        {
                            System.Console.Out.WriteLine("No Context String in returned" + " control");
                        }
                    }
                }
            }

            /* We are done - disconnect */
            if (conn.Connected)
            {
                conn.Disconnect();
            }
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine(e.ToString());
        }
        catch (System.IO.IOException e)
        {
            System.Console.Out.WriteLine("Error: " + e.ToString());
        }
        catch (Exception e)
        {
            System.Console.WriteLine("Error: " + e.Message);
        }
    }
        static void Main(string[] args)
        {
            if (args.Length != 6)
            {
                Console.WriteLine("Usage:   mono SortSearch <host name> <ldap port>  <login dn>" + " <password> <search base>" + " <search filter>");
                Console.WriteLine("Example: mono SortSearch Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"" + "         \"(objectclass=*)\"");
                return;
            }

            string ldapHost     = args[0];
            int    ldapPort     = System.Convert.ToInt32(args[1]);
            String loginDN      = args[2];
            String password     = args[3];
            String searchBase   = args[4];
            String searchFilter = args[5];

            String[] attrs = new String[1];
            attrs[0] = "sn";

            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("sn");

            try
            {
                LdapConnection conn = new LdapConnection();
                conn.Connect(ldapHost, ldapPort);
                conn.Bind(loginDN, password);


                // Create a LDAPSortControl object - Fail if cannot sort
                LdapSortControl sort = new LdapSortControl(keys, true);

                // Set the Sort control to be sent as part of search request
                LdapSearchConstraints cons = conn.SearchConstraints;
                cons.setControls(sort);
                conn.Constraints = cons;

                Console.WriteLine("Connecting to:" + ldapHost);
                LdapSearchResults lsc = conn.Search(searchBase,
                                                    LdapConnection.SCOPE_SUB,
                                                    searchFilter,
                                                    attrs,
                                                    false,
                                                    (LdapSearchConstraints)null);

                while (lsc.HasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (LdapException e)
                    {
                        Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    }
                    Console.WriteLine("\n" + nextEntry.DN);
                    LdapAttributeSet attributeSet        = nextEntry.getAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;
                        Console.WriteLine(attributeName + "value:" + attributeVal);
                    }
                }

                conn.Disconnect();
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error:" + e.LdapErrorMessage);
                Console.WriteLine("Error:" + e.ToString());
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
                return;
            }
        }
Exemple #22
0
            public List <DomainObject> GetDomainComputers(IEnumerable <string> Identities = null, string LDAPFilter = "", IEnumerable <string> Properties = null, IEnumerable <UACEnum> UACFilter = null, bool Unconstrained = false, bool TrustedToAuth = false, bool Printers = false, string SPN = "", string OperatingSystem = "", string ServicePack = "", string SiteName = "", bool Ping = false, bool FindOne = false, int SearchScope = LdapConnection.SCOPE_SUB)
            {
                string Filter         = "";
                string IdentityFilter = ConvertIdentitiesToFilter(Identities, DomainObjectType.Computer);

                string[] Props = null;
                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += "(|" + IdentityFilter + ")";
                }

                if (Unconstrained)
                {
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=524288)";
                }
                if (TrustedToAuth)
                {
                    Filter += "(msds-allowedtodelegateto=*)";
                }
                if (Printers)
                {
                    Filter += "(objectCategory=printQueue)";
                }
                if (SPN != "")
                {
                    Filter += "(servicePrincipalName=" + SPN + ")";
                }
                if (OperatingSystem != "")
                {
                    Filter += "(operatingsystem=" + OperatingSystem + ")";
                }
                if (ServicePack != "")
                {
                    Filter += "(operatingsystemservicepack=" + ServicePack + ")";
                }
                if (SiteName != "")
                {
                    Filter += "(serverreferencebl=" + SiteName + ")";
                }

                Filter += LDAPFilter;
                if (UACFilter != null)
                {
                    foreach (UACEnum uac in UACFilter)
                    {
                        Filter += "(userAccountControl:1.2.840.113556.1.4.803:=" + ((int)uac) + ")";
                    }
                }

                Filter = "(&(samAccountType=805306369)" + Filter + ")";
                Console.WriteLine("Final Filter: {0}", Filter);
                Console.WriteLine(this.SearchBase);
                Console.WriteLine(SearchScope);
                LdapSearchResults   lsc     = this.Searcher.Search(this.SearchBase, SearchScope, Filter, Props, false);
                List <DomainObject> results = new List <DomainObject>();

                while (lsc.HasMore())
                {
                    try
                    {
                        results.Add(ConvertLDAPProperty(lsc.Next()));
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }

                return(results);
            }
        static void Main(string[] args)
        {
            // https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
            int    ldapPort    = LdapConnection.DEFAULT_PORT;
            int    ldapVersion = LdapConnection.Ldap_V3;
            string ldapHost    = "ldap.forumsys.com";
            var    loginDN     = "cn=read-only-admin,dc=example,dc=com";
            var    password    = "******";

            string searchLdapUser = "******";

            string searchFilter = "(objectclass=*)";
            string searchBase   = $"uid={searchLdapUser}, dc=example, dc=com"; // "ou = scientists, dc = example, dc = com"; //"uid=gauss, dc=example, dc=com";

            LdapSearchConstraints constraints = new LdapSearchConstraints {
            };

            var users = new HashSet <string>();

            try
            {
                using (var cn = new LdapConnection())
                {
                    // connect
                    cn.Connect(ldapHost, ldapPort);
                    cn.Bind(loginDN, password);

                    LdapSearchResults searchResults = cn.Search(
                        searchBase,
                        LdapConnection.SCOPE_SUB,
                        searchFilter,
                        null, // no specified attributes
                        true, // false = return attr and value
                        constraints);


                    while (searchResults.HasMore())
                    {
                        if (searchResults.Count == 1)
                        {
                            Console.WriteLine("true - found");
                        }
                        searchResults.Next();
                    }
                }
            }
            catch (LdapException ldapEx)
            {
                Console.WriteLine(ldapEx.ToString()); // ocassional time outs
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            foreach (var u in users)
            {
                Console.WriteLine("Key:" + u);
            }
            Console.ReadKey();
        }
Exemple #24
0
    public static void Main(String[] args)
    {
        if (args.Length != 5)
        {
            Console.Error.WriteLine("Usage:   mono List <host name> <login dn>"
                                    + " <password> <search base>\n"
                                    + "         <search filter>");
            Console.Error.WriteLine("Example: mono List Acme.com \"cn=admin,o=Acme\""
                                    + " secret \"ou=sales,o=Acme\"\n"
                                    + "         \"(objectclass=*)\"");
            Environment.Exit(1);
        }

        int  LdapPort      = LdapConnection.DEFAULT_PORT;
        int  searchScope   = LdapConnection.SCOPE_ONE;
        int  LdapVersion   = LdapConnection.Ldap_V3;;
        bool attributeOnly = true;

        String[]       attrs        = { LdapConnection.NO_ATTRS };
        String         ldapHost     = args[0];
        String         loginDN      = args[1];
        String         password     = args[2];
        String         searchBase   = args[3];
        String         searchFilter = args[4];
        LdapConnection lc           = new LdapConnection();

        try
        {
            // connect to the server
            lc.Connect(ldapHost, LdapPort);
            // bind to the server
            lc.Bind(LdapVersion, loginDN, password);

            LdapSearchResults searchResults =
                lc.Search(searchBase,            // container to search
                          searchScope,           // search scope
                          searchFilter,          // search filter
                          attrs,                 // "1.1" returns entry name only
                          attributeOnly);        // no attributes are returned

            // print out all the objects
            while (searchResults.HasMore())
            {
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = searchResults.Next();
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.ToString());

                    // Exception is thrown, go for next entry
                    continue;
                }

                Console.WriteLine("\n" + nextEntry.DN);
            }
            // disconnect with the server
            lc.Disconnect();
        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        Environment.Exit(0);
    }
Exemple #25
0
    public static void Main(String[] args)
    {
        if (args.Length != 4)
        {
            Console.WriteLine("Usage:   mono ListGroups <host name> <login dn>"
                              + " <password> <group dn>\n");
            Console.WriteLine("Example: mono ListGroups Acme.com"
                              + " \"cn=admin,o=Acme\" secret "
                              + " cn=salesGroup,ou=sales,o=acme\n");
            Environment.Exit(0);
        }

        int         ldapPort    = LdapConnection.DEFAULT_PORT;
        int         searchScope = LdapConnection.SCOPE_BASE;
        int         ldapVersion = LdapConnection.Ldap_V3;
        int         i;
        IEnumerator objClass = null;
        IEnumerator queryURL = null;
        IEnumerator identity = null;
        IEnumerator excludedMember = null;
        IEnumerator member = null;
        bool        isGroup = false, isDynamicGroup = false;

        String[] attrs = new String[] { "objectClass",
                                        "memberQueryURL",
                                        "dgIdentity",
                                        "excludedMember",
                                        "member" };

        /* Since reading members of a dynamic group could potentially involve
         * a significant directory search, we use a timeout. Setting
         * time out to 10 seconds
         */
        LdapSearchConstraints cons = new LdapSearchConstraints();

        cons.TimeLimit = 10000;

        String ldapHost = args[0];
        String loginDN  = args[1];
        String password = args[2];
        String groupDN  = args[3];

        LdapConnection lc = new LdapConnection();

        try
        {
            // connect to the server
            lc.Connect(ldapHost, ldapPort);
            // bind to the server
            lc.Bind(ldapVersion, loginDN, password);

            Console.WriteLine("\n\tReading object :" + groupDN);
            LdapSearchResults searchResults =
                lc.Search(groupDN,             // object to read
                          searchScope,         // scope - read single object
                          null,                // search filter
                          attrs,               // return only required attributes
                          false,               // return attrs and values
                          cons);               // time out value

            // Examine the attributes that were returned and extract the data

            LdapEntry nextEntry = null;
            try
            {
                nextEntry = searchResults.Next();
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error: " + e.ToString());
                Environment.Exit(1);
            }

            LdapAttributeSet attributeSet  = nextEntry.getAttributeSet();
            IEnumerator      allAttributes = attributeSet.GetEnumerator();

            while (allAttributes.MoveNext())
            {
                LdapAttribute attribute     = (LdapAttribute)allAttributes.Current;
                String        attributeName = attribute.Name;
                // Save objectclass values
                if (attributeName.ToUpper().Equals("objectClass".ToUpper()))
                {
                    objClass = attribute.StringValues;
                }

                // Save the memberQueryURL attribute if present
                else if (attributeName.ToUpper().Equals("memberQueryURL".ToUpper()))
                {
                    queryURL = attribute.StringValues;
                }

                // Save the dgIdentity attribute if present
                else if (attributeName.ToUpper().Equals("dgIdentity".ToUpper()))
                {
                    identity = attribute.StringValues;
                }

                // Save the excludedMember attribute if present
                else if (attributeName.ToUpper().Equals("excludedMember".ToUpper()))
                {
                    excludedMember = attribute.StringValues;
                }

                /* Save the member attribute.  This may also show up
                 * as uniqueMember
                 */
                else if (attributeName.ToUpper().Equals("member".ToUpper()) ||
                         attributeName.ToUpper().Equals("uniqueMember".ToUpper()))
                {
                    member = attribute.StringValues;
                }
            }

            /* Verify that this is a group object  (i.e. objectClass contains
             * the value "group", "groupOfNames", or "groupOfUniqueNames").
             * Also determine if this is a dynamic group object
             * (i.e. objectClass contains the value "dynamicGroup" or
             * "dynamicGroupAux").
             */
            while (objClass.MoveNext())
            {
                String objectName = (String)objClass.Current;
                if (objectName.ToUpper().Equals("group".ToUpper()) ||
                    objectName.ToUpper().Equals("groupOfNames".ToUpper()) ||
                    objectName.ToUpper().Equals("groupOfUniqueNames".ToUpper()))
                {
                    isGroup = true;
                }
                else if (objectName.ToUpper().Equals("dynamicGroup".ToUpper()) ||
                         objectName.ToUpper().Equals("dynamicGroupAux".ToUpper()))
                {
                    isGroup = isDynamicGroup = true;
                }
            }

            if (!isGroup)
            {
                Console.WriteLine("\tThis object is NOT a group object."
                                  + "Exiting.\n");
                Environment.Exit(0);
            }

            /* If this is a dynamic group, display its memberQueryURL, identity
             * and excluded member list.
             */
            if (isDynamicGroup)
            {
                if ((queryURL != null) && (queryURL.MoveNext()))
                {
                    Console.WriteLine("\tMember Query URL:");
                    while (queryURL.MoveNext())
                    {
                        Console.WriteLine("\t\t" + queryURL.Current);
                    }
                }

                if ((identity != null) && (identity.MoveNext()))
                {
                    Console.WriteLine("\tIdentity for search:"
                                      + identity.Current);
                }

                if ((excludedMember != null) &&
                    (excludedMember.MoveNext()))
                {
                    Console.WriteLine("\tExcluded member list:");
                    while (excludedMember.MoveNext())
                    {
                        Console.WriteLine("\t\t"
                                          + excludedMember.Current);
                    }
                }
            }

            // Print the goup's member list
            if (member != null && member.MoveNext())
            {
                Console.WriteLine("\n\tMember list:");
                while (member.MoveNext())
                {
                    Console.WriteLine("\t\t" + member.Current);
                }
            }

            // disconnect with the server
            lc.Disconnect();
        }
        catch (LdapException e)
        {
            Console.WriteLine("Error: " + e.ToString());
            Environment.Exit(1);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.ToString());
        }
        Environment.Exit(0);
    }