Exemplo n.º 1
0
        //returns search result as list of distinguishedNames
        //[DirectoryServicesPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public static ReadOnlyCollection <string> Search(string filter, string baseDN, string propToLoad, int pageSize)
        {
            List <string>  retVal = new List <string>();
            LdapConnection conn   = GetLdapConnection(ConnectionType.Ldap);

            SearchRequest rq = new SearchRequest(baseDN, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, propToLoad);
            //we need to perform a paged search here
            PageResultRequestControl pagedRqc = new PageResultRequestControl(pageSize);

            if (pageSize > 0)
            {
                rq.Controls.Add(pagedRqc);
            }
            rq.Controls.Add(new SearchOptionsControl(SearchOption.DomainScope));
            bool processingFinished = false;

            while (!processingFinished)
            {
                SearchResponse rsp = conn.SendRequest(rq) as SearchResponse;
                if (pageSize > 0)
                {
                    PageResultResponseControl prrc = null;
                    if (rsp.Controls.Length > 0)
                    {
                        foreach (DirectoryControl ctrl in rsp.Controls)
                        {
                            if (ctrl is PageResultResponseControl)
                            {
                                prrc = ctrl as PageResultResponseControl;
                                break;
                            }
                        }
                    }
                    if (prrc == null)
                    {
                        throw new DirectoryOperationException("Paging is not supported");
                    }
                    if (prrc.Cookie.Length == 0)
                    {
                        //last page --> we're done
                        processingFinished = true;
                    }
                    else
                    {
                        pagedRqc.Cookie = prrc.Cookie;
                    }
                }
                else
                {
                    processingFinished = true;
                }
                foreach (SearchResultEntry sr in rsp.Entries)
                {
                    retVal.Add(sr.DistinguishedName);
                }
            }
            return(new ReadOnlyCollection <string>(retVal));
        }
        public override void JustGronkIT()
        {
            string filter    = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
            string tartgetOU = @"yourdomain.com";

            string[] attrs = { "sAMAccountName",      "givenName",        "sn",          "initials", "description",   "userPrincipalName", "distinguishedName",
                               "extentionAttribute6", "departmentNumber", "wwwHomePage", "manager",  "extensionName", "mail",              "telephoneNumber" };
            using (_LDAP = new LdapConnection(Properties.Settings.Default.Domain))
            {
                myADUsers = new ADDataSet();
                myADUsers.ADUsers.MinimumCapacity = 60000;
                myADUsers.ADUsers.CaseSensitive   = false;

                try
                {
                    SearchRequest            request     = new SearchRequest(tartgetOU, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, attrs);
                    PageResultRequestControl pageRequest = new PageResultRequestControl(5000);
                    request.Controls.Add(pageRequest);
                    SearchOptionsControl searchOptions = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);
                    request.Controls.Add(searchOptions);

                    while (true)
                    {
                        SearchResponse            searchResponse = (SearchResponse)_LDAP.SendRequest(request);
                        PageResultResponseControl pageResponse   = (PageResultResponseControl)searchResponse.Controls[0];
                        foreach (SearchResultEntry entry in searchResponse.Entries)
                        {
                            string _myUserid = "";
                            string _myUPN    = "";
                            SearchResultAttributeCollection attributes = entry.Attributes;
                            foreach (DirectoryAttribute attribute in attributes.Values)
                            {
                                if (attribute.Name.Equals("sAMAccountName"))
                                {
                                    _myUserid = (string)attribute[0] ?? "";
                                    _myUserid.Trim();
                                }
                                if (attribute.Name.Equals("userPrincipalName"))
                                {
                                    _myUPN = (string)attribute[0] ?? "";
                                    _myUPN.Trim();
                                }
                                //etc with each datum you return from AD
                            }                                //foreach DirectoryAttribute
                                                             //do something with all the above info, I put it into a dataset
                        }                                    //foreach SearchResultEntry
                        if (pageResponse.Cookie.Length == 0) //check and see if there are more pages
                        {
                            break;                           //There are no more pages
                        }
                        pageRequest.Cookie = pageResponse.Cookie;
                    }   //while loop
                }  //try
                catch {}
            } //using _LDAP
        }     //JustGronkIT method
Exemplo n.º 3
0
        protected override void ProcessRecord()
        {
            SearchRoot = base.CheckSearchRoot(SearchRoot);

            String LdapFilter = "(&(objectCategory=dnsNode))";

            if (Name != String.Empty)
            {
                LdapFilter = String.Format("(&(objectCategory=dnsNode)(name={0}))", Name);
            }

            base.SetLdapConnection(Server, Credential);
            base.SetSearchRequest(SearchRoot, LdapFilter);

            int pageCount = 0;

            while (true)
            {
                pageCount++;

                SearchResponse SearchResponse =
                    (SearchResponse)base.LdapConnection.SendRequest(this.SearchRequest);

                if (SearchResponse.Controls.Length != 1 ||
                    !(SearchResponse.Controls[0] is PageResultResponseControl))
                {
                    return;
                }

                PageResultResponseControl PageResponse =
                    (PageResultResponseControl)SearchResponse.Controls[0];

                foreach (SearchResultEntry Entry in SearchResponse.Entries)
                {
                    for (int i = 0; i < Entry.Attributes["dnsrecord"].Count; i++)
                    {
                        RecordType CurrentRecordType = (RecordType)(UInt16)(
                            ((Byte[])Entry.Attributes["dnsrecord"].GetValues(typeof(Byte[]))[i])[2] +
                            ((Byte[])Entry.Attributes["dnsrecord"].GetValues(typeof(Byte[]))[i])[3] * 256);

                        base.WriteRecord(Entry, i, CurrentRecordType);
                    }
                }

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

                PageRequest.Cookie = PageResponse.Cookie;
            }
        }
Exemplo n.º 4
0
        protected override void ProcessRecord()
        {
            SearchRoot = base.CheckSearchRoot(SearchRoot);

            String LdapFilter = "(&(objectCategory=dnsZone))";

            if (Name != String.Empty)
            {
                LdapFilter = String.Format("(&(objectCategory=dnsZone)(name={0}))", Name);
            }

            base.SetLdapConnection(Server, Credential);
            base.SetSearchRequest(SearchRoot, LdapFilter);

            int pageCount = 0;

            while (true)
            {
                pageCount++;

                SearchResponse SearchResponse =
                    (SearchResponse)base.LdapConnection.SendRequest(this.SearchRequest);

                if (SearchResponse.Controls.Length != 1 ||
                    !(SearchResponse.Controls[0] is PageResultResponseControl))
                {
                    return;
                }

                PageResultResponseControl PageResponse =
                    (PageResultResponseControl)SearchResponse.Controls[0];

                foreach (SearchResultEntry Entry in SearchResponse.Entries)
                {
                    WriteObject(new Zone(Entry));
                }

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

                PageRequest.Cookie = PageResponse.Cookie;
            }
        }
Exemplo n.º 5
0
        public void UpdatePagingCookie(DirectoryControl dControl, int pageSize)
        {
            if (FirstPagingRun)
            {
                CurrentPageSize = pageSize;

                FirstPagingRun = false;
            }

            else if (pageSize > CurrentPageSize)
            {
                CurrentPageSize = pageSize;
            }


            Request.Controls.Remove(PageControl);

            MoreData = false;

            if (dControl != null)
            {
                PageResultResponseControl response = (PageResultResponseControl)dControl;

                PagingCookie = response.Cookie;
            }

            if ((PagingCookie != null) && (PagingCookie.Length != 0))
            {
                MoreData = true;
            }

            else
            {
                MoreData = false;
            }

            if (MoreData)
            {
                PageControl = new PageResultRequestControl(PagingCookie);

                PageControl.PageSize = pageSize;

                Request.Controls.Add(PageControl);
            }
        }
Exemplo n.º 6
0
        internal void FindAll()
        {
            // The code for this section is taken from http://msdn.microsoft.com/en-us/library/bb332056.aspx

            int pageCount = 0;

            while (true)
            {
                // increment the pageCount by 1
                pageCount++;

                // cast the directory response into a SearchResponse object
                SearchResponse SearchResponse =
                    (SearchResponse)this.LdapConnection.SendRequest(this.SearchRequest);

                // verify support for this advanced search operation
                if (SearchResponse.Controls.Length != 1 ||
                    !(SearchResponse.Controls[0] is PageResultResponseControl))
                {
                    // Console.WriteLine("The server cannot page the result set");
                    return;
                }

                // cast the diretory control into a PageResultResponseControl object.
                PageResultResponseControl PageResponse =
                    (PageResultResponseControl)SearchResponse.Controls[0];

                // display the entries within this page
                foreach (SearchResultEntry Entry in SearchResponse.Entries)
                {
                }

                // if this is true, there are no more pages to request
                if (PageResponse.Cookie.Length == 0)
                {
                    break;
                }

                // set the cookie of the pageRequest equal to the cookie
                // of the pageResponse to request the next page of data
                // in the send request
                PageRequest.Cookie = PageResponse.Cookie;
            }
        }
Exemplo n.º 7
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.º 8
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.º 9
0
        protected PageResultRequestControl UpdatePrc(SearchResponse resp)
        {
            if (this.PageSize < 1)
            {
                return(null);
            }

            foreach (DirectoryControl dc in resp.Controls)
            {
                PageResultResponseControl c = dc as PageResultResponseControl;

                if (c != null && c.Cookie != null && c.Cookie.Length > 0)
                {
                    return new PageResultRequestControl
                           {
                               Cookie     = c.Cookie,
                               PageSize   = this.PageSize,
                               IsCritical = true
                           }
                }
                ;
            }
            return(null);
        }
Exemplo n.º 10
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.º 11
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.º 12
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.º 13
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);
        }
Exemplo n.º 14
0
        private List <string> GetAllGroupNames()
        {
            List <string>  groups            = new List <string>();
            LdapConnection conn              = null;
            int            defaultADPageSize = 500;
            int            pageCount         = 0;

            try
            {
                string ActiveDirectoryGroupFilterQuery2 =
                    "(|(objectClass=msExchDynamicDistributionList)(objectClass=group))";
                string[]      propertiesToQuery = { "distinguishedname", "objectguid", "member", "memberof", "objectClass" };
                SearchRequest request           = new SearchRequest(
                    null,
                    ActiveDirectoryGroupFilterQuery2,
                    System.DirectoryServices.Protocols.SearchScope.Subtree,
                    propertiesToQuery);
                // Set the result page size
                SearchRequest searchRequestDistinguishedName = new SearchRequest
                {
                    Scope  = SearchScope.Subtree,
                    Filter = ActiveDirectoryGroupFilterQuery2
                };
                SearchOptionsControl searchOptions =
                    new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.PhantomRoot);
                searchRequestDistinguishedName.Controls.Add(searchOptions);
                //PageResultRequestControl requestPageSize = new PageResultRequestControl(defaultADPageSize);

                //request.Controls.Add(requestPageSize);
                while (true)
                {
                    PageResultResponseControl pageResponse = null;

                    SearchResponse results =
                        (SearchResponse)_ldapConnectionUsers.SendRequest(searchRequestDistinguishedName);

                    if (null == results)
                    {
                        break;
                    }
                    pageCount++;

                    // verify support for this advanced search operation
                    if (results.Controls.Length != 1 ||
                        !(results.Controls[0] is PageResultResponseControl))
                    {
                        break;
                    }
                    // cast the diretory control into a PageResultResponseControl object.
                    pageResponse = (PageResultResponseControl)results.Controls[0];
                    if (results.Entries.Count > 0)
                    {
                        foreach (SearchResultEntry searchResult in results.Entries)
                        {
                            SearchResultAttributeCollection attColl = searchResult.Attributes;
                            groups.Add(attColl["distinguishedname"][0].ToString());
                        }

                        // if this is true, there are no more pages to request
                        if (pageResponse != null && pageResponse.Cookie.Length == 0)
                        {
                            break;
                        }

                        // set the cookie of the pageRequest equal to the cookie of the pageResponse to
                        // request the next page of data in the send request
                        if (pageResponse != null)
                        {
                            //requestPageSize.Cookie = pageResponse.Cookie;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (conn != null)
                {
                    conn.Dispose();
                }
            }
            return(groups);
        }
Exemplo n.º 15
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.º 16
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.º 17
0
        public override async System.Threading.Tasks.Task <object> ExecuteAsync(LdapConnection connection, SearchScope scope, int maxPageSize, bool pagingEnabled, ILinqToLdapLogger log = null, string namingContext = null)
        {
            if (Options.YieldNoResults)
            {
                return(0);
            }

            var                       index      = BuildRequest(scope, maxPageSize, pagingEnabled, log, namingContext);
            SearchResponse            response   = null;
            int                       count      = 0;
            bool                      hasResults = false;
            PageResultResponseControl pageResultResponseControl = null;

            void handleRespnse(SearchResponse r)
            {
                r.AssertSuccess();

                pageResultResponseControl = GetControl <PageResultResponseControl>(r.Controls);
                hasResults = pageResultResponseControl != null && pageResultResponseControl.Cookie.Length > 0;
                count     += r.Entries.Count;
            }

#if NET45
            await System.Threading.Tasks.Task.Factory.FromAsync(
                (callback, state) =>
            {
                return(connection.BeginSendRequest(SearchRequest, Options.AsyncProcessing, callback, state));
            },
                (asyncresult) =>
            {
                response = (SearchResponse)connection.EndSendRequest(asyncresult);
                handleRespnse(response);
            },
                null
                ).ConfigureAwait(false);
#else
            response = await System.Threading.Tasks.Task.Run(() => connection.SendRequest(SearchRequest) as SearchResponse).ConfigureAwait(false);

            handleRespnse(response);
#endif

            if (pagingEnabled && !Options.WithoutPaging)
            {
                while (hasResults)
                {
                    SearchRequest.Controls[index] = new PageResultRequestControl(pageResultResponseControl.Cookie);

                    if (log != null && log.TraceEnabled)
                    {
                        log.Trace(SearchRequest.ToLogString());
                    }
#if NET45
                    await System.Threading.Tasks.Task.Factory.FromAsync(
                        (callback, state) =>
                    {
                        return(connection.BeginSendRequest(SearchRequest, Options.AsyncProcessing, callback, state));
                    },
                        (asyncresult) =>
                    {
                        response = (SearchResponse)connection.EndSendRequest(asyncresult);
                        handleRespnse(response);
                    },
                        null
                        ).ConfigureAwait(false);
#else
                    response = await System.Threading.Tasks.Task.Run(() => connection.SendRequest(SearchRequest) as SearchResponse).ConfigureAwait(false);

                    handleRespnse(response);
#endif
                }
            }

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

            return(count);
        }
        internal static void TransformControls(DirectoryControl[] controls)
        {
            for (int i = 0; i < controls.Length; i++)
            {
                Debug.Assert(controls[i] != null);
                byte[] value = controls[i].GetValue();
                if (controls[i].Type == "1.2.840.113556.1.4.319")
                {
                    // The control is a PageControl.
                    object[] result = BerConverter.Decode("{iO}", value);
                    Debug.Assert((result != null) && (result.Length == 2));

                    int size = (int)result[0];
                    // user expects cookie with length 0 as paged search is done.
                    byte[] cookie = (byte[])result[1] ?? Array.Empty <byte>();

                    PageResultResponseControl pageControl = new PageResultResponseControl(size, cookie, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = pageControl;
                }
                else if (controls[i].Type == "1.2.840.113556.1.4.1504")
                {
                    // The control is an AsqControl.
                    object[] o = BerConverter.Decode("{e}", value);
                    Debug.Assert((o != null) && (o.Length == 1));

                    int result             = (int)o[0];
                    AsqResponseControl asq = new AsqResponseControl(result, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = asq;
                }
                else if (controls[i].Type == "1.2.840.113556.1.4.841")
                {
                    // The control is a DirSyncControl.
                    object[] o = BerConverter.Decode("{iiO}", value);
                    Debug.Assert(o != null && o.Length == 3);

                    int    moreData      = (int)o[0];
                    int    count         = (int)o[1];
                    byte[] dirsyncCookie = (byte[])o[2];

                    DirSyncResponseControl dirsync = new DirSyncResponseControl(dirsyncCookie, (moreData == 0 ? false : true), count, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = dirsync;
                }
                else if (controls[i].Type == "1.2.840.113556.1.4.474")
                {
                    // The control is a SortControl.
                    int      result    = 0;
                    string   attribute = null;
                    object[] o         = BerConverter.TryDecode("{ea}", value, out bool decodeSucceeded);

                    // decode might fail as AD for example never returns attribute name, we don't want to unnecessarily throw and catch exception
                    if (decodeSucceeded)
                    {
                        Debug.Assert(o != null && o.Length == 2);
                        result    = (int)o[0];
                        attribute = (string)o[1];
                    }
                    else
                    {
                        // decoding might fail as attribute is optional
                        o = BerConverter.Decode("{e}", value);
                        Debug.Assert(o != null && o.Length == 1);

                        result = (int)o[0];
                    }

                    SortResponseControl sort = new SortResponseControl((ResultCode)result, attribute, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = sort;
                }
                else if (controls[i].Type == "2.16.840.1.113730.3.4.10")
                {
                    // The control is a VlvResponseControl.
                    int      position;
                    int      count;
                    int      result;
                    byte[]   context = null;
                    object[] o       = BerConverter.TryDecode("{iieO}", value, out bool decodeSucceeded);

                    if (decodeSucceeded)
                    {
                        Debug.Assert(o != null && o.Length == 4);
                        position = (int)o[0];
                        count    = (int)o[1];
                        result   = (int)o[2];
                        context  = (byte[])o[3];
                    }
                    else
                    {
                        o = BerConverter.Decode("{iie}", value);
                        Debug.Assert(o != null && o.Length == 3);
                        position = (int)o[0];
                        count    = (int)o[1];
                        result   = (int)o[2];
                    }

                    VlvResponseControl vlv = new VlvResponseControl(position, count, context, (ResultCode)result, controls[i].IsCritical, controls[i].GetValue());
                    controls[i] = vlv;
                }
            }
        }
Exemplo n.º 19
0
        protected override void ProcessRecord()
        {
            DirectoryEntry RootDSE = new DirectoryEntry(
                String.Format("LDAP://{0}/RootDSE", Server));

            if (Credential != null)
            {
                RootDSE.Username = Credential.UserName;
                RootDSE.Password = System.Runtime.InteropServices.Marshal.PtrToStringAuto(
                    System.Runtime.InteropServices.Marshal.SecureStringToBSTR(Credential.Password));
            }

            String LdapFilter = "(&(objectCategory=crossRef)(!name=Enterprise Configuration)(!name=Enterprise Schema))";

            base.SetLdapConnection(Server, Credential);
            base.Properties = new String[] { "name",
                                             "whenCreated",
                                             "whenChanged",
                                             "objectGUID",
                                             "msDS-NC-Replica-Locations",
                                             "nCName",
                                             "nETBIOSName" };
            base.SetSearchRequest(RootDSE.Properties["configurationNamingContext"][0].ToString(), LdapFilter);


            int pageCount = 0;

            while (true)
            {
                // increment the pageCount by 1
                pageCount++;

                // cast the directory response into a SearchResponse object
                SearchResponse SearchResponse =
                    (SearchResponse)base.LdapConnection.SendRequest(this.SearchRequest);

                // verify support for this advanced search operation
                if (SearchResponse.Controls.Length != 1 ||
                    !(SearchResponse.Controls[0] is PageResultResponseControl))
                {
                    // Console.WriteLine("The server cannot page the result set");
                    return;
                }

                // cast the diretory control into a PageResultResponseControl object.
                PageResultResponseControl PageResponse =
                    (PageResultResponseControl)SearchResponse.Controls[0];

                // display the entries within this page
                foreach (SearchResultEntry Entry in SearchResponse.Entries)
                {
                    WriteObject(new Partition(Entry));
                }

                // if this is true, there are no more pages to request
                if (PageResponse.Cookie.Length == 0)
                {
                    break;
                }

                // set the cookie of the pageRequest equal to the cookie
                // of the pageResponse to request the next page of data
                // in the send request
                PageRequest.Cookie = PageResponse.Cookie;
            }
        }