private System.DirectoryServices.Protocols.SearchScope getSearchScope(string name)
        {
            System.DirectoryServices.Protocols.SearchScope returnValeu = System.DirectoryServices.Protocols.SearchScope.Subtree;

            switch (name.ToLower())
            {
            case ("subtree"):
            {
                returnValeu = System.DirectoryServices.Protocols.SearchScope.Subtree;
                break;
            }

            case ("base"):
            {
                returnValeu = System.DirectoryServices.Protocols.SearchScope.Base;
                break;
            }

            case ("onelevel"):
            {
                returnValeu = System.DirectoryServices.Protocols.SearchScope.OneLevel;
                break;
            }

            default:
            {
                returnValeu = System.DirectoryServices.Protocols.SearchScope.Subtree;
                break;
            }
            }

            return(returnValeu);
        }
Example #2
0
        public static string[] GetAttributeValuesString(
            DsServer dc, string dn, string attributeName,
            string ldapFilter = "(objectClass=*)",
            System.DirectoryServices.Protocols.SearchScope searchScope
            = System.DirectoryServices.Protocols.SearchScope.Base)
        {
            SearchResultEntryCollection results = null;
            ResultCode ret = Search(
                dc,
                dn,
                ldapFilter,
                searchScope,
                new string[] { attributeName },
                out results);

            if (ret != ResultCode.Success)
            {
                return(null);
            }

            foreach (SearchResultEntry e in results)
            {
                DirectoryAttribute attr = e.Attributes[attributeName];
                if (attr == null)
                {
                    return(null);
                }
                else
                {
                    return((string[])attr.GetValues(typeof(string)));
                }
            }

            return(null);
        }
Example #3
0
        public static ResultCode Search(
            DsServer dc,
            string baseDn,
            string ldapFilter,
            System.DirectoryServices.Protocols.SearchScope searchScope,
            string[] attributesToReturn,
            out SearchResultEntryCollection results
            )
        {
            SearchResponse response = null;

            try
            {
                SearchRequest request = new SearchRequest(
                    baseDn,
                    ldapFilter,
                    searchScope,
                    attributesToReturn
                    );
                response = (SearchResponse)dc.LdapConn.SendRequest(request);
            }
            catch (DirectoryOperationException e)
            {
                results = null;
                return(e.Response.ResultCode);
            }
            results = response.Entries;
            return(response.ResultCode);
        }
Example #4
0
        public static string GetSingleValue(LdapConnection conn,
                                            string filter,
                                            SearchScope scope,
                                            string[] attrsToReturn,
                                            string dn)
        {
            var request = new SearchRequest(dn, filter, scope, attrsToReturn);

            var searchControl = new SearchOptionsControl();

            request.Controls.Add(searchControl);

            SearchResponse response;

            try
            {
                response = (SearchResponse)conn.SendRequest(request);
                foreach (SearchResultEntry entry in response.Entries)
                {
                    return(entry.DistinguishedName);
                }
                return(null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected error:  {0}", e.Message);
                return(null);
            }
        }
        public bool GetLDAPObject(string distinguishedName, string serverName,
                                  string filter, System.DirectoryServices.Protocols.SearchScope scope, string[] reqAttributes,
                                  out System.DirectoryServices.Protocols.SearchResponse result)
        {
            LdapConnection connection = null;

            try
            {
                if (serverOS < OSVersion.WinSvr2008R2)
                {
                    connection = new LdapConnection(new LdapDirectoryIdentifier(serverName));
                }
                else
                {
                    connection = new LdapConnection(new LdapDirectoryIdentifier(serverName + "." + adAdapter.PrimaryDomainDnsName));
                }
                connection.Bind();

                SearchRequest request = new SearchRequest(distinguishedName, filter, scope, reqAttributes);

                result = (SearchResponse)connection.SendRequest(request);

                connection.Dispose();

                return(true);
            }
            catch (Exception)
            {
                connection.Dispose();
                result = null;
                return(false);
            }
        }
Example #6
0
        public SearchRequest GetSearchRequest(string filter, SearchScope scope, string[] attribs, string domainName = null, string adsPath = null)
        {
            Domain targetDomain;

            try
            {
                targetDomain = GetDomain(domainName);
            }
            catch
            {
                Verbose($"Unable to contact domain {domainName}");
                return(null);
            }

            domainName = targetDomain.Name;
            adsPath    = adsPath?.Replace("LDAP://", "") ?? $"DC={domainName.Replace(".", ",DC=")}";

            var request = new SearchRequest(adsPath, filter, scope, attribs);
            //Add our search options control
            var soc = new SearchOptionsControl(SearchOption.DomainScope);

            request.Controls.Add(soc);

            return(request);
        }
Example #7
0
        public void Register(string dn, string filter, System.DirectoryServices.Protocols.SearchScope scope)
        {
            SearchRequest request = new SearchRequest(
                dn,     //root the search here
                filter, //very inclusive
                scope,  //any scope works
                null    //we are interested in all attributes
                );

            //register our search
            request.Controls.Add(new DirectoryNotificationControl());

            //we will send this async and register our callback
            //note how we would like to have partial results
            IAsyncResult result = _connection.BeginSendRequest(
                request,
                TimeSpan.FromDays(1), //set timeout to a day...
                PartialResultProcessing.ReturnPartialResultsAndNotifyCallback,
                Notify,
                request
                );

            //store the hash for disposal later
            _results.Add(result);
        }
Example #8
0
        public LdapObj SearchDnOne(String baseDn, String ldapFilter, System.DirectoryServices.Protocols.SearchScope scope, String[] attribs)
        {
            List <LdapObj> lstObjects = SearchDn(baseDn, ldapFilter, scope, attribs);

            if ((lstObjects != null) && (lstObjects.Count > 0))
            {
                return(lstObjects[0]);
            }
            return(null);
        }
Example #9
0
 public static byte[][] GetAttributeValuesBytes(
     DsServer dc,
     string dn,
     string attributeName,
     string ldapFilter = "(objectClass=*)",
     System.DirectoryServices.Protocols.SearchScope searchScope
     = System.DirectoryServices.Protocols.SearchScope.Base)
 {
     return((byte[][])(GetAttributeValuesOfType(dc, dn, attributeName, ldapFilter, searchScope, typeof(byte[]))));
 }
Example #10
0
 public static byte[] GetAttributeValueInBytes(
     DsServer dc,
     string dn,
     string attributeName,
     string ldapFilter = "(objectClass=*)",
     System.DirectoryServices.Protocols.SearchScope searchScope
     = System.DirectoryServices.Protocols.SearchScope.Base)
 {
     byte[][] attrs = GetAttributeValuesBytes(dc, dn, attributeName, ldapFilter, searchScope);
     return(attrs?[0]);
 }
Example #11
0
        public List <String> findDn(String baseDn, String ldapFilter)
        {
            List <String> lstDn = new List <string>();

            if (!bindingSuccess)
            {
                Connect();
            }
            string dnUser = String.Empty;

            System.DirectoryServices.Protocols.SearchScope scope = System.DirectoryServices.Protocols.SearchScope.Subtree;
            try
            {
                String         dn;
                SearchRequest  request  = new SearchRequest(baseDn, ldapFilter, scope);
                SearchResponse response = (SearchResponse)ldapConnexion.SendRequest(request);
                if (response.Entries.Count > 0)
                {
                    for (int i = 0; i < response.Entries.Count; i++)
                    {
                        dn = response.Entries[i].DistinguishedName;
                        //Console.WriteLine(dn);
                        lstDn.Add(dn);
                    }
                }
            }
            catch (LdapException ex)
            {
                Console.WriteLine(String.Format("Error LdapException FindPeDateMajCert {0}...", ex.Message));
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
            catch (DirectoryOperationException ex)
            {
                Console.WriteLine(String.Format("Error DirectoryOperationException FindPeDateMajCert {0}...", ex.Message));
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error Exception FindPeDateMajCert {0}...", ex.Message));
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }


            return(lstDn);
        }
        /// <summary>
        /// Creates a SearchRequest packet.
        /// </summary>
        /// <param name="context">The user context which contains message ID.</param>
        /// <param name="dn">The DN to be searched.</param>
        /// <param name="sizeLimit">Size limit.</param>
        /// <param name="timeLimit">Time limit, in seconds.</param>
        /// <param name="scope">Search scope. Base, single level, or subtree.</param>
        /// <param name="dereferenceAliases">Dereference aliase options.</param>
        /// <param name="filter">Search filter.</param>
        /// <param name="typesOnly">
        /// Specifies whether the search returns only the attribute names without the attribute values.
        /// </param>
        /// <param name="attributes">The attributes to be retrieved.</param>
        /// <returns>The packet that contains the request.</returns>
        internal override AdtsSearchRequestPacket CreateSearchRequest(
            AdtsLdapContext context,
            string dn,
            long sizeLimit,
            long timeLimit,
            MsLdap.SearchScope scope,
            MsLdap.DereferenceAlias dereferenceAliases,
            Asn1Choice filter,
            bool typesOnly,
            params string[] attributes)
        {
            int length = (attributes != null) ? attributes.Length : 0;

            AttributeType[] attributeTypeArray = new AttributeType[length];
            for (int i = 0; i < length; i++)
            {
                attributeTypeArray[i] = new AttributeType(attributes[i]);
            }
            Asn1SequenceOf <AttributeType> attributeList = new Asn1SequenceOf <AttributeType>(attributeTypeArray);

            SearchRequest searchRequest = new SearchRequest(
                new LDAPDN(dn ?? string.Empty),
                new SearchRequest_scope((long)scope),
                new SearchRequest_derefAliases((long)dereferenceAliases),
                new Asn1Integer(sizeLimit),
                new Asn1Integer(timeLimit),
                new Asn1Boolean(typesOnly),
                (Filter)filter,
                attributeList);

            LDAPMessage_protocolOp operation = new LDAPMessage_protocolOp();

            operation.SetData(LDAPMessage_protocolOp.searchRequest, searchRequest);

            LDAPMessage             message = new LDAPMessage(new MessageID(context.MessageId), operation);
            AdtsSearchRequestPacket packet  = new AdtsSearchRequestPacket();

            packet.ldapMessagev2 = message;
            packet.messageId     = context.MessageId;

            return(packet);
        }
Example #13
0
        public static object[] GetAttributeValuesOfType(
            DsServer dc,
            string dn,
            string attributeName,
            string ldapFilter,
            System.DirectoryServices.Protocols.SearchScope searchScope,
            Type valuesType)
        {
            SearchResultEntryCollection results = null;
            ResultCode ret = Search(
                dc,
                dn,
                ldapFilter,
                searchScope,
                new string[] { attributeName },
                out results);

            if (ret != ResultCode.Success)
            {
                return(null);
            }

            foreach (SearchResultEntry e in results)
            {
                DirectoryAttribute attr = e.Attributes[attributeName];
                if (attr == null)
                {
                    return(null);
                }
                else
                {
                    return(attr.GetValues(valuesType));
                }
            }

            return(null);
        }
Example #14
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;
                }
            }
        }
Example #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;
                }
            }
        }
 /// <summary>
 /// Retrieve Object with attributes is to retrieve server Object Variables.
 /// </summary>
 /// <param name="distinguishedName"> ServerDistinguished Name</param>
 /// <param name="serverName">Server Name</param>
 /// <param name="ldapFilter">Fileter String</param>
 /// <param name="attributes">Attributes to be queried</param>
 /// <param name="scope">Search Scope</param>
 /// <param name="searchResponse">Search Response</param>
 /// <returns></returns>
 public void RetrieveObjectwithattributes(string distinguishedName, string serverName, string ldapFilter, string[] attributes, System.DirectoryServices.Protocols.SearchScope scope, out System.DirectoryServices.Protocols.SearchResponse searchResponse)
 {
     using (LdapConnection serverConnection = new LdapConnection(serverName))
     {
         serverConnection.AuthType = AuthType.Basic;
         serverConnection.SessionOptions.ProtocolVersion = 3;
         serverConnection.Bind(new System.Net.NetworkCredential(ConfigStore.DomainNetbiosName + "\\" + ConfigStore.AdminName, ConfigStore.AdminPassword));
         int                      pageSize       = 3000;
         SearchRequest            searchRequest  = new SearchRequest(distinguishedName, ldapFilter, scope, attributes);
         PageResultRequestControl requestControl = new PageResultRequestControl(pageSize);
         searchRequest.Controls.Add(requestControl);
         searchResponse = (SearchResponse)serverConnection.SendRequest(searchRequest);
     }
 }
Example #17
0
        private List <LdapObj> SearchDn(String baseDn, String ldapFilter, System.DirectoryServices.Protocols.SearchScope scope, String[] attribs)
        {
            List <LdapObj> lstLdapObj = null;

            try
            {
                if (!bindingSuccess)
                {
                    Connect();
                }
                if (attribs != null)
                {
                    for (int i = 0; i < attribs.Length; i++)
                    {
                        attribs[i] = attribs[i].Trim();
                    }
                }
                SearchRequest request;
                if (attribs == null)
                {
                    request = new SearchRequest(baseDn, ldapFilter, scope);
                }
                else
                {
                    request = new SearchRequest(baseDn, ldapFilter, scope, attribs);
                }

                SearchResponse result = (SearchResponse)ldapConnexion.SendRequest(request);
                if ((result != null) && result.Entries.Count > 0)
                {
                    lstLdapObj = new List <LdapObj>();

                    foreach (SearchResultEntry sResult in result.Entries)
                    {
                        String  dn      = sResult.DistinguishedName;
                        LdapObj ldapObj = new LdapObj(dn);
                        if (attribs != null)
                        {
                            foreach (String attr in attribs)
                            {
                                ldapObj.AddLdapAttribut(new LdapAttribut(attr));
                            }
                        }

                        foreach (DirectoryAttribute attribute in sResult.Attributes.Values)
                        {
                            /*Console.WriteLine(attribute.Name + " ==> " + attribute.Count);
                             * if (attribute.Name.Equals("objectClass"))
                             *  Console.WriteLine(attribute.Name + " ==> " + attribute.Count);
                             */
                            LdapAttribut ldapAttribut = new LdapAttribut(attribute.Name);
                            ldapAttribut.AddRange((byte[][])attribute.GetValues(typeof(byte[])));
                            ldapObj.AddLdapAttribut(ldapAttribut);
                        }
                        lstLdapObj.Add(ldapObj);
                    }
                }
                return(lstLdapObj);
            }
            catch (LdapException ex)
            {
                Console.WriteLine(String.Format("Error LdapException FindPeDateMajCert {0}...", ex.Message));
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
            catch (DirectoryOperationException ex)
            {
                Console.WriteLine(String.Format("Error DirectoryOperationException FindPeDateMajCert {0}...", ex.Message));
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error Exception FindPeDateMajCert {0}...", ex.Message));
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }
Example #18
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;
            }
        }
Example #19
0
        public IEnumerable <LdapObject> Search(string searchFilter, SearchScope scope, params string[] attributes)
        {
            var baseDN = !String.IsNullOrEmpty(Options.BindBaseDN) ? Options.BindBaseDN : GetDefaultNamingContext();

            return(Search(baseDN, searchFilter, scope, attributes));
        }
Example #20
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();
                }
            }
        }
Example #21
0
        internal static IEnumerable <SearchResultEntry> GetResponses(string dn, string filter, SearchScope scope, string[] attrsToReturn, bool useGC = false)
        {
            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);

            while (true)
            {
                SearchResponse response;

                try
                {
                    response = (SearchResponse)connection.SendRequest(request);
                }
                catch (Exception e)
                {
                    //Console.WriteLine(e.StackTrace);
                    Console.WriteLine("[X] ERROR: {0}", e.Message);
                    yield break;
                }

                if (response.Controls.Length != 1 || !(response.Controls[0] is PageResultResponseControl))
                {
                    Console.WriteLine("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);

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

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

                pageReqControl.Cookie = pageResControl.Cookie;
            }
        }
Example #22
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;
 }
Example #23
0
        private static SearchRequest GetRequest(string dn, string filter, string[] returnAttrs, SearchScope scope = SearchScope.Subtree)
        {
            var request = new SearchRequest(dn, filter, scope, returnAttrs);

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

            var searchControl = new SearchOptionsControl(SearchOption.DomainScope);

            //To retrieve nTSecurityDescriptor attribute https://github.com/BloodHoundAD/SharpHound3/blob/master/SharpHound3/DirectorySearch.cs#L157
            var securityDescriptorFlagControl = new SecurityDescriptorFlagControl
            {
                SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
            };

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

            return(request);
        }
Example #24
0
        public bool Exists(string searchFilter, SearchScope scope = SearchScope.Subtree)
        {
            var found = Search(searchFilter, scope, "distinguishedName");

            return(found.Any());
        }
Example #25
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;
            }
        }
Example #26
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;
            }
        }