Esempio n. 1
0
        public List <LdapObject> SearchSimple(string searchBase, LdapScope scope, string searchFilter,
                                              string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null)
        {
            if (!IsConnected)
            {
                Connect();
            }

            if (searchBase == null)
            {
                searchBase = "";
            }

            var entries = new List <LdapEntry>();

            if (string.IsNullOrEmpty(searchFilter))
            {
                return(new List <LdapObject>());
            }

            if (attributes == null)
            {
                if (string.IsNullOrEmpty(LdapUniqueIdAttribute))
                {
                    attributes = new[]
                    {
                        "*", LdapConstants.RfcLDAPAttributes.ENTRY_DN, LdapConstants.RfcLDAPAttributes.ENTRY_UUID,
                        LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, LdapConstants.RfcLDAPAttributes.GUID
                    };
                }
                else
                {
                    attributes = new[] { "*", LdapUniqueIdAttribute };
                }
            }

            var ldapSearchConstraints = searchConstraints ?? new LdapSearchConstraints
            {
                // Maximum number of search results to return.
                // The value 0 means no limit. The default is 1000.
                MaxResults = limit == -1 ? 0 : limit,
                // Returns the number of results to block on during receipt of search results.
                // This should be 0 if intermediate results are not needed, and 1 if results are to be processed as they come in.
                //BatchSize = 0,
                // The maximum number of referrals to follow in a sequence during automatic referral following.
                // The default value is 10. A value of 0 means no limit.
                HopLimit = 0,
                // Specifies whether referrals are followed automatically
                // Referrals of any type other than to an LDAP server (for example, a referral URL other than ldap://something) are ignored on automatic referral following.
                // The default is false.
                ReferralFollowing = true,
                // The number of seconds to wait for search results.
                // Sets the maximum number of seconds that the server is to wait when returning search results.
                //ServerTimeLimit = 600000, // 10 minutes
                // Sets the maximum number of milliseconds the client waits for any operation under these constraints to complete.
                // If the value is 0, there is no maximum time limit enforced by the API on waiting for the operation results.
                //TimeLimit = 600000 // 10 minutes
            };

            // initially, cookie must be set to an empty string
            var pageSize = 2;

            sbyte[] cookie = Array.ConvertAll(Encoding.ASCII.GetBytes(""), b => unchecked ((sbyte)b));
            var     i      = 0;

            do
            {
                var requestControls = new LdapControl[1];
                requestControls[0] = new LdapPagedResultsControl(pageSize, cookie);
                ldapSearchConstraints.setControls(requestControls);
                _ldapConnection.Constraints = ldapSearchConstraints;

                var res = _ldapConnection.Search(searchBase,
                                                 (int)scope, searchFilter, attributes, false, (LdapSearchConstraints)null);

                while (res.hasMore())
                {
                    LdapEntry nextEntry;
                    try
                    {
                        nextEntry = res.next();

                        if (nextEntry == null)
                        {
                            continue;
                        }
                    }
                    catch (LdapException ex)
                    {
                        if (ex is LdapReferralException)
                        {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(ex.Message) && ex.Message.Contains("Sizelimit Exceeded"))
                        {
                            break;
                        }

                        _log.ErrorFormat("SearchSimple({0}) error: {1}", searchFilter, ex);
                        continue;
                    }

                    _log.DebugFormat("{0}. DN: {1}", ++i, nextEntry.DN);

                    entries.Add(nextEntry);

                    if (string.IsNullOrEmpty(LdapUniqueIdAttribute))
                    {
                        LdapUniqueIdAttribute = GetLdapUniqueId(nextEntry);
                    }
                }

                // Server should send back a control irrespective of the
                // status of the search request
                var controls = res.ResponseControls;
                if (controls == null)
                {
                    _log.Debug("No controls returned");
                    cookie = null;
                }
                else
                {
                    // Multiple controls could have been returned
                    foreach (LdapControl control in controls)
                    {
                        /* Is this the LdapPagedResultsResponse control? */
                        if (!(control is LdapPagedResultsResponse))
                        {
                            continue;
                        }

                        var response = new LdapPagedResultsResponse(control.ID,
                                                                    control.Critical, control.getValue());

                        cookie = response.Cookie;
                    }
                }
                // if cookie is empty, we are done.
            } while (cookie != null && cookie.Length > 0);

            var result = entries.ToLdapObjects(LdapUniqueIdAttribute);

            return(result);
        }
Esempio n. 2
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 PGControl <host name> <login dn>" + " <password> <container> [ssl]");
            System.Console.Error.WriteLine("Example: mono PGControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\"");
            System.Console.Error.WriteLine("\tfor test over a secure connection add SSL argument");
            System.Console.Error.WriteLine("Example: mono PGControl Acme.com \"cn=admin,o=Acme\" secret" + " \"ou=Sales,o=Acme\" ssl");
            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];
        System.Boolean ssl        = false;

        if (args.Length == 5 && String.Equals(args[4], "ssl", StringComparison.OrdinalIgnoreCase))
        {
            ssl = true;
        }

        /*System.String LdapHost = "23.20.46.132";
         * System.String loginDN = "cn=read-only-admin, dc=example,dc=com";
         * System.String password = "******";
         * System.String searchBase = "dc=example,dc=com";*/

        /*System.String LdapHost = @"192.168.50.133";
         * System.String loginDN = @"*****@*****.**";
         * System.String password = @"admin1!";
         * System.String searchBase = @"dc=rem,dc=dev";*/

        int LdapPort = LdapConnection.DEFAULT_PORT;

        // If user asked for LDAPS, change the port
        if (ssl)
        {
            LdapPort = LdapConnection.DEFAULT_SSL_PORT;
        }

        int            LdapVersion = LdapConnection.Ldap_V3;
        LdapConnection conn        = new LdapConnection();

        try
        {
            // turn SSL on/off
            conn.SecureSocketLayer = ssl;
            // We don't require a valided SSL certificate to run the sample
            // If our certificated is not validated by a CA, we want to validate it ourselves.
            if (ssl)
            {
                conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidationCallback);
            }

            conn.Connect(LdapHost, LdapPort);
            // bind to the server
            conn.Bind(LdapVersion, loginDN, password);
            System.Console.Out.WriteLine("Successfully 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[3];
            attrs[0] = "givenName";
            attrs[1] = "cn";
            attrs[2] = "gidNumber";

            // We will be sending two controls to the server
            LdapSearchConstraints cons = conn.SearchConstraints;

            // hardcoded results page size
            int pageSize = 2;
            // initially, cookie must be set to an empty string
            System.String cookie = "";

            do
            {
                LdapControl[] requestControls = new LdapControl[1];
                requestControls[0] = new LdapPagedResultsControl(pageSize, cookie);
                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;
//						if (attrName != "cn")
//							continue;
//						System.Console.Out.Write("\t{0}: ", attrName);
                        System.Console.Out.Write("" + 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.Write(" = {0}; ", aVal);
                        }
                        System.Console.Out.WriteLine("");
                    }
                }

                // 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
                {
                    // Multiple controls could have been returned
                    foreach (LdapControl control in controls)
                    {
                        /* Is this the LdapPagedResultsResponse control? */
                        if (control is LdapPagedResultsResponse)
                        {
                            LdapPagedResultsResponse response = new LdapPagedResultsResponse(control.ID, control.Critical, control.getValue());

                            cookie = response.Cookie;

                            // Cookie is an opaque octet string. The chacters it contains might not be printable.
                            byte[]        hexCookie = System.Text.Encoding.ASCII.GetBytes(cookie);
                            StringBuilder hex       = new StringBuilder(hexCookie.Length);
                            foreach (byte b in hexCookie)
                            {
                                hex.AppendFormat("{0:x}", b);
                            }

                            System.Console.Out.WriteLine("Cookie: {0}", hex.ToString());
                            System.Console.Out.WriteLine("Size: {0}", response.Size);
                        }
                    }
                }
                // if cookie is empty, we are done.
            } while (!String.IsNullOrEmpty(cookie));

            /* 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);
        }
    }
Esempio n. 3
0
        /// <summary>
        /// Executes the paged search.
        /// </summary>
        /// <returns>The paged search.</returns>
        /// <param name="searchBase">Search base.</param>
        /// <param name="filter">Filter.</param>
        /// <param name="cookie">Cookie to restore last search.</param>
        public LdapPagedResponse ExecutePagedSearch(string searchBase, string filter, string cookie = "")
        {
            var results = new List <LdapEntry>();

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

            var sb = searchBase + config.searchBase;


            // 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 = 0;
            //int afterCount = config.maxResults -1;

            //System.String cookie = "";

            if (cookie != "")
            {
                byte[] data = System.Convert.FromBase64String(cookie);
                cookie = System.Text.Encoding.UTF8.GetString(data);
                //cookie = System.Text.ASCIIEncoding.ASCII.GetString(data);
            }


            requestControls[1] = new LdapPagedResultsControl(config.maxResults, cookie);

            // 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...");

            string[] attrs = null;

            ILdapSearchResults res = (LdapSearchResults)conn.Search(sb, LdapConnection.ScopeSub, 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();
                    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);
            }

            var response = new LdapPagedResponse {
                Entries = results
            };

            // Server should send back a control irrespective of the
            // status of the search request
            LdapControl[] controls = ((LdapSearchResults)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 LdapPagedResultsResponse)
                    {
                        logger.Debug("Received Ldap Paged Control from Server");

                        LdapPagedResultsResponse cresp = new LdapPagedResultsResponse(controls[i].Id, controls[i].Critical, controls[i].GetValue());

                        cookie = cresp.Cookie;



                        byte[] hexCookie = System.Text.Encoding.UTF8.GetBytes(cookie);
                        response.Cookie = Convert.ToBase64String(hexCookie);

                        /*
                         * // Cookie is an opaque octet string. The chacters it contains might not be printable.
                         * byte[] hexCookie = System.Text.Encoding.ASCII.GetBytes(cookie);
                         * StringBuilder hex = new StringBuilder(hexCookie.Length);
                         * foreach (byte b in hexCookie)
                         *  hex.AppendFormat("{0:x}", b);
                         *
                         * System.Console.Out.WriteLine("Cookie: {0}", hex.ToString());
                         * System.Console.Out.WriteLine("Size: {0}", cresp.Size);
                         */
                    }
                }
            }


            return(response);
        }
Esempio n. 4
0
        public List<ILdapUser> SearchUsersPaged(string filter)
        {

            var ldapUsers = new List<ILdapUser>();

            //Bind function with null user dn and password value will perform anonymous bind to LDAP server
            //First figure the user structure 

            try
            {

                GetConnection();

                // We will be sending two controls to the server 
                LdapSearchConstraints cons = _ldapConnection.SearchConstraints;

                // hardcoded results page size
                int pageSize = 500;
                // initially, cookie must be set to an empty string
                string cookie = "";

                do
                {
                    LdapControl[] requestControls = new LdapControl[1];
                    requestControls[0] = new LdapPagedResultsControl(pageSize, cookie);
                    cons.setControls(requestControls);
                    _ldapConnection.Constraints = cons;

                    // Send the search request - Synchronous Search is being used here 
                    //System.Console.Out.WriteLine("Calling Asynchronous Search...");
                    LdapSearchResults res = _ldapConnection.Search(_config.LdapBaseDn, LdapConnection.SCOPE_SUB, 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 user = null;
                        try
                        {
                            user = res.next();

                            if (user != null)
                            {
                                var appUser = new TUser();
                                appUser.SetBaseDetails(user, "local"); // Should we change to LDAP.
                                ldapUsers.Add(appUser);
                                
                            }
                        }
                        catch (LdapException e)
                        {
                            if (e is LdapReferralException)
                                continue;
                            else
                            {
                                //System.Console.Out.WriteLine("Search stopped with exception " + e.ToString());
                                break;
                            }
                        }
                        
                    }

                    // Server should send back a control irrespective of the 
                    // status of the search request
                    LdapControl[] controls = res.ResponseControls;
                    if (controls == null)
                    {
                        Console.Out.WriteLine("No controls returned");
                    }
                    else
                    {
                        // Multiple controls could have been returned
                        foreach (LdapControl control in controls)
                        {
                            /* Is this the LdapPagedResultsResponse control? */
                            if (control is LdapPagedResultsResponse)
                            {
                                LdapPagedResultsResponse response = new LdapPagedResultsResponse(control.ID, control.Critical, control.getValue());

                                cookie = response.Cookie;

                            }
                        }
                    }
                    // if cookie is empty, we are done.
                } while (!String.IsNullOrEmpty(cookie));

                /* We are done - disconnect */
                if (_ldapConnection.Connected)
                    _ldapConnection.Disconnect();
            }
            catch (LdapException e)
            {
                //Console.Out.WriteLine(e.ToString());
                _logger.LogError($"[LdapService] => {e.ToString()}");
            }
            catch (System.IO.IOException e)
            {
                //Console.Out.WriteLine("Error: " + e.ToString());
                _logger.LogError($"[LdapService] => {e.ToString()}");
            }
            catch (Exception e)
            {
                //Console.WriteLine("Error: " + e.Message);
                _logger.LogError($"[LdapService] => {e.Message}");
            }
            
            return ldapUsers;
        }