Exemplo n.º 1
0
        internal static SearchResultEntry GetSingleResponse(string dn, string filter, SearchScope scope, string[] attrsToReturn, bool useGC)
        {
            var connection = useGC ? ConnectGCLDAP() : ConnectLDAP();

            var request = new SearchRequest(dn, filter, scope);//, attrsToReturn);

            // the size of each page
            var pageReqControl = new PageResultRequestControl(500);

            // turn off referral chasing so that data
            // from other partitions is not returned

            var searchControl = new SearchOptionsControl(SearchOption.DomainScope);

            //Unhandled Exception: System.ComponentModel.InvalidEnumArgumentException:
            //The value of argument 'value' (0) is invalid for Enum type 'SearchOption'.
            //var searchControl = new SearchOptionsControl();

            request.Controls.Add(pageReqControl);
            request.Controls.Add(searchControl);
            try
            {
                var response = (SearchResponse)connection.SendRequest(request);

                if (response.Entries.Count == 0)
                {
                    return(null);
                }

                return(response.Entries[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
            finally
            {
                if (useGC)
                {
                    connection.Dispose();
                }
            }
        }
Exemplo n.º 2
0
 public virtual IEnumerable <ExSearchResultEntry> PagedScan(string absolutePath, string query, System.DirectoryServices.Protocols.SearchScope scope, params string[] attributes)
 {
     byte[] lastPageCookie = null;
     if (string.IsNullOrEmpty(absolutePath))
     {
         absolutePath = this.GetTargetBaseSearchPath();
     }
     do
     {
         SearchRequest request = new SearchRequest(absolutePath, query, scope, attributes);
         request.Attributes.Add("objectClass");
         PageResultRequestControl pageControl = (lastPageCookie == null) ? new PageResultRequestControl() : new PageResultRequestControl(lastPageCookie);
         pageControl.PageSize   = 1000;
         pageControl.IsCritical = false;
         request.Controls.Add(pageControl);
         SearchResponse response;
         try
         {
             response = (SearchResponse)this.SendRequest(request);
         }
         catch (ExDirectoryException ex)
         {
             if (ex.ResultCode == ResultCode.NoSuchObject)
             {
                 yield break;
             }
             throw;
         }
         foreach (object obj in response.Entries)
         {
             SearchResultEntry resultEntry = (SearchResultEntry)obj;
             yield return(new ExSearchResultEntry(resultEntry));
         }
         if (response.Controls.Length == 0)
         {
             break;
         }
         PageResultResponseControl pagedResponse = (PageResultResponseControl)response.Controls[0];
         lastPageCookie = pagedResponse.Cookie;
     }while (lastPageCookie != null && lastPageCookie.Length != 0);
     yield break;
 }
Exemplo n.º 3
0
        public virtual List <LdapUser> GetUsersByLdapFilter(string filter)
        {
            var usersList = new List <LdapUser>();

            string[] userAttributes         = GetUserAttributes();
            string[] userRequiredAttributes = GetUserRequiredAttributes();
            var      request = new SearchRequest(_ldapUsersEntry, filter, SearchScope.Subtree, userAttributes);
            PageResultRequestControl paging = CreatePageResultRequestControl();

            request.Controls.Add(paging);
            SortRequestControl sortControl = CreateSortRequestControl(_ldapUserLoginAttribute);

            request.Controls.Add(sortControl);
            do
            {
                SearchResponse response;
                try {
                    response = _ldapConnection.SendRequest(request, RequestTimeout) as SearchResponse;
                } catch (Exception exception) {
                    LogLdapRequestError(exception, request);
                    throw;
                }
                if (response.ResultCode == ResultCode.Success)
                {
                    foreach (SearchResultEntry entry in response.Entries)
                    {
                        CheckEntryAttributes(entry, userRequiredAttributes);
                        LdapUser ldapUser = CreateLdapUser(entry, null);
                        usersList.Add(ldapUser);
                    }
                }
                else
                {
                    _log.DebugFormat("Unable to obtain a list of users with the \"{0}\" filter. Result code: {1}. Error: {2}",
                                     filter, response.ResultCode, response.ErrorMessage ?? string.Empty);
                }
                var responseControl = (PageResultResponseControl)Array.Find(response.Controls,
                                                                            item => item is PageResultResponseControl);
                paging.Cookie = responseControl.Cookie;
            } while (paging.Cookie.Length != 0);
            return(usersList);
        }
Exemplo n.º 4
0
 public virtual IEnumerable <ExSearchResultEntry> PagedScan(string baseDN, string query, SearchScope scope, params string[] attributes)
 {
     byte[] lastPageCookie = null;
     do
     {
         SearchRequest request = new SearchRequest(baseDN, query, scope, attributes);
         request.Attributes.Add("objectClass");
         PageResultRequestControl pageControl = (lastPageCookie == null) ? new PageResultRequestControl() : new PageResultRequestControl(lastPageCookie);
         pageControl.PageSize   = 1000;
         pageControl.IsCritical = false;
         request.Controls.Add(pageControl);
         request.TimeLimit       = Connection.DefaultSearchRequestTimeout;
         this.connection.Timeout = request.TimeLimit + Connection.ConnectionTimeoutPadding;
         SearchResponse response;
         try
         {
             response = (SearchResponse)this.SendRequest(request);
         }
         catch (ExDirectoryException ex)
         {
             if (ex.ResultCode == ResultCode.NoSuchObject)
             {
                 yield break;
             }
             throw;
         }
         foreach (object obj in response.Entries)
         {
             SearchResultEntry resultEntry = (SearchResultEntry)obj;
             yield return(new ExSearchResultEntry(resultEntry));
         }
         if (response.Controls.Length == 0)
         {
             break;
         }
         PageResultResponseControl pagedResponse = (PageResultResponseControl)response.Controls[0];
         lastPageCookie = pagedResponse.Cookie;
     }while (lastPageCookie != null && lastPageCookie.Length != 0);
     yield break;
 }
Exemplo n.º 5
0
            public Guid BeginPagedSearch(
                string baseDN,
                string filter,
                string[] attribs,
                int pageSize
                )
            {
                Guid guid = Guid.NewGuid();

                SearchRequest request = new SearchRequest(
                    baseDN,
                    filter,
                    System.DirectoryServices.Protocols.SearchScope.Subtree,
                    attribs
                    );

                PageResultRequestControl prc = new PageResultRequestControl(pageSize);

                //add the paging control
                request.Controls.Add(prc);

                //we will use this to distinguish multiple searches.
                request.RequestId = guid.ToString();

                //create a temporary placeholder for the results
                _results.Add(request.RequestId, new List <SearchResultEntry>());

                //kick off async
                IAsyncResult result = this._connect.BeginSendRequest(
                    request,
                    PartialResultProcessing.NoPartialResultSupport,
                    new AsyncCallback(InternalCallback),
                    request
                    );

                return(guid);
            }
Exemplo n.º 6
0
        public IEnumerable <SearchResultEntryCollection> PagedSearch(
            string searchFilter,
            string[] attributesToLoad)
        {
            var pagedResults = new List <SearchResultEntryCollection>();

            var searchRequest = new SearchRequest
                                    (searchBaseDN,
                                    searchFilter,
                                    SearchScope.Subtree,
                                    attributesToLoad);


            var searchOptions = new SearchOptionsControl(SearchOption.DomainScope);

            searchRequest.Controls.Add(searchOptions);

            var pageResultRequestControl = new PageResultRequestControl(pageSize);

            searchRequest.Controls.Add(pageResultRequestControl);

            while (true)
            {
                var searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
                var pageResponse   = (PageResultResponseControl)searchResponse.Controls[0];

                yield return(searchResponse.Entries);

                if (pageResponse.Cookie.Length == 0)
                {
                    break;
                }

                pageResultRequestControl.Cookie = pageResponse.Cookie;
            }
        }
Exemplo n.º 7
0
        public IEnumerable <Wrapper <SearchResultEntry> > DoWrappedSearch(string filter, SearchScope scope, string[] props,
                                                                          string domainName = null, string adsPath = null, bool useGc = false)
        {
            var conn = useGc ? GetGcConnection(domainName) : GetLdapConnection(domainName);

            if (conn == null)
            {
                Verbose("Unable to contact LDAP");
                yield break;
            }
            var request = GetSearchRequest(filter, scope, props, domainName, adsPath);

            if (request == null)
            {
                Verbose($"Unable to contact domain {domainName}");
                yield break;
            }

            var prc = new PageResultRequestControl(500);

            request.Controls.Add(prc);

            if (IsMethodSet(ResolvedCollectionMethod.ACL))
            {
                var sdfc =
                    new SecurityDescriptorFlagControl {
                    SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
                };
                request.Controls.Add(sdfc);
            }

            PageResultResponseControl pageResponse = null;

            while (true)
            {
                SearchResponse response;
                try
                {
                    response = (SearchResponse)conn.SendRequest(request);
                    if (response != null)
                    {
                        pageResponse = (PageResultResponseControl)response.Controls[0];
                    }
                }
                catch (Exception e)
                {
                    Debug("Exception in Domain Searcher.");
                    Debug(e.Message);
                    yield break;
                }
                if (response == null || pageResponse == null)
                {
                    continue;
                }
                foreach (SearchResultEntry entry in response.Entries)
                {
                    yield return(new Wrapper <SearchResultEntry> {
                        Item = entry
                    });
                }

                if (pageResponse.Cookie.Length == 0)
                {
                    break;
                }

                prc.Cookie = pageResponse.Cookie;
            }
        }
Exemplo n.º 8
0
        static void DoPagedSearch()
        {
            Console.WriteLine("\r\nDoing a paged search ...");

            string ldapSearchFilter = "(&(objectClass=organizationalUnit)" +
                                      "(ou=object*))";

            // return only these attributes
            string[] attributesToReturn = new string[] {
                "description",
                "ou",
                "objectClass"
            };

            PageResultRequestControl pageRequestControl =
                new PageResultRequestControl(pageSize);

            // used to retrieve the cookie to send for the subsequent request
            PageResultResponseControl pageResponseControl;
            SearchResponse            searchResponse;

            // create a search request: specify baseDn, ldap search filter,
            // attributes to return and scope of the search
            SearchRequest searchRequest = new SearchRequest(
                targetOU,
                ldapSearchFilter,
                SearchScope.Subtree,
                attributesToReturn
                );

            // attach a page request control to retrieve the results in small chunks
            searchRequest.Controls.Add(pageRequestControl);


            // The cookie returned by the page-result response control is
            // valid on the same LDAP connection that DSML server uses,
            // therefore we want DSML server to hold on to that same connection
            // for the subsequent SendRequest calls. This is achived by initiating
            // a session on the DsmlSoapHttpConnection
            Console.WriteLine("Initiating a session with the DSML server...");
            dsmlConnection.BeginSession();
            Console.WriteLine("SessionId=" + dsmlConnection.SessionId);

            int pageCount = 0;
            int count;

            // search in a loop untill there is no more page to retrieve
            while (true)
            {
                pageCount++;

                searchResponse = (SearchResponse)dsmlConnection.SendRequest(searchRequest);
                Console.WriteLine("\r\nPage" + pageCount + ": " +
                                  searchResponse.Entries.Count +
                                  " entries:");

                // print the entries in this page
                count = 0;
                foreach (SearchResultEntry entry in searchResponse.Entries)
                {
                    Console.WriteLine(++count + ":" + entry.DistinguishedName);
                }


                // retrieve the cookie
                if (searchResponse.Controls.Length != 1 ||
                    !(searchResponse.Controls[0] is PageResultResponseControl)
                    )
                {
                    Console.WriteLine("The server did not return " +
                                      "a PageResultResponseControl as expected.");
                    return;
                }

                pageResponseControl = (PageResultResponseControl)searchResponse.Controls[0];

                // if responseControl.Cookie.Length is 0 then there
                // is no more page to retrieve so break the loop
                if (pageResponseControl.Cookie.Length == 0)
                {
                    break;
                }

                // set the cookie from the response control to retrieve the next page
                pageRequestControl.Cookie = pageResponseControl.Cookie;
            }

            Console.WriteLine("\r\nClosing the session with the DSML server.");
            dsmlConnection.EndSession();

            Console.WriteLine("\r\nPaged search is completed successfully.\r\n");
        }
Exemplo n.º 9
0
        public IEnumerable <LdapObject> Search(string distinguishedName, string searchFilter, SearchScope searchScope, params string[] attributes)
        {
            var con = Connect();

            //var baseDN = !String.IsNullOrEmpty(Options.BindBaseDN) ? Options.BindBaseDN : GetDefaultNamingContext();

            if (attributes.Any())
            {
                var attrList = new List <string>()
                {
                    "distinguishedName",
                    "objectClass"
                };
                attrList.AddRange(attributes.Where(att => att != "distinguishedName"));
                attributes = attrList.ToArray();
            }

            List <SearchResponse> result   = new List <SearchResponse>();
            SearchResponse        response = null;
            int maxResultsToRequest        = 1000;

            if (Options.SearchPageSize.HasValue && Options.SearchPageSize > 0)
            {
                maxResultsToRequest = Options.SearchPageSize.Value;
            }

            PageResultRequestControl pageRequestControl = new PageResultRequestControl(maxResultsToRequest);

            // used to retrieve the cookie to send for the subsequent request
            PageResultResponseControl pageResponseControl;
            SearchRequest             searchRequest = new SearchRequest(distinguishedName, searchFilter, searchScope, attributes);

            searchRequest.Controls.Add(pageRequestControl);

            while (true)
            {
                response = (SearchResponse)con.SendRequest(searchRequest);
                SearchResultEntryCollection entries = response.Entries;
                for (int i = 0; i < entries.Count; i++)//Iterate through the results
                {
                    var dict = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
                    SearchResultEntry     entry      = entries[i];
                    IDictionaryEnumerator attribEnum = entry.Attributes.GetEnumerator();
                    while (attribEnum.MoveNext())//Iterate through the result attributes
                    {
                        //Attributes have one or more values so we iterate through all the values
                        //for each attribute
                        DirectoryAttribute subAttrib = (DirectoryAttribute)attribEnum.Value;

                        var val = TypeMapper.GetAttributeValue(subAttrib);
                        dict.Add(subAttrib.Name, val);
                    }

                    yield return(new LdapObject(dict));
                }
                result.Add(response);
                pageResponseControl = (PageResultResponseControl)response.Controls[0];
                if (pageResponseControl.Cookie.Length == 0)
                {
                    break;
                }
                pageRequestControl.Cookie = pageResponseControl.Cookie;
            }
        }
Exemplo n.º 10
0
        public override object Execute(DirectoryConnection connection, SearchScope scope, int maxPageSize, bool pagingEnabled, ILinqToLdapLogger log = null, string namingContext = null)
        {
            if (Options.YieldNoResults)
            {
                return(0);
            }

            SetDistinguishedName(namingContext);
            SearchRequest.Scope = scope;

            int index = -1;

            if (pagingEnabled && !Options.WithoutPaging)
            {
                var pagedRequest = GetControl <PageResultRequestControl>(SearchRequest.Controls);
                if (pagedRequest != null)
                {
                    index = SearchRequest.Controls.IndexOf(pagedRequest);
                }

                if (pagedRequest == null)
                {
                    pagedRequest = new PageResultRequestControl(maxPageSize);
                    index        = SearchRequest.Controls.Add(pagedRequest);
                }
            }

            SearchRequest.TypesOnly = true;
            SearchRequest.Attributes.Add("distinguishedname");

            if (log != null && log.TraceEnabled)
            {
                log.Trace(SearchRequest.ToLogString());
            }
            var response = connection.SendRequest(SearchRequest) as SearchResponse;

            response.AssertSuccess();

            int count = response.Entries.Count;

            if (pagingEnabled && !Options.WithoutPaging)
            {
                var  pageResultResponseControl = GetControl <PageResultResponseControl>(response.Controls);
                bool hasResults = pageResultResponseControl != null && pageResultResponseControl.Cookie.Length > 0;
                while (hasResults)
                {
                    SearchRequest.Controls[index] = new PageResultRequestControl(pageResultResponseControl.Cookie);

                    if (log != null && log.TraceEnabled)
                    {
                        log.Trace(SearchRequest.ToLogString());
                    }
                    response = connection.SendRequest(SearchRequest) as SearchResponse;
                    response.AssertSuccess();
                    pageResultResponseControl = GetControl <PageResultResponseControl>(response.Controls);
                    hasResults = pageResultResponseControl != null && pageResultResponseControl.Cookie.Length > 0;
                    count     += response.Entries.Count;
                }
            }

            if (Options.IsLongCount)
            {
                return((long)count);
            }

            return(count);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Performs LDAP Search and extracts attributes.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="CurrentTime">Locked program timestamp value</param>
        private void ExtractLDAPResults(LogHelper logger, DateTime CurrentTime)
        {
            List <string> AttributesToAdd = new List <string>();

            foreach (PropertyBase item in this.Properties)
            {
                AttributesToAdd.Add(item.Mapping);
            }

            string[] _attrs = AttributesToAdd.ToArray();

            String sFilter = SetQueryFilter(this.BatchAction, CurrentTime);

            SearchRequest searchRequest = new SearchRequest(this.SearchRoot, sFilter, SearchScope.Subtree, _attrs);

            PageResultRequestControl PageResponse  = new PageResultRequestControl(this.PageSize);
            SearchOptionsControl     SearchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);

            searchRequest.Controls.Add(PageResponse);
            searchRequest.Controls.Add(SearchOptions);

            logger.LogVerbose(string.Format("Establishing LDAP Connection to: {0}", this.ServerName));

            using (LdapConnection connection = CreateLDAPConnection())
            {
                logger.LogVerbose(string.Format("Performing a {0} operation with filter: {1}", this.BatchAction, sFilter));

                while (true)
                {
                    SearchResponse response = null;

                    try
                    {
                        response = connection.SendRequest(searchRequest) as SearchResponse;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("An error occurred whilst creating the SearchResponse", ex);
                    }

                    int ResponseCount = response.Entries.Count;
                    int CurrentBatchSize;

                    if (ResponseCount != this.PageSize)
                    {
                        CurrentBatchSize = ResponseCount;
                    }
                    else
                    {
                        CurrentBatchSize = this.PageSize;
                    }

                    string FilePath = CSVCreateFile(this.CSVDirectoryLocation, _TotalUsers, CurrentBatchSize);


                    foreach (DirectoryControl control in response.Controls)
                    {
                        if (control is PageResultResponseControl)
                        {
                            PageResponse.Cookie = ((PageResultResponseControl)control).Cookie;
                            break;
                        }
                    }

                    // Create CSV file for current batch of users
                    using (CSVWriter BatchFile = new CSVWriter(FilePath))
                    {
                        // Create column headings for CSV file
                        CSVUserEntry heading = new CSVUserEntry();

                        // Iterate over attribute headings
                        foreach (PropertyBase item in this.Properties)
                        {
                            heading.Add(item.Name);
                        }

                        BatchFile.CSVWriteUser(heading, logger);

                        // Create new CSV row for each user
                        foreach (SearchResultEntry sre in response.Entries)
                        {
                            // Placeholder for CSV entry of current user
                            CSVUserEntry user = new CSVUserEntry();

                            // Exract each user attribute specified in XML file
                            foreach (PropertyBase item in this.Properties)
                            {
                                try
                                {
                                    DirectoryAttribute attr  = sre.Attributes[item.Mapping];
                                    string             value = string.Empty;
                                    if (null != attr && attr.Count > 0)
                                    {
                                        value = attr[0].ToString();
                                    }

                                    if (item.Index == this.UserNameIndex)
                                    {
                                        user.Add(CreateUserAccountName(value, attr));
                                    }
                                    else
                                    {
                                        user.Add(value);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (logger != null)
                                    {
                                        logger.LogException(string.Empty, ex);
                                        _TotalFailures++;
                                    }
                                }
                            }

                            // Write current user to CSV file
                            BatchFile.CSVWriteUser(user, logger);

                            // Increment user count value
                            _TotalUsers++;
                        }
                    }

                    logger.LogVerbose(string.Format("Successfully extracted {0} users to {1} - the total user count is: {2}", CurrentBatchSize, FilePath, _TotalUsers));

                    if (PageResponse.Cookie.Length == 0)
                    {
                        break;
                    }
                }
            }
        }
Exemplo n.º 12
0
        public static void GetResponse(LdapConnection conn,
                                       string filter,
                                       SearchScope scope,
                                       string[] attrsToReturn,
                                       string dn,
                                       string printOption = null,
                                       string spnName     = null)
        //Dictionary<string, string> myNames = null)
        {
            var request = new SearchRequest(dn, filter, scope, attrsToReturn);

            // the size of each page
            var pageReqControl = new PageResultRequestControl(500);

            // turn off referral chasing so that data
            // from other partitions is not returned

            //var searchControl = new SearchOptionsControl(SearchOption.DomainScope);
            //Unhandled Exception: System.ComponentModel.InvalidEnumArgumentException:
            //The value of argument 'value' (0) is invalid for Enum type 'SearchOption'.
            var searchControl = new SearchOptionsControl();

            request.Controls.Add(pageReqControl);
            request.Controls.Add(searchControl);


            SearchResponse            response;
            PageResultResponseControl pageResControl;

            // loop through each page
            while (true)
            {
                try
                {
                    response = (SearchResponse)conn.SendRequest(request);

                    if (response.Controls.Length != 1 || !(response.Controls[0] is PageResultResponseControl))
                    {
                        Console.WriteLine("The server does not support this advanced search operation");
                        return;
                    }
                    pageResControl = (PageResultResponseControl)response.Controls[0];

                    //Console.WriteLine("\nThis page contains {0} response entries:\n", response.Entries.Count);

                    switch (printOption)
                    {
                    //if there's only one attribute needs to be returned
                    //and this attribute is a single-valued attribute
                    case "single":
                        Outputs.PrintSingle(response, attrsToReturn[0]);
                        break;

                    //if there's only one attribute needs to be returned
                    //and this attribute is a multi-valued attribute
                    case "multi":
                        Outputs.PrintMulti(response, attrsToReturn[0]);
                        break;

                    ////Use specified name paris
                    //case "mynames":
                    //Outputs.PrintMyName(response, myNames);
                    //break;

                    case "gpo":
                        Outputs.PrintGPO(response);
                        break;

                    case "spn":
                        Outputs.PrintSPNs(response, spnName);
                        break;

                    case "domain":
                        Outputs.PrintDomainAttrs(response);
                        break;

                    //case "attrname":
                    //Outputs.PrintAttrName(response);
                    //break;

                    //default: print all attributesToReturned
                    default:
                        Outputs.PrintAll(response);
                        break;
                    }


                    if (pageResControl.Cookie.Length == 0)
                    {
                        break;
                    }

                    pageReqControl.Cookie = pageResControl.Cookie;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected error:  {0}", e.Message);
                    break;
                }
            }
        }
Exemplo n.º 13
0
 public override object HandlePagedRequest(DirectoryConnection connection, PageResultRequestControl pageRequest, ILinqToLdapLogger log)
 {
     HandlePagedRequestCalled = true;
     return(_enablePagedRequestCall ? base.HandlePagedRequest(connection, pageRequest, log) : null);
 }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Console.Error.WriteLine("ShowAdCerts v1.0, (c) 2012 Zetetic LLC");

            if (args.Length == 1 && args[0].EndsWith("?"))
            {
                Console.Error.WriteLine(@"Switches (all are optional): 

-h  host or domain name (default = default logon server)
-f  ldap filter         (default = userCertificate=*   )
-b  search base         (default = domain root NC      )
-v  (turn on cert validation of non-expired certs      )
-r  (dump raw cert data                                )
");

                System.Environment.ExitCode = 1;
                return;
            }

            string searchbase = null, filter = "(&(userCertificate=*))", host = "";
            bool   validate = false, raw = false;

            try
            {
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-h":
                        host = args[++i];
                        break;

                    case "-r":
                        raw = true;
                        break;

                    case "-f":
                        filter = args[++i];
                        switch (filter.ToLowerInvariant())
                        {
                        case "computer":
                            filter = "(&(userCertificate=*)(objectCategory=computer))";
                            break;

                        case "user":
                        case "person":
                            filter = "(&(userCertificate=*)(objectCategory=person))";
                            break;
                        }
                        break;

                    case "-b":
                        searchbase = args[++i];
                        break;

                    case "-v":
                        validate = true;
                        break;

                    default:
                        Console.Error.WriteLine("Unknown argument {0}", args[i]);
                        break;
                    }
                }

                using (var conn = new LdapConnection(host))
                {
                    conn.SessionOptions.ProtocolVersion = 3;

                    if (string.IsNullOrEmpty(searchbase))
                    {
                        var e = ((SearchResponse)conn.SendRequest(new SearchRequest(
                                                                      "",
                                                                      "(&(objectClass=*))",
                                                                      SearchScope.Base,
                                                                      "defaultNamingContext"))).Entries[0];

                        searchbase = e.Attributes["defaultNamingContext"][0].ToString();
                    }

                    var srch  = new SearchRequest(searchbase, filter, SearchScope.Subtree, "userCertificate");
                    var pager = new PageResultRequestControl();
                    srch.Controls.Add(pager);

                    int count = 0;

                    while (true)
                    {
                        var resp = (SearchResponse)conn.SendRequest(srch);

                        foreach (SearchResultEntry se in resp.Entries)
                        {
                            if (!se.Attributes.Contains("userCertificate"))
                            {
                                continue;
                            }

                            Console.WriteLine("# {0}", ++count);
                            Console.WriteLine("dn: {0}", se.DistinguishedName);

                            foreach (var o in se.Attributes["userCertificate"].GetValues(typeof(byte[])))
                            {
                                byte[] bytes = (byte[])o;

                                try
                                {
                                    X509Certificate2 cert = new X509Certificate2(bytes);

                                    Console.WriteLine("subject: {0}", string.IsNullOrEmpty(cert.Subject) ? cert.SubjectName.Name : cert.Subject);
                                    Console.WriteLine("issuer: {0}", cert.Issuer);
                                    Console.WriteLine("thumbprint: {0}", cert.Thumbprint);
                                    Console.WriteLine("serial: {0}", cert.SerialNumber);

                                    var estr    = cert.GetExpirationDateString();
                                    var expired = false;

                                    if (!string.IsNullOrEmpty(estr))
                                    {
                                        Console.WriteLine("exp: {0}", estr);
                                        DateTime dt;

                                        if (DateTime.TryParse(estr, out dt) && dt < DateTime.Now)
                                        {
                                            Console.WriteLine("expired: TRUE");
                                            expired = true;
                                        }
                                    }

                                    if (validate && !expired)
                                    {
                                        Console.WriteLine("valid: {0}", cert.Verify().ToString().ToUpperInvariant());
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("exception: {0}, {1}", e.GetType(), e.Message);
                                }

                                if (raw)
                                {
                                    var s = Convert.ToBase64String(bytes);

                                    Console.WriteLine("-----BEGIN CERTIFICATE-----");

                                    for (int i = 0; i < s.Length; i += 78)
                                    {
                                        Console.WriteLine(s.Substring(i, Math.Min(78, s.Length - i)));
                                    }

                                    Console.WriteLine("-----END CERTIFICATE-----");
                                }

                                Console.WriteLine("-");
                            }
                            Console.WriteLine("");
                        }

                        var rc = resp.Controls.SingleOrDefault(t => t is PageResultResponseControl) as PageResultResponseControl;

                        if (rc == null || rc.Cookie == null || rc.Cookie.Length == 0)
                        {
                            break;
                        }

                        pager.Cookie = rc.Cookie;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error type = {0}, message = {1}, stack = {2}", e.GetType(), e.Message, e.StackTrace);

                System.Environment.ExitCode = 2;
            }
        }
Exemplo n.º 15
0
        public virtual async System.Threading.Tasks.Task <object> HandlePagedRequestAsync(LdapConnection connection, PageResultRequestControl pageRequest, ILinqToLdapLogger log)
        {
            if (Options.YieldNoResults)
            {
                var bindingAttr = new[]
                {
                    pageRequest.PageSize,
                    null,
                    Options.GetEnumerator(),
                    null
                };

                return(ObjectActivator.CreateGenericInstance(typeof(LdapPage <>), Options.GetEnumeratorReturnType(), bindingAttr, null));
            }

            if (pageRequest == null)
            {
                pageRequest = new PageResultRequestControl(Options.PagingOptions.PageSize)
                {
                    Cookie = Options.PagingOptions.NextPage
                };

                SearchRequest.Controls.Add(pageRequest);
            }

            if (log != null && log.TraceEnabled)
            {
                log.Trace(SearchRequest.ToLogString());
            }

#if NET45
            return(await System.Threading.Tasks.Task.Factory.FromAsync(
                       (callback, state) =>
            {
                return connection.BeginSendRequest(SearchRequest, Options.AsyncProcessing, callback, state);
            },
                       (asyncresult) =>
            {
                var response = (SearchResponse)connection.EndSendRequest(asyncresult);
                response.AssertSuccess();
                AssertSortSuccess(response.Controls);

                var enumerator = Options.GetEnumerator(response.Entries);
                var nextPage = GetControl <PageResultResponseControl>(response.Controls);
                var parameters = new[]
                {
                    pageRequest.PageSize,
                    nextPage?.Cookie,
                    enumerator,
                    Options.Filter
                };

                return ObjectActivator.CreateGenericInstance(typeof(LdapPage <>), Options.GetEnumeratorReturnType(), parameters, null);
            },
                       null
                       ).ConfigureAwait(false));
#else
            var response = await System.Threading.Tasks.Task.Run(() => connection.SendRequest(SearchRequest) as SearchResponse).ConfigureAwait(false);

            response.AssertSuccess();
            AssertSortSuccess(response.Controls);

            var enumerator = Options.GetEnumerator(response.Entries);
            var nextPage   = GetControl <PageResultResponseControl>(response.Controls);
            var parameters = new[]
            {
                pageRequest.PageSize,
                nextPage?.Cookie,
                enumerator,
                Options.Filter
            };

            return(ObjectActivator.CreateGenericInstance(typeof(LdapPage <>), Options.GetEnumeratorReturnType(), parameters, null));
#endif
        }
Exemplo n.º 16
0
        internal IEnumerable <string> GetUserList()
        {
            var conn = GetConnection();

            if (conn == null)
            {
                yield break;
            }

            using (conn)
            {
                var request = GetRequest();

                if (request == null)
                {
                    Console.WriteLine("Unable to contact domain");
                    yield break;
                }

                var prc = new PageResultRequestControl(500);
                request.Controls.Add(prc);
                PageResultResponseControl pr = null;

                while (true)
                {
                    SearchResponse response;
                    try
                    {
                        response = (SearchResponse)conn.SendRequest(request);
                        if (response != null)
                        {
                            pr = (PageResultResponseControl)response.Controls[0];
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        yield break;
                    }

                    if (response == null || pr == null)
                    {
                        continue;
                    }

                    foreach (SearchResultEntry entry in response.Entries)
                    {
                        var bp = entry.GetProp("badpwdcount");
                        if (int.TryParse(bp, out var badpwdcount) || bp == null)
                        {
                            var user = entry.GetProp("samaccountname");
                            if (badpwdcount < _options.Lockout - 2 && user != null)
                            {
                                yield return(user);
                            }
                            else
                            {
                                if (_options.Verbose)
                                {
                                    Console.WriteLine($"Skipping {user} due to badpwdcount");
                                }
                            }
                        }
                    }

                    if (pr.Cookie.Length == 0)
                    {
                        yield break;
                    }

                    prc.Cookie = pr.Cookie;
                }
            }
        }
Exemplo n.º 17
0
        public IEnumerable <SearchResultEntry> DoSearch(string filter, SearchScope scope, string[] props,
                                                        string domainName = null, string adsPath = null, bool useGc = false)
        {
            using (var conn = useGc ? GetGcConnection() : GetLdapConnection(domainName))
            {
                if (conn == null)
                {
                    yield break;
                }
                var request = GetSearchRequest(filter, scope, props, domainName, adsPath);

                if (request == null)
                {
                    Verbose($"Unable to contact domain {domainName}");
                    yield break;
                }

                var prc = new PageResultRequestControl(500);
                request.Controls.Add(prc);

                if (_options.CollectMethod.Equals(CollectionMethod.ACL))
                {
                    var sdfc =
                        new SecurityDescriptorFlagControl {
                        SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
                    };
                    request.Controls.Add(sdfc);
                }

                PageResultResponseControl pageResponse = null;
                while (true)
                {
                    SearchResponse response;
                    try
                    {
                        response = (SearchResponse)conn.SendRequest(request);
                        if (response != null)
                        {
                            pageResponse = (PageResultResponseControl)response.Controls[0];
                        }
                    }
                    catch
                    {
                        yield break;
                    }
                    if (response == null || pageResponse == null)
                    {
                        continue;
                    }
                    foreach (SearchResultEntry entry in response.Entries)
                    {
                        yield return(entry);
                    }

                    if (pageResponse.Cookie.Length == 0 || response.Entries.Count == 0)
                    {
                        yield break;
                    }

                    prc.Cookie = pageResponse.Cookie;
                }
            }
        }
Exemplo n.º 18
0
        public IEnumerable <SearchResultEntry> DoSearch(string filter, SearchScope scope, string[] props,
                                                        string domainName = null, string adsPath = null, bool useGc = false)
        {
            Debug("Creating connection");
            var conn = useGc ? GetGcConnection(domainName) : GetLdapConnection(domainName);

            if (conn == null)
            {
                Debug("Connection null");
                yield break;
            }
            Debug("Getting search request");
            var request = GetSearchRequest(filter, scope, props, domainName, adsPath);

            if (request == null)
            {
                Debug($"Unable to contact domain {domainName}");
                Verbose($"Unable to contact domain {domainName}");
                yield break;
            }

            Debug("Creating page control");
            var prc = new PageResultRequestControl(500);

            request.Controls.Add(prc);

            if (IsMethodSet(ResolvedCollectionMethod.ACL))
            {
                var sdfc =
                    new SecurityDescriptorFlagControl {
                    SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
                };
                request.Controls.Add(sdfc);
            }

            PageResultResponseControl pageResponse = null;

            Debug("Starting loop");
            while (true)
            {
                SearchResponse response;
                try
                {
                    response = (SearchResponse)conn.SendRequest(request);
                    if (response != null)
                    {
                        pageResponse = (PageResultResponseControl)response.Controls[0];
                    }
                }
                catch (Exception e)
                {
                    Debug("Error in loop");
                    Debug(e.Message);
                    yield break;
                }
                if (response == null || pageResponse == null)
                {
                    continue;
                }
                foreach (SearchResultEntry entry in response.Entries)
                {
                    yield return(entry);
                }

                if (pageResponse.Cookie.Length == 0 || response.Entries.Count == 0)
                {
                    Debug("Loop finished");
                    yield break;
                }

                prc.Cookie = pageResponse.Cookie;
            }
        }
Exemplo n.º 19
0
        private IDictionary <string, AccountStatus> PagedSearch(string afilter)
        {
            // read data from LDAP
            PageResultRequestControl pageRequestControl = new PageResultRequestControl(5);
            // for some reason without setting this search option
            // paged search doesn't work for domain root base name
            // (probably caused by incompatible referral settings
            // so this is no longer necessary with "External" referral
            //SearchOptionsControl searchOptions =
            //    new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);
            // with following option we could technically track also deleted
            // objects that are currently updated only by full search in AD,
            // but that requires special persmissions (administrator?) and
            // additional code to deal with history of objects with same name
            //ShowDeletedControl showDeleted = new ShowDeletedControl();

            SearchRequest request = new SearchRequest();

            request.Attributes.Add("cn");
            request.Attributes.Add("userAccountControl");
            //request.Attributes.Add("isDeleted");
            request.Controls.Add(pageRequestControl);
            //request.Controls.Add(searchOptions);
            //request.Controls.Add(showDeleted);
            request.DistinguishedName = sbase;
            request.Filter            = afilter;
            request.Scope             = System.DirectoryServices.Protocols.SearchScope.Subtree;

            Dictionary <string, AccountStatus> ret = new Dictionary <string, AccountStatus>();
            SearchResponse response;

            while (true)
            {
                response = (SearchResponse)con.SendRequest(request);

                foreach (SearchResultEntry entry in response.Entries)
                {
                    string user = (string)entry.Attributes["cn"][0];
                    Int32  uac  = Int32.Parse((string)entry.Attributes["userAccountControl"][0]);

                    if (!CaseSensitive)
                    {
                        user = user.ToLower();
                    }

                    AccountStatus status = AccountStatus.EXISTS;
                    if ((uac & 0x00000010) == 0x00000010)
                    {
                        status |= AccountStatus.LOCKED;
                    }
                    if ((uac & 0x00000002) == 0x00000002)
                    {
                        status |= AccountStatus.DISABLED;
                    }
                    //if (entry.Attributes.Contains("isDeleted") && bool.Parse((string)entry.Attributes["isDeleted"][0]))
                    //{
                    //    status |= Account.DELETED;
                    //}

                    ret[user] = status;
                }

                //find the returned page response control
                foreach (DirectoryControl control in response.Controls)
                {
                    if (control is PageResultResponseControl)
                    {
                        //update the cookie for next set
                        pageRequestControl.Cookie = ((PageResultResponseControl)control).Cookie;
                        break;
                    }
                }

                if (pageRequestControl.Cookie.Length == 0)
                {
                    break;
                }
            }
            //con.SessionOptions.StopTransportLayerSecurity();

            return(ret);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Performs LDAP Search and extracts attributes.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="currentTime">Locked program timestamp value</param>
        Task ExtractLdapResultsAsync(DateTime currentTime)
        {
            var attributesToAdd = new List <string>();

            foreach (var item in Properties)
            {
                attributesToAdd.Add(item.Mapping);
            }
            attributesToAdd.Add("userAccountControl");
            var ldapFilter    = SetQueryFilter(BatchAction, currentTime);
            var searchRequest = new SearchRequest(SearchRoot, ldapFilter, SearchScope.Subtree, attributesToAdd.ToArray());
            var pageResponse  = new PageResultRequestControl(PageSize);
            var searchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);

            searchRequest.Controls.Add(pageResponse);
            searchRequest.Controls.Add(searchOptions);
            Log?.LogInformation($"Establishing LDAP Connection to: {ServerName}");
            using (var connection = CreateLdapConnection())
            {
                Log?.LogInformation($"Performing a {BatchAction} operation with filter: {ldapFilter}");
                while (true)
                {
                    SearchResponse response = null;
                    try { response = connection.SendRequest(searchRequest) as SearchResponse; }
                    catch (Exception e) { throw new Exception("An error occurred whilst creating the SearchResponse", e); }

                    var responseCount    = response.Entries.Count;
                    var currentBatchSize = (responseCount != PageSize ? responseCount : PageSize);
                    var filePath         = CsvCreateFile(DirectoryLocation, _totalUsers, currentBatchSize);

                    foreach (var control in response.Controls)
                    {
                        if (control is PageResultResponseControl responseControl)
                        {
                            pageResponse.Cookie = responseControl.Cookie;
                            break;
                        }
                    }

                    // Create CSV file for current batch of users
                    using (var batchFile = new CsvWriter(filePath, Log))
                    {
                        // Create column headings for CSV file
                        var heading = new CsvRow();
                        // Iterate over attribute headings
                        foreach (var item in Properties)
                        {
                            heading.Add(item.Name);
                        }
                        batchFile.CsvWrite(heading);
                        // Create new CSV row for each user
                        foreach (SearchResultEntry sre in response.Entries)
                        {
                            // Placeholder for CSV entry of current user
                            var entry     = new CsvRow();
                            var syncValue = true;

                            // Get whether account is disabled
                            var userAccountControlAttr = sre.Attributes["userAccountControl"];
                            var accountDisabled        = true;
                            if (userAccountControlAttr != null && userAccountControlAttr.Count > 0)
                            {
                                var userAccountControlValue = userAccountControlAttr[0].ToString();
                                try
                                {
                                    var userAccountControl = int.Parse(userAccountControlValue);
                                    accountDisabled = (userAccountControl & ACCOUNTDISABLE) == ACCOUNTDISABLE;
                                }
                                catch (Exception e) { Log?.LogCritical(e, e.Message); }
                            }

                            // Extract each user attribute specified in XML file
                            foreach (var item in Properties)
                            {
                                try
                                {
                                    var attr  = sre.Attributes[item.Mapping];
                                    var value = (attr != null && attr.Count > 0 ? attr[0].ToString() : string.Empty);
                                    if (syncValue && TryParseValue(item, entry, value, accountDisabled, attr, sre))
                                    {
                                        continue;
                                    }
                                    if (item.Index == UserNameIndex)
                                    {
                                        entry.Add(CreateUserAccountName(value, attr));
                                        continue;
                                    }
                                    entry.Add(syncValue ? value : string.Empty);
                                }
                                catch (Exception e) { Log?.LogCritical(e, string.Empty); _totalFailures++; }
                            }
                            // Write current user to CSV file
                            batchFile.CsvWrite(entry);
                            // Increment user count value
                            _totalUsers++;
                        }
                    }
                    Log?.LogInformation($"Successfully extracted {currentBatchSize} users to {filePath} - the total user count is: {_totalUsers}");
                    if (pageResponse.Cookie.Length == 0)
                    {
                        break;
                    }
                }
            }
            return(Task.CompletedTask);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Lazy-loading pure IEnumerable with transparent paging
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable <SearchResultEntry> GetResults()
        {
            SearchRequest req = new SearchRequest
            {
                DistinguishedName = this.DistinguishedName,
                Filter            = this.Filter,
                Scope             = this.SearchScope
            };

            if (this.MaxSearchTimePerPage.TotalSeconds > 0)
            {
                req.TimeLimit = this.MaxSearchTimePerPage;
            }

            if (this.SizeLimit > 0)
            {
                req.SizeLimit = this.SizeLimit;
            }

            string alist = string.Empty;

            if (this.Attrs != null && this.Attrs.Length > 0)
            {
                alist = string.Join("!", this.Attrs);
                req.Attributes.AddRange(this.Attrs);
            }

            PageResultRequestControl prc = new PageResultRequestControl(this.PageSize);

            prc.IsCritical = false;

            logger.Trace("Initial pg of {0}, max pages {1}", this.PageSize, this.MaxPages);

            int currentPage = 0;

            while (!_abort && prc != null && (currentPage++ < this.MaxPages || this.MaxPages < 1))
            {
                if (this.PageSize > 0 && (this.PageSize < this.SizeLimit || this.SizeLimit == 0))
                {
                    if (currentPage > 1)
                    {
                        req.Controls.Clear();
                    }

                    req.Controls.Add(prc);
                }
                else
                {
                    logger.Trace("Unpaged search (pgsz {0}, sizelimit {1})", this.PageSize, this.SizeLimit);
                }

                foreach (var dc in this.UserControls)
                {
                    req.Controls.Add(dc);
                }

                string key = this.DistinguishedName + ";" + this.SearchScope.ToString()
                             + ";f=" + this.Filter + ";cp=" + currentPage + ";psz=" + this.PageSize
                             + ";szl=" + this.SizeLimit + ";att" + alist;

                SearchResponse resp;

                try
                {
                    resp = this.GetSearchResponse(key, req);

                    if (resp != null)
                    {
                        logger.Debug("{0} total results", resp.Entries.Count);
                    }
                }
                catch (LdapException lde)
                {
                    if (_abort && lde.ErrorCode == 88)
                    {
                        logger.Info("Canceled by user");
                        yield break;
                    }
                    else
                    {
                        logger.Error("Ldap server msg {0}, code {1}, ex msg {2}",
                                     lde.ServerErrorMessage, lde.ErrorCode, lde.Message);
                        throw;
                    }
                }
                // Note that Directory(Operation)Exception is NOT a subclass of LdapException
                // nor vice versa... verified

                if (_abort || resp == null)
                {
                    yield break;
                }

                foreach (SearchResultEntry se in resp.Entries)
                {
                    if (_abort)
                    {
                        logger.Info("Request aborted in enum");
                        yield break;
                    }

                    yield return(se);
                }

                prc = UpdatePrc(resp);
            }
        }
Exemplo n.º 22
0
        //Find all matching LDAP objects from LDAP
        //[adsisearcher]::new([adsi]"LDAP://DC","(filter)").FindAll()
        public static IEnumerable <SearchResultEntry> GetResultEntries(LDAPSearchString searchString)
        {
            var connection = ConnectDirectory(searchString.UseGlobalCatalog);

            _logger.Debug($"Collecting {searchString.Filter} from ({searchString.DN}) with SearchScope.{searchString.Scope}");

            try
            {
                var request        = GetRequest(searchString.DN, searchString.Filter, searchString.ReturnAttributes, searchString.Scope);
                var pageReqControl = new PageResultRequestControl(500);
                request.Controls.Add(pageReqControl);

                while (true)
                {
                    SearchResponse response;
                    try
                    {
                        _logger.Debug("Sending Request...");
                        response = (SearchResponse)connection.SendRequest(request);
                        _logger.Debug($"{response.Entries.Count} Entries Received");
                    }
                    catch (Exception e)
                    {
                        _logger.Warn(e.Message + "[DN:" + searchString.DN + " Filter:" + searchString.Filter + "]");
                        yield break;
                    }
                    if (response.Controls.Length != 1 || !(response.Controls[0] is PageResultResponseControl))
                    {
                        _logger.Error("The server does not support this advanced search operation");
                        yield break;
                    }

                    var pageResControl = (PageResultResponseControl)response.Controls[0];

                    //Console.WriteLine("\n[*] This page contains {0} response entries:\n", response.Entries.Count);
                    if (response.Entries.Count != 0)
                    {
                        foreach (SearchResultEntry entry in response.Entries)
                        {
                            yield return(entry);
                        }
                    }

                    if (pageResControl.Cookie.Length == 0)
                    {
                        break;
                    }

                    pageReqControl.Cookie = pageResControl.Cookie;
                }
            }
            finally
            {
                if (!searchString.UseGlobalCatalog)
                {
                    _connectionPool.Add(connection);
                }
                else
                {
                    connection.Dispose();
                }
            }
        }
Exemplo n.º 23
0
        public void TestPageRequests()
        {
            using (LdapConnection connection = GetConnection())
            {
                string ouName = "ProtocolsGroup8";
                string dn     = "ou=" + ouName;

                try
                {
                    for (int i = 0; i < 20; i++)
                    {
                        DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn);
                    }
                    DeleteEntry(connection, dn);

                    AddOrganizationalUnit(connection, dn);
                    SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName);
                    Assert.NotNull(sre);

                    for (int i = 0; i < 20; i++)
                    {
                        AddOrganizationalUnit(connection, "ou=ProtocolsSubGroup8." + i + "," + dn);
                    }

                    string        filter        = "(objectClass=*)";
                    SearchRequest searchRequest = new SearchRequest(
                        dn + "," + LdapConfiguration.Configuration.Domain,
                        filter,
                        SearchScope.Subtree,
                        null);

                    PageResultRequestControl pageRequest = new PageResultRequestControl(5);
                    searchRequest.Controls.Add(pageRequest);
                    SearchOptionsControl searchOptions = new SearchOptionsControl(SearchOption.DomainScope);
                    searchRequest.Controls.Add(searchOptions);
                    while (true)
                    {
                        SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                        Assert.Equal(1, searchResponse.Controls.Length);
                        Assert.True(searchResponse.Controls[0] is PageResultResponseControl);

                        PageResultResponseControl pageResponse = (PageResultResponseControl)searchResponse.Controls[0];

                        if (pageResponse.Cookie.Length == 0)
                        {
                            break;
                        }

                        pageRequest.Cookie = pageResponse.Cookie;
                    }
                }
                finally
                {
                    for (int i = 0; i < 20; i++)
                    {
                        DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn);
                    }
                    DeleteEntry(connection, dn);
                }
            }
        }
Exemplo n.º 24
0
        static void DoPagedSearch()
        {
            Console.WriteLine("\r\nDoing a paged search ...");

            string ldapSearchFilter = "(&(objectClass=organizationalUnit)(ou=object*))";

            // return only these attributes
            string[] attributesToReturn = new string[] { "description", "ou", "objectClass" };

            PageResultRequestControl pageRequestControl =
                new PageResultRequestControl(pageSize);

            // used to retrieve the cookie to send for the subsequent request
            PageResultResponseControl pageResponseControl;

            SearchResponse searchResponse;

            // create a search request: specify baseDn,
            // ldap search filter, attributes to return and scope of the search
            SearchRequest searchRequest = new SearchRequest
                                              (targetOU,
                                              ldapSearchFilter,
                                              SearchScope.Subtree,
                                              attributesToReturn);

            // attach a page request control to retrieve the results in small chunks
            searchRequest.Controls.Add(pageRequestControl);


            int pageCount = 0;
            int count;

            // search in a loop untill there is no more page to retrieve
            while (true)
            {
                pageCount++;

                searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);

                Console.WriteLine("\r\nPage" + pageCount + ": " +
                                  searchResponse.Entries.Count + " entries:");

                // print the entries in this page
                count = 0;
                foreach (SearchResultEntry entry in searchResponse.Entries)
                {
                    Console.WriteLine(++count + ":" + entry.DistinguishedName);
                }


                // retrieve the cookie
                if (searchResponse.Controls.Length != 1 ||
                    !(searchResponse.Controls[0] is PageResultResponseControl))
                {
                    Console.WriteLine("The server did not return a " +
                                      "PageResultResponseControl as expected.");
                    return;
                }

                pageResponseControl = (PageResultResponseControl)searchResponse.Controls[0];

                // if responseControl.Cookie.Length is 0 then there
                // is no more page to retrieve so break the loop
                if (pageResponseControl.Cookie.Length == 0)
                {
                    break;
                }

                // set the cookie from the response control to retrieve the next page
                pageRequestControl.Cookie = pageResponseControl.Cookie;
            }

            Console.WriteLine("\r\nPaged search is completed successfully.\r\n");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Search method
        /// </summary>
        /// <param name="dir">Search settings<seealso cref="DirectoryType"/></param>
        /// <returns>A dataset conform to the specified FieldFormatters<seealso cref="FieldFormatter"/></returns>
        public static DataSet Search(DirectoryType dir)
        {
            DataSet            results = new DataSet();
            DataTable          dt      = results.Tables.Add();
            LdapDatasourceType ldt     = (LdapDatasourceType)dir.Item;

            try
            {
                Init(ldt.server, ldt.authenticationType, ldt.user, ldt.userPassword, ldt.targetOU, ldt.ldapFilter, ldt.pageSize, ldt.nbPages);
                log.Debug("Search " + ldapFilter + " from " + targetOU + " on " + ldapServer);
                PageResultRequestControl prc = new PageResultRequestControl(pageSize);
                prc.IsCritical = false;
                PageResultResponseControl cookie;
                SearchResponse            sr;

                SearchRequest request = new SearchRequest(targetOU, ldapFilter, SearchScope.Subtree, ldt.ldapAttributes);
                request.Controls.Add(prc);

                foreach (string attribut in ldt.ldapAttributes)
                {
                    dt.Columns.Add(attribut, typeof(string));
                }


                int pageCount = 0;
                int count;
                while (true)
                {
                    pageCount++;

                    sr = (SearchResponse)ldapConnection.SendRequest(request);
                    log.Debug("Page " + pageCount.ToString() + ": " + sr.Entries.Count + " entries");

                    count = 0;
                    foreach (SearchResultEntry entry in sr.Entries)
                    {
                        count++;
                        log.Debug("Entry " + count.ToString() + ": " + entry.DistinguishedName);
                        List <object> values = new List <object>();

                        foreach (string attribut in ldt.ldapAttributes)
                        {
                            DirectoryAttribute da = entry.Attributes[attribut];
                            if (da != null && da.GetValues(typeof(string)).Length > 0)
                            {
                                values.Add((string)da.GetValues(typeof(string))[0]);
                            }
                            else
                            {
                                values.Add("");
                            }
                        }
                        dt.Rows.Add(values.ToArray());
                    }

                    if (sr.Controls.Length != 1 || !(sr.Controls[0] is PageResultResponseControl))
                    {
                        log.Debug("Weird response...");
                        ldapConnection.Dispose();
                        return(results);
                    }

                    cookie = (PageResultResponseControl)sr.Controls[0];

                    if (cookie.Cookie.Length == 0)
                    {
                        break;
                    }

                    prc.Cookie = cookie.Cookie;
                }

                ldapConnection.Dispose();
                log.Debug("Search ended");
                return(results);
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(results);
            }
        }
Exemplo n.º 26
0
        public static List <IDictionary <string, Object> > GetLdapQuery(System.Net.NetworkCredential cred, string OUName, string domainController, string domain, string filter, bool ldaps = false)
        {
            var ActiveDirectoryObjects = new List <IDictionary <string, Object> >();

            if (String.IsNullOrEmpty(domainController))
            {
                domainController = Networking.GetDCName(domain); //if domain is null, this will try to find a DC in current user's domain
            }
            if (String.IsNullOrEmpty(domainController))
            {
                Console.WriteLine("[X] Unable to retrieve the domain information, try again with '/domain'.");
                return(null);
            }

            if (ldaps)
            {
                LdapConnection           ldapConnection = null;
                SearchResponse           response       = null;
                List <SearchResultEntry> result         = new List <SearchResultEntry>();
                // perhaps make this dynamic?
                int maxResultsToRequest = 1000;

                try
                {
                    var serverId = new LdapDirectoryIdentifier(domainController, 636);
                    ldapConnection = new LdapConnection(serverId, cred);
                    ldapConnection.SessionOptions.SecureSocketLayer        = true;
                    ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return(true); };
                    ldapConnection.Bind();
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("[X] Error binding to LDAP server: {0}", ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("[X] Error binding to LDAP server: {0}", ex.Message);
                    }
                    return(null);
                }

                if (String.IsNullOrEmpty(OUName))
                {
                    OUName = String.Format("DC={0}", domain.Replace(".", ",DC="));
                }

                try
                {
                    Console.WriteLine("[*] Searching path '{0}' for '{1}'", OUName, filter);
                    PageResultRequestControl  pageRequestControl = new PageResultRequestControl(maxResultsToRequest);
                    PageResultResponseControl pageResponseControl;
                    SearchRequest             request = new SearchRequest(OUName, filter, SearchScope.Subtree, null);
                    request.Controls.Add(pageRequestControl);
                    while (true)
                    {
                        response = (SearchResponse)ldapConnection.SendRequest(request);
                        foreach (SearchResultEntry entry in response.Entries)
                        {
                            result.Add(entry);
                        }
                        pageResponseControl = (PageResultResponseControl)response.Controls[0];
                        if (pageResponseControl.Cookie.Length == 0)
                        {
                            break;
                        }
                        pageRequestControl.Cookie = pageResponseControl.Cookie;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Error executing LDAP query: {0}", ex.Message);
                }

                if (response.ResultCode == ResultCode.Success)
                {
                    ActiveDirectoryObjects = Helpers.GetADObjects(result);
                }
            }
            else
            {
                DirectoryEntry    directoryObject = null;
                DirectorySearcher searcher        = null;
                try
                {
                    directoryObject = Networking.GetLdapSearchRoot(cred, OUName, domainController, domain);
                    searcher        = new DirectorySearcher(directoryObject);
                    // enable LDAP paged search to get all results, by pages of 1000 items
                    searcher.PageSize = 1000;
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("[X] Error creating the domain searcher: {0}", ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("[X] Error creating the domain searcher: {0}", ex.Message);
                    }
                    return(null);
                }

                // check to ensure that the bind worked correctly
                try
                {
                    string dirPath = directoryObject.Path;
                    if (String.IsNullOrEmpty(dirPath))
                    {
                        Console.WriteLine("[*] Searching the current domain for '{0}'", filter);
                    }
                    else
                    {
                        Console.WriteLine("[*] Searching path '{0}' for '{1}'", dirPath, filter);
                    }
                }
                catch (DirectoryServicesCOMException ex)
                {
                    if (!String.IsNullOrEmpty(OUName))
                    {
                        Console.WriteLine("\r\n[X] Error validating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message);
                    }
                    else
                    {
                        Console.WriteLine("\r\n[X] Error validating the domain searcher: {0}", ex.Message);
                    }
                    return(null);
                }

                try
                {
                    searcher.Filter = filter;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Error settings the domain searcher filter: {0}", ex.InnerException.Message);
                    return(null);
                }

                SearchResultCollection results = null;

                try
                {
                    results = searcher.FindAll();

                    if (results.Count == 0)
                    {
                        Console.WriteLine("[X] No results returned by LDAP!");
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("[X] Error executing the domain searcher: {0}", ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("[X] Error executing the domain searcher: {0}", ex.Message);
                    }
                    return(null);
                }
                ActiveDirectoryObjects = Helpers.GetADObjects(results);
            }

            return(ActiveDirectoryObjects);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Performs an LDAP search returning multiple objects/pages
        /// </summary>
        /// <param name="ldapFilter"></param>
        /// <param name="props"></param>
        /// <param name="scope"></param>
        /// <param name="adsPath"></param>
        /// <param name="globalCatalog"></param>
        /// <returns>An IEnumerable with search results</returns>
        internal IEnumerable <SearchResultEntry> QueryLdap(string ldapFilter, string[] props, SearchScope scope, string adsPath = null, bool globalCatalog = false)
        {
            var connection = globalCatalog ? GetGlobalCatalogConnection() : GetLdapConnection();

            try
            {
                var searchRequest = CreateSearchRequest(ldapFilter, scope, props, adsPath);
                var pageRequest   = new PageResultRequestControl(500);
                searchRequest.Controls.Add(pageRequest);

                var securityDescriptorFlagControl = new SecurityDescriptorFlagControl
                {
                    SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
                };
                searchRequest.Controls.Add(securityDescriptorFlagControl);

                while (true)
                {
                    SearchResponse searchResponse;
                    try
                    {
                        searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                    }
                    catch (Exception e)
                    {
                        //Console.WriteLine(ldapFilter);
                        //Console.WriteLine("\nUnexpected exception occured:\n\t{0}: {1}",
                        //    e.GetType().Name, e.Message);
                        yield break;
                    }

                    if (searchResponse.Controls.Length != 1 ||
                        !(searchResponse.Controls[0] is PageResultResponseControl))
                    {
                        //Mq.Error("Server does not support paging");
                        yield break;
                    }

                    var pageResponse = (PageResultResponseControl)searchResponse.Controls[0];

                    foreach (SearchResultEntry entry in searchResponse.Entries)
                    {
                        yield return(entry);
                    }

                    if (pageResponse.Cookie.Length == 0)
                    {
                        break;
                    }

                    pageRequest.Cookie = pageResponse.Cookie;
                }
            }
            finally
            {
                if (!globalCatalog)
                {
                    _connectionPool.Add(connection);
                }
                else
                {
                    connection.Dispose();
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Searches the LDAP directory for entries that match the specified search filter.
        /// </summary>
        /// <param name="filter">The filter that defines the entries to find.</param>
        /// <param name="attributes">(Optional) The attributes that should be returned in each entry found. </param>
        /// <param name="baseDn">(Optional)The distinguished name of the base entry where the search will begin. (Typically an OU or the base DN of the directory.) If not supplied, the default values will be used. This base is used only for the duration of this search.</param>
        /// <param name="scope">(Optional) The scope to use while searching. Defaults to Subtree. (Typically Base, just the object with the DN specified; OneLevel, just the child objects of the base object; or Subtree, the base object and all child objects) This scope is used only for the duration of this search.</param>
        /// <param name="queryPageSize">(Optional) The query page size to specify when making large requests. Defaults to DEFAULT_QUERY_PAGE_SIZE.</param>
        /// <param name="chaseReferrals">(Optional) Whether the search should chase object referrals to other servers if necessary. Defaults to true;</param>
        /// <returns>A collection of search result entries found, or null if there was an error with the search.</returns>
        public List <SearchResultEntry> Search(string filter, List <string> attributes = null, string baseDn = null, SearchScope scope = SearchScope.Subtree, int queryPageSize = DEFAULT_QUERY_PAGE_SIZE, bool chaseReferrals = true)
        {
            // Set the search base and scope for the search if provided.
            string      previousBase       = searchBaseDN;
            SearchScope previousScope      = searchScope;
            bool        customBaseAndScope = false;

            if (!string.IsNullOrWhiteSpace(baseDn))
            {
                SetSearchBaseAndScope(baseDn, scope);
                customBaseAndScope = true;
            }

            SearchRequest request = null;

            // Check if attributes have been provided.
            if (attributes == null || attributes.Count == 0)
            {
                // No attributes were provided... get them all.
                request = new SearchRequest(searchBaseDN, filter, searchScope);
            }
            else
            {
                // Specific attributes were requested, limit the search to just them.
                request = new SearchRequest(searchBaseDN, filter, searchScope, attributes.ToArray());
            }

            // Add a directory control that makes the search use pages for returning large result sets.
            PageResultRequestControl pageResultRequestControl = new PageResultRequestControl(queryPageSize);

            request.Controls.Add(pageResultRequestControl);

            if (!chaseReferrals)
            {
                // Turn of referral chasing in the session.
                connection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
            }

            // Create a list to hold our results while we request all of the results in pages.
            List <SearchResultEntry> results = new List <SearchResultEntry>();

            try
            {
                while (true)
                {
                    // Add the page request control that manages the paged searched, and send the request for results.
                    SearchResponse response = (SearchResponse)connection.SendRequest(request);

                    // Check that we received a response.
                    if (response != null)
                    {
                        // A response was received.

                        // Get the paging response control to allow us to gather the results in batches.
                        foreach (DirectoryControl control in response.Controls)
                        {
                            if (control is PageResultResponseControl)
                            {
                                PageResultResponseControl pageResultResponseControl =
                                    (PageResultResponseControl)control;

                                // Update the cookie in the request control to gather the next page of the query.
                                pageResultRequestControl.Cookie = pageResultResponseControl.Cookie;

                                // Break out of the loop now that we've copied the cookie.
                                break;
                            }
                        }

                        if (response.ResultCode == ResultCode.Success)
                        {
                            // Add the results to the list.
                            foreach (SearchResultEntry entry in response.Entries)
                            {
                                results.Add(entry);
                            }
                        }
                        else
                        {
                            // There has been an error retrieving the results.

                            // Reset the search base and scope if necessary.
                            if (customBaseAndScope)
                            {
                                SetSearchBaseAndScope(previousBase, previousScope);
                            }

                            return(null);
                        }

                        // Check whether the cookies is empty and all the results have been gathered.
                        if (pageResultRequestControl.Cookie.Length == 0)
                        {
                            // The cookie is empty. We're done gathing results.
                            break;
                        }
                    }
                    else
                    {
                        // No response was received.
                        return(null);
                    }
                }
                // Return the results found.

                // Reset the search base and scope if necessary.
                if (customBaseAndScope)
                {
                    SetSearchBaseAndScope(previousBase, previousScope);
                }

                return(results);
            }
            catch
            {
            }

            // Reset the search base and scope if necessary.
            if (customBaseAndScope)
            {
                SetSearchBaseAndScope(previousBase, previousScope);
            }

            return(null);
        }