Exemplo n.º 1
0
        public static uint[] GetResourceGroupIds(string domainName, NetworkCredential cred, uint resourceGroupCount, Group[] resourceGroups)
        {
            LdapConnection connection = new LdapConnection(domainName);

            connection.Credential = cred;
            uint[] rid = new uint[resourceGroupCount];

            for (int i = 0; i < resourceGroupCount; i++)
            {
                string         dn             = GetDomainDnFromDomainName(domainName);
                string         targetOu       = dn;
                string         filter         = "cn=" + resourceGroups[i].GroupName;
                SearchRequest  searchRequest  = new SearchRequest(targetOu, filter, SearchScope.Subtree, "objectSid");
                SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                if (searchResponse.Entries.Count > 1)
                {
                    throw new Exception("There are more than one entries with the same resourceGroupName.");
                }
                SearchResultAttributeCollection groupAttributes = searchResponse.Entries[0].Attributes;
                string[] tmp = GetobjectSid(groupAttributes).Split('-');
                rid[i] = Convert.ToUInt32(tmp[tmp.Length - 1]);
            }

            return(rid);
        }
Exemplo n.º 2
0
        private SearchResultAttributeCollection GetLdapAttributes(SafeHandle ld, IntPtr entry, ref IntPtr ber)
        {
            var attributes = new SearchResultAttributeCollection();

            for (var attr = Native.ldap_first_attribute(ld, entry, ref ber);
                 attr != IntPtr.Zero;
                 attr = Native.ldap_next_attribute(ld, entry, ber))
            {
                var vals = Native.ldap_get_values_len(ld, entry, attr);
                if (vals != IntPtr.Zero)
                {
                    var attrName = Encoder.Instance.PtrToString(attr);
                    if (attrName != null)
                    {
                        var directoryAttribute = new DirectoryAttribute
                        {
                            Name = attrName
                        };
                        directoryAttribute.AddValues(MarshalUtils.BerValArrayToByteArrays(vals));
                        attributes.Add(directoryAttribute);
                    }
                    Native.ldap_value_free_len(vals);
                }

                Native.ldap_memfree(attr);
            }

            return(attributes);
        }
Exemplo n.º 3
0
        public static string GetDomainFunctionalLevel(string domainName, string domainAdminName, string domainAdminPwd)
        {
            LdapConnection    connection = new LdapConnection(domainName);
            NetworkCredential cred       = new NetworkCredential(domainAdminName, domainAdminPwd, domainName);

            connection.Credential = cred;
            string attributeName = "domainControllerFunctionality";

            string attributeValue = null;

            object[] attribute = null;
            try
            {
                SearchRequest  searchRequest  = new SearchRequest(null, "(objectClass=*)", SearchScope.Base, attributeName);
                SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                attribute = attributes[attributeName].GetValues(typeof(string));
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to query Domain Controller Functionality.", ex);
            }

            if (attribute.Length > 1)
            {
                throw new Exception("Attribute has more than one entry.");
            }
            attributeValue = Convert.ToString(attribute[0]);

            return(attributeValue);
        }
        public string GetDFSRFilters(int contentId, string filterString)
        {
            String fileType = null;

            using (LdapConnection connection = new LdapConnection(ConfigStore.SutLdapAddress))
            {
                connection.AuthType = AuthType.Basic;
                connection.Bind(new System.Net.NetworkCredential(ConfigStore.DomainNetbiosName + "\\" + ConfigStore.AdminName, ConfigStore.AdminPassword));
                SearchRequest  request  = new SearchRequest(typeof(ConfigStore).GetField("ContentId" + contentId.ToString()).GetValue(null).ToString(), "(objectClass=msDFSR-ContentSet)", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { filterString });
                SearchResponse response = (SearchResponse)connection.SendRequest(request);
                foreach (SearchResultEntry entry in response.Entries)
                {
                    SearchResultAttributeCollection attributeCollection = entry.Attributes;
                    foreach (DirectoryAttribute attribute in attributeCollection.Values)
                    {
                        for (int j = 0; j < attribute.Count; j++)
                        {
                            //If Attribute is string type
                            if (attribute[j] is string)
                            {
                                fileType = attribute[j].ToString();
                            }
                        }
                    }
                }
            }
            return(fileType);
        }
        /// <summary>
        /// This method is used to get attribute display name of an account
        /// </summary>
        /// <param name="domainName">Local domain Name</param>
        /// <param name="accountName">Account name, user name or computer name</param>
        /// <param name="accountType">Users or computers</param>
        /// <param name="attributename">The attribute of account to query</param>
        /// <param name="adminName">Admin user Name</param>
        /// <param name="adminPwd">Admin password</param>
        public string getAccountAttributeDN(string domainName, string accountName, string accountType, string attributeName, string adminName, string adminPwd)
        {
            LdapConnection    connection = new LdapConnection(domainName);
            NetworkCredential cred       = new NetworkCredential(adminName, adminPwd, domainName);

            connection.Credential = cred;
            string dn       = PacHelper.GetDomainDnFromDomainName(domainName);
            string targetOu = "CN=" + accountName + ",CN=" + accountType + ",DC=" + domainName + ",DC=com";

            string filter = "CN=" + accountName;

            string[] attributesToReturn = new string[] { attributeName };

            SearchRequest  searchRequest  = null;
            SearchResponse searchResponse = null;
            string         attributeValue = null;

            try
            {
                searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);

                searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                object attribute = null;
                attribute      = PacHelper.getAttributeValue(attributes, attributeName);
                attributeValue = Convert.ToString(attribute);
            }
            catch
            {
                throw new InvalidOperationException("Request attribute failed with targetOU: " + targetOu + ", filter: " + filter + ", attribute: " + attributeName);
            }

            return(attributeValue);
        }
Exemplo n.º 6
0
        public static uint[] GetDomainSid(string domainName, NetworkCredential cred)
        {
            LdapConnection connection = new LdapConnection(domainName);

            connection.Credential = cred;
            string         dn             = GetDomainDnFromDomainName(domainName);
            string         filter         = "(objectClass=*)";
            SearchRequest  searchRequest  = new SearchRequest(dn, filter, SearchScope.Base, "objectSid");
            SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);

            if (searchResponse.Entries.Count > 1)
            {
                throw new Exception("There are more than one entries with the same domain distinguishedName.");
            }
            SearchResultAttributeCollection domainObjAttributes = searchResponse.Entries[0].Attributes;

            string[] tmp       = GetobjectSid(domainObjAttributes).Split('-');
            uint[]   domainSid = new uint[tmp.Length - 3];
            for (int i = 0; i < tmp.Length - 3; i++)
            {
                domainSid[i] = Convert.ToUInt32(tmp[i + 3]);
            }

            return(domainSid);
        }
Exemplo n.º 7
0
        SearchResultAttributeCollection getAttributes(LdapConnection con, string dn, string[] attributes)
        {
            SearchRequest  req = null;
            SearchResponse res = null;
            SearchResultAttributeCollection ret = null;

            try
            {
                req = new SearchRequest(
                    dn,
                    "(objectclass=*)",
                    System.DirectoryServices.Protocols.SearchScope.Base,
                    attributes);

                res = (SearchResponse)con.SendRequest(req);
                if (res.Entries.Count == 0)
                {
                    errors.Add("Failed to query object " + dn);
                }
            }
            catch (Exception e)
            {
                errors.Add("Failed to get attributes from object " + dn + ", error info: " + e.Message);
            }
            return(ret);
        }
Exemplo n.º 8
0
        public static string GetDCAttribute(string computerName, string attributeName, string domainName, string domainAdminName, string domainAdminPwd)
        {
            LdapConnection    connection = new LdapConnection(domainName);
            NetworkCredential cred       = new NetworkCredential(domainAdminName, domainAdminPwd, domainName);

            connection.Credential = cred;

            //get domain DN name
            string[]      domainDn = domainName.Split('.');
            StringBuilder sb       = new StringBuilder();

            for (int i = 0; i < domainDn.Length; i++)
            {
                sb.Append("dc=");
                sb.Append(domainDn[i]);
                if (i != domainDn.Length - 1)
                {
                    sb.Append(",");
                }
            }
            string dn       = sb.ToString();
            string targetOu = "OU=Domain Controllers," + dn;
            string filter   = "CN=" + computerName;

            string[] attributesToReturn = new string[] { attributeName };

            SearchRequest  searchRequest  = null;
            SearchResponse searchResponse = null;
            string         attributeValue = null;

            try
            {
                searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);

                searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                object[] attribute = null;

                try
                {
                    attribute = attributes[attributeName].GetValues(Type.GetType("System.String"));
                }
                catch
                {
                    return(null);
                }
                if (attribute.Length > 1)
                {
                    throw new Exception("Attribute has more than one entry.");
                }

                attributeValue = Convert.ToString(attribute[0]);
            }
            catch (Exception ex)
            {
                throw new Exception("Requst attribute failed with targetOU: " + targetOu + ", filter: " + filter + ", attribute: " + attributeName + ". " + ex.Message);
            }

            return(attributeValue);
        }
Exemplo n.º 9
0
        public static uint[] GetGroupIds(SearchResultAttributeCollection attributes, string domainName, NetworkCredential cred)
        {
            LdapConnection connection = new LdapConnection(domainName);

            connection.Credential = cred;
            int groupCount = attributes["memberOf"].Count + 1;

            uint[] rid = new uint[groupCount];

            //Fix me
            //The built-in groupmembership Domain Users Rid = 513
            rid[0] = 513;
            for (int i = 1; i < groupCount; i++)
            {
                string         dn             = GetDomainDnFromDomainName(domainName);
                string         targetOu       = "cn=Users," + dn;
                string[]       filter         = attributes["memberOf"][i - 1].ToString().Split(',');
                SearchRequest  searchRequest  = new SearchRequest(targetOu, filter[0], SearchScope.Subtree, "objectSid");
                SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                if (searchResponse.Entries.Count > 1)
                {
                    throw new Exception("There are more than one entries with the same groupName.");
                }
                SearchResultAttributeCollection groupAttributes = searchResponse.Entries[0].Attributes;
                string[] tmp = GetobjectSid(groupAttributes).Split('-');
                rid[i] = Convert.ToUInt32(tmp[tmp.Length - 1]);
            }

            return(rid);
        }
Exemplo n.º 10
0
        /// <summary>
        /// This method is used to get an authentication policy TGT life time by policy name and attribute name
        /// If the TGT lifetime is not set, null will return
        /// </summary>
        /// <param name="domainName">Domain Name</param>
        /// <param name="policyname">authentication policy name</param>
        /// <param name="tgtlifetimeattributename">the lifetime attribute name, such as msds-ComputerTGTLifetime, msds-UserTGTLifetime or msds-ServiceTGTLifetime</param>
        /// <param name="adminName">Admin user Name</param>
        /// <param name="adminPwd">Admin password</param>
        public double?getAuthPolicyTGTLifeTime(string domainName, string policyName, string tgtLifetimeAttributeName, string adminName, string adminPwd)
        {
            LdapConnection    connection = new LdapConnection(domainName);
            NetworkCredential cred       = new NetworkCredential(adminName, adminPwd, domainName);

            connection.Credential = cred;
            string dn       = PacHelper.GetDomainDnFromDomainName(domainName);
            string targetOu = "CN=" + policyName + ",CN=AuthN Policies,CN=AuthN Policy Configuration,CN=Services,CN=Configuration,DC=" + domainName + ",DC=com";

            string filter = "CN=" + policyName;

            string[] attributesToReturn = new string[] { tgtLifetimeAttributeName };

            double?        tgtLifeTime    = null;
            SearchRequest  searchRequest  = null;
            SearchResponse searchResponse = null;

            try
            {
                searchRequest  = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);
                searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                object attributeValue = PacHelper.getAttributeValue(attributes, tgtLifetimeAttributeName);
                tgtLifeTime = (double?)Convert.ToDouble(attributeValue);
            }
            catch
            {
                throw new InvalidOperationException("Request attribute failed with targetOU: " + targetOu + ", filter: " + filter + ", attribute: " + tgtLifetimeAttributeName);
            }

            return(tgtLifeTime);
        }
Exemplo n.º 11
0
        /// <summary>
        /// This method is to help enable the compound identity feature on the computer account in the specific domain.
        /// </summary>
        /// <param name="domainName">The domain name of the service principal.</param>
        /// <param name="computerName">The host name of the service principal.</param>
        /// <param name="adminName">Need administrator's credential to modify active directory account.</param>
        /// <param name="adminPwd">Need administrator's credential to modify active directory account.</param>
        public void enableCompId(string domainName, string computerName, string adminName, string adminPwd)
        {
            LdapConnection    connection = new LdapConnection(domainName);
            NetworkCredential cred       = new NetworkCredential(adminName, adminPwd, domainName);

            connection.Credential = cred;
            string dn       = PacHelper.GetDomainDnFromDomainName(domainName);
            string targetOu = "cn=Computers," + dn;

            computerName = computerName.Replace("$", "");
            string filter = "cn=" + computerName;

            string[]      attributesToReturn = new string[] { "msDS-SupportedEncryptionTypes" };
            SearchRequest searchRequest      = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn);

            SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
            SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;

            object attributeValue = null;

            attributeValue = PacHelper.getAttributeValue(attributes, "msDS-SupportedEncryptionTypes");
            uint?supportedEncTypes = (uint?)Convert.ToInt32(attributeValue);

            uint compIdFlag = 131072;

            if ((supportedEncTypes.Value & compIdFlag) != compIdFlag)
            {
                string computerDN = filter + "," + targetOu;
                supportedEncTypes = supportedEncTypes + compIdFlag;
                ModifyRequest  modRequest  = new ModifyRequest(computerDN, DirectoryAttributeOperation.Replace, "msDS-SupportedEncryptionTypes", supportedEncTypes.ToString());
                ModifyResponse modResponse = (ModifyResponse)connection.SendRequest(modRequest);
            }
        }
Exemplo n.º 12
0
        void verifyAttributes(LdapConnection con, string dn, Dictionary <string, string> attributes)
        {
            SearchResultAttributeCollection attrs = getAttributes(
                con,
                dn,
                attributes.Keys.ToArray());

            if (attrs == null)
            {
                return;
            }

            Dictionary <string, string> .Enumerator enumer = attributes.GetEnumerator();
            while (enumer.MoveNext())
            {
                if (!attrs.Contains(enumer.Current.Key) && enumer.Current.Value != null)
                {
                    errors.Add("Failed to find attribute " + enumer.Current.Key + " from object " + dn);
                }
                else
                {
                    string value = attrs[enumer.Current.Key].ToString().ToLower();
                    if (enumer.Current.Value.ToLower() != value)
                    {
                        errors.Add("expected: " + enumer.Current.Value.ToLower() + " , actual: " + value + ", attribute " + enumer.Current.Key + " of object " + dn);
                    }
                }
            }
        }
        public SearchResultAttributeCollectionWrapper(SearchResultAttributeCollection searchResultAttributeCollection)
        {
            if (searchResultAttributeCollection == null)
            {
                throw new ArgumentNullException("searchResultAttributeCollection");
            }

            this._searchResultAttributeCollection = searchResultAttributeCollection;
        }
Exemplo n.º 14
0
        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.º 15
0
        public static string[] GetRootDseValues(this SearchResultAttributeCollection attributes, string name)
        {
            var attribute = attributes[name];

            if (attribute == null)
            {
                throw new AutoDetectionException("Ldap Ping failed, cannot find attribute {0} in RootDSE.", name);
            }
            return(attribute.GetValues(typeof(string)) as string[]);
        }
Exemplo n.º 16
0
        protected string GetAttribute(SearchResultAttributeCollection attributes, string name)
        {
            if (attributes[name] == null)
            {
                return(null);
            }

            string result = attributes[name][0].ToString();

            return(string.IsNullOrEmpty(result) ? null : result);
        }
        public Guid GetNtdsConnectionGuid(string path, string fromServer)
        {
            Guid   guid = Guid.Empty;
            string from = "";

            using (LdapConnection connection = new LdapConnection(ConfigStore.SutLdapAddress))
            {
                connection.AuthType = AuthType.Basic;
                connection.SessionOptions.ProtocolVersion = 3;
                connection.Bind(new System.Net.NetworkCredential(ConfigStore.DomainNetbiosName + "\\" + ConfigStore.AdminName, ConfigStore.AdminPassword));
                SearchRequest  request  = new SearchRequest(path, "(objectclass=ntdsconnection)", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "objectGUID", "fromServer" });
                SearchResponse response = null;
                try
                {
                    response = (SearchResponse)connection.SendRequest(request);
                }
                catch (DirectoryOperationException e)
                {
                    Site.Assume.Fail("Failed to find {0}: {1}", path, e.Message);
                }

                foreach (SearchResultEntry entry in response.Entries)
                {
                    SearchResultAttributeCollection attributeCollection = entry.Attributes;
                    foreach (DirectoryAttribute attribute in attributeCollection.Values)
                    {
                        for (int j = 0; j < attribute.Count; j++)
                        {
                            if (attribute[j] is byte[])
                            {
                                byte[] x = attribute[j] as byte[];
                                guid = new Guid(x);
                            }
                            if (attribute[j] is string)
                            {
                                from = attribute[j].ToString();
                            }
                        }
                        if (0 == string.Compare(from.ToLower(), fromServer.ToLower()))
                        {
                            return(guid);
                        }
                    }
                }
            }
            throw new Exception("Failed to find replication partner's NTDS Connection guid");
        }
Exemplo n.º 18
0
        public void AttributeCollection_CaseInsensitivity()
        {
            var searchCollection = new SearchResultAttributeCollection();
            var modifyCollection = new ModifyAttributeCollection();
            var gnAttr           = new DirectoryAttribute {
                Name = LdapAttributes.GivenName.ToLowerInvariant()
            };
            var modifAttr = new DirectoryModificationAttribute {
                Name = LdapAttributes.GivenName.ToLowerInvariant()
            };

            searchCollection.Add(gnAttr);
            modifyCollection.Add(modifAttr);

            Assert.True(searchCollection.Contains(LdapAttributes.GivenName.ToUpperInvariant()));
            Assert.True(modifyCollection.Contains(LdapAttributes.GivenName.ToUpperInvariant()));
        }
Exemplo n.º 19
0
        /// <summary>
        /// get a bunch of accounts with same type, such as computers, or users at once
        /// </summary>
        /// <param name="accountType"></param>
        /// <param name="domainName"></param>
        /// <param name="domainAdminName"></param>
        /// <param name="domainAdminPwd"></param>
        /// <returns></returns>
        public static string GetAccounts(string accountType, string domainName, string domainAdminName, string domainAdminPwd)
        {
            LdapConnection    connection = new LdapConnection(domainName);
            NetworkCredential cred       = new NetworkCredential(domainAdminName, domainAdminPwd, domainName);

            connection.Credential = cred;

            //get domain DN name
            string[]      domainDn = domainName.Split('.');
            StringBuilder sb       = new StringBuilder();

            for (int i = 0; i < domainDn.Length; i++)
            {
                sb.Append("dc=");
                sb.Append(domainDn[i]);
                if (i != domainDn.Length - 1)
                {
                    sb.Append(",");
                }
            }
            string dn       = sb.ToString();
            string targetOu = "CN=" + accountType + "," + dn;
            //string[] accounts = new string[] { };

            SearchRequest  searchRequest  = null;
            SearchResponse searchResponse = null;
            string         attributeValue = null;
            string         filter         = "CN=*";
            string         attributeName  = "users";

            string[] accounts = new string[] { attributeName };

            try
            {
                searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, accounts);

                searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
            }
            catch (Exception ex)
            {
                throw new Exception("Requst attribute failed with targetOU: " + targetOu + ", filter: " + filter + ", attribute: msDS-Behavior-Version. " + ex.Message);
            }

            return(attributeValue);
        }
Exemplo n.º 20
0
        protected Dictionary <string, string> GetValues(SearchResultAttributeCollection attributes, string name)
        {
            Dictionary <string, string> result = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            if (attributes[name] == null)
            {
                return(result);
            }

            for (int i = 0; i < attributes[name].Count; i++)
            {
                string tmp = attributes[name][i].ToString();
                result.Add(tmp.Substring(3, tmp.IndexOf(",")), tmp);
            }

            return(result);
        }
Exemplo n.º 21
0
        private DirectoryAttribute ReadMultivalueAttribute(string absolutePath, string attributeName)
        {
            SearchRequest request = new SearchRequest(absolutePath, Schema.Query.QueryAll, System.DirectoryServices.Protocols.SearchScope.Base, new string[]
            {
                attributeName
            });
            SearchResponse searchResponse = (SearchResponse)this.SendRequest(request);

            if (searchResponse.Entries.Count > 0)
            {
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                if (attributes.Contains(attributeName))
                {
                    return(attributes[attributeName]);
                }
            }
            return(null);
        }
Exemplo n.º 22
0
        private string GetSearchResultEntryValue(SearchResultEntry entry, string attributeName)
        {
            SearchResultAttributeCollection attributes = entry.Attributes;

            if (!attributes.Contains(attributeName))
            {
                return(null);
            }

            try
            {
                return(string.Join(",", attributes[attributeName].GetValues(typeof(string))));
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 23
0
        public static long?GetAttributeFileTime(SearchResultAttributeCollection attributes, string attrName)
        {
            object[] obj = null;
            try
            {
                obj = attributes[attrName].GetValues(Type.GetType("System.String"));
            }
            catch
            {
                return(null);
            }
            if (obj.Length > 1)
            {
                throw new Exception("Attribute has more than one entry.");
            }

            return(Convert.ToInt64(obj[0]));
        }
Exemplo n.º 24
0
        public static ushort?GetAttributeUshort(SearchResultAttributeCollection attributes, string attrName)
        {
            object[] obj = null;
            try
            {
                obj = attributes[attrName].GetValues(Type.GetType("System.String"));
            }
            catch
            {
                //unable to get attrName attribute, value unset
                return(null);
            }
            if (obj.Length > 1)
            {
                throw new Exception("Attribute has more than one entry.");
            }

            return(Convert.ToUInt16(obj[0]));
        }
Exemplo n.º 25
0
        public void AdjustAttributesToDisplay(SearchResultAttributeCollection attributeList, bool doValRangeRetrieval)
        {
            CurrentAttributesToDisplay.Clear();
            CurrentRangeRetrieval.Clear();

            if (Attributes != null)
            {
                foreach (string name in Attributes)
                {
                    CurrentAttributesToDisplay.AddSafe <string, short>(name, 0);
                }
            }

            foreach (string name in attributeList.AttributeNames)
            {
                string attribName = null;
                int    lowval = 0;  int maxval = 0;

                if (name.IsRangeAttribute(out attribName, out lowval, out maxval))
                {
                    CurrentRangeRetrieval.Add(attribName, new RangeInfo(lowval, maxval, name, attribName));

                    RangeRetrievalAlerts.AddSafe <string>(name);

                    if (!doValRangeRetrieval)
                    {
                        CurrentAttributesToDisplay.AddSafe <string, short>(name, 0);
                    }
                }

                else
                {
                    CurrentAttributesToDisplay.AddSafe <string, short>(name, 0);
                }
            }

            foreach (string name in CurrentRangeRetrieval.Keys)
            {
                CurrentAttributesToDisplay.RemoveSafe <string, short>(name);
            }

            CurrentAttributesToDisplay = CurrentAttributesToDisplay.OrderByKeySafe();
        }
Exemplo n.º 26
0
        public static string GetobjectSid(SearchResultAttributeCollection attributes)
        {
            object[] obj = null;
            try
            {
                obj = attributes["objectSid"].GetValues(Type.GetType("System.Byte[]"));
            }
            catch
            {
                //unable to get objectSid attribute, value unset
                return(null);
            }
            if (obj.Length > 1)
            {
                throw new Exception("objectSid has more than one entry.");
            }

            SecurityIdentifier objectSid = new SecurityIdentifier((byte[])obj[0], 0);

            return(objectSid.ToString());
        }
Exemplo n.º 27
0
        public static KERB_SID_AND_ATTRIBUTES[] GetResourceGroupExtraSids(string domainName, NetworkCredential cred, uint resourceGroupCount, Group[] resourceGroups)
        {
            LdapConnection connection = new LdapConnection(domainName);

            connection.Credential = cred;
            KERB_SID_AND_ATTRIBUTES[] resourceGroupExtraSids = new KERB_SID_AND_ATTRIBUTES[resourceGroupCount];

            for (int i = 0; i < resourceGroupCount; i++)
            {
                string         dn             = GetDomainDnFromDomainName(domainName);
                string         targetOu       = dn;
                string         filter         = "cn=" + resourceGroups[i].GroupName;
                SearchRequest  searchRequest  = new SearchRequest(targetOu, filter, SearchScope.Subtree, "objectSid");
                SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                if (searchResponse.Entries.Count > 1)
                {
                    throw new Exception("There are more than one entries with the same resourceGroupName.");
                }
                SearchResultAttributeCollection groupAttributes = searchResponse.Entries[0].Attributes;
                string[] tmp = GetobjectSid(groupAttributes).Split('-');

                _RPC_SID resourceGroupSid = new _RPC_SID();
                resourceGroupSid.Revision                  = 0x01;
                resourceGroupSid.IdentifierAuthority       = new _RPC_SID_IDENTIFIER_AUTHORITY();
                resourceGroupSid.IdentifierAuthority.Value = new byte[] { 0, 0, 0, 0, 0, 5 };
                resourceGroupSid.SubAuthorityCount         = Convert.ToByte(tmp.Length - 3);
                resourceGroupSid.SubAuthority              = new uint[tmp.Length - 3];
                for (int j = 3; j < tmp.Length; j++)
                {
                    resourceGroupSid.SubAuthority[j - 3] = Convert.ToUInt32(tmp[j]);
                }

                resourceGroupExtraSids[i]            = new KERB_SID_AND_ATTRIBUTES();
                resourceGroupExtraSids[i].Attributes = Attributes_Values.Mandatory | Attributes_Values.EnabledByDefault | Attributes_Values.Enabled | Attributes_Values.Resource;
                resourceGroupExtraSids[i].SID        = new _RPC_SID[1];
                resourceGroupExtraSids[i].SID[0]     = resourceGroupSid;
            }
            return(resourceGroupExtraSids);
        }
Exemplo n.º 28
0
        public void SetUp()
        {
            _guidBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            _siBytes   = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 };
            var strings = new[] { "one", "two", "three", "four" };

            _byteArrays = new[] { _guidBytes, _siBytes };

            _collection =
                typeof(SearchResultAttributeCollection).Create <SearchResultAttributeCollection>();
            _collection
            .Call("Add", new object[] { "Property1", new DirectoryAttribute("Property1", "prop1") });
            _collection
            .Call("Add", new object[] { "Property2", new DirectoryAttribute("Property2", "2") });
            _collection
            .Call("Add", new object[] { "Property3", new DirectoryAttribute("Property3", _guidBytes) });
            _collection
            .Call("Add", new object[] { "Property4", new DirectoryAttribute("Property4", strings) });
            _collection
            .Call("Add", new object[] { "Property5", new DirectoryAttribute("Property5", _siBytes) });
            _collection
            .Call("Add", new object[] { "Property6", new DirectoryAttribute("Property6", "TRUE") });
            _collection
            .Call("Add", new object[] { "Property7", new DirectoryAttribute("Property7", "20110313064859.0Z") });
            _collection
            .Call("Add", new object[] { "Property8", new DirectoryAttribute("Property8", "129444725394225946") });
            _collection
            .Call("Add", new object[] { "Property9", new DirectoryAttribute("Property9", "20110313064859Z") });
            _collection
            .Call("Add", new object[] { "Property10", new DirectoryAttribute("Property10", _byteArrays) });
            _collection
            .Call("Add", new object[] { "Property11", new DirectoryAttribute("Property10", Resources.ResourceHelper.GetAssemblyResource(@"Resources\cert.cer")) });

            _entry =
                typeof(SearchResultEntry).Create <SearchResultEntry>(
                    new object[] { "theDn", _collection });

            _attributes = new DirectoryAttributes(_entry);
        }
        /// <summary>
        /// Adavalidation method is used to Validate AD related Requiremnts.
        /// This method compares boolean type attribute values of the specified object
        /// </summary>
        /// <param name="GuidString">Distinguished Name</param>
        /// <param name="GuidClass">ladpFilter</param>
        /// <param name="refString">Attribute</param>
        /// <param name="comparreValue">ExprectedValue</param>
        /// <returns></returns>

        public bool AdValidation(String GuidString, string GuidClass, string refString, bool comparreValue)
        {
            if (GuidString == null)
            {
                return(false);
            }
            using (LdapConnection connection = new LdapConnection(ConfigStore.DomainDnsName))
            {
                connection.AuthType = AuthType.Basic;
                connection.Bind(new System.Net.NetworkCredential(ConfigStore.AdminName, ConfigStore.AdminPassword, ConfigStore.DomainNetbiosName));
                bool           flag     = false;
                SearchRequest  request  = new SearchRequest(GuidString, GuidClass, System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { refString });
                SearchResponse response = (SearchResponse)connection.SendRequest(request);
                Guid           guid     = Guid.Empty;
                foreach (SearchResultEntry entry in response.Entries)
                {
                    SearchResultAttributeCollection attributeCollection = entry.Attributes;
                    foreach (DirectoryAttribute attribute in attributeCollection.Values)
                    {
                        for (int j = 0; j < attribute.Count; j++)
                        {
                            if (attribute[j] is string)
                            {
                                bool attvalue = Convert.ToBoolean(attribute[j]);
                                if (attvalue == comparreValue)
                                {
                                    return(true);
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                }
                return(flag);
            }
        }
Exemplo n.º 30
0
        private object ReadSingleObjectAttribute(string absolutePath, string attributeName, params DirectoryControl[] controls)
        {
            SearchRequest searchRequest = new SearchRequest(absolutePath, Schema.Query.QueryAll, System.DirectoryServices.Protocols.SearchScope.Base, new string[]
            {
                attributeName
            });

            foreach (DirectoryControl control in controls)
            {
                searchRequest.Controls.Add(control);
            }
            SearchResponse searchResponse = (SearchResponse)this.SendRequest(searchRequest);

            if (searchResponse.Entries.Count > 0)
            {
                SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes;
                if (attributes.Contains(attributeName))
                {
                    return(attributes[attributeName][0]);
                }
            }
            return(null);
        }