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);
            }
        }
Пример #2
0
		private void AddResult(SearchResponse partialResults, SearchResponse newResult)
		{
			if (newResult != null)
			{
				if (newResult.Entries != null)
				{
					for (int i = 0; i < newResult.Entries.Count; i++)
					{
						partialResults.Entries.Add(newResult.Entries[i]);
					}
				}
				if (newResult.References != null)
				{
					for (int j = 0; j < newResult.References.Count; j++)
					{
						partialResults.References.Add(newResult.References[j]);
					}
				}
				return;
			}
			else
			{
				return;
			}
		}
Пример #3
0
        /// <summary>
        /// This method get the search respose and return a list of users
        /// 
        /// NOT TESTED: Because it's difficult to mockup the SearchResponse Obj
        /// </summary>
        /// <param name="searchResponse"></param>
        /// <returns></returns>
        public static List<ILdapUser> ConvertToLdapUsers(SearchResponse searchResponse)
        {
            var searchResult = new List<ILdapUser>();

            if (searchResponse == null) return searchResult;

            searchResult.AddRange(from SearchResultEntry userReturn in searchResponse.Entries select ConvertToLdapUser(userReturn));

            return searchResult;
        }
        public void LDAP_Search_ConstructedAttributes_isUserCachableAtRodc()
        {
            if (string.IsNullOrWhiteSpace(AD_LDAPModelAdapter.Instance(Site).RODCNetbiosName))
            {
                BaseTestSite.Assert.Fail("Test case requires a RODC but \"RODCName\" ptfconfig property value is invalid");
            }

            #region variables

            string RODCName = AD_LDAPModelAdapter.Instance(Site).RODCNetbiosName;
            string RODCDN   = "CN=" + RODCName + ",OU=Domain Controllers," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            //Let D be the DN of the user principal specified using LDAP Control LDAP_SERVER_DN_INPUT_OID.
            //If the DN of a security principal is not explicitly specified, D is the DN of the current requester.
            string userName   = AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName;
            string userDN     = "CN=" + userName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            bool   isCachable = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(AD_LDAPModelAdapter.Instance(Site).PDCIPAddress),
                                                    new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                                          AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                                          AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region search with LDAP_SERVER_DN_INPUT_OID

            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                RODCDN,
                "(objectClass=computer)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "msDS-isUserCachableAtRodc");
            //Let D be the DN of the user principal specified using LDAP Control LDAP_SERVER_DN_INPUT_OID.
            //If the DN of a security principal is not explicitly specified, D is the DN of the current requester.
            System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            DirectoryAttribute attr   = searchRep.Entries[0].Attributes["msDS-isUserCachableAtRodc"];
            object[]           values = attr.GetValues(Type.GetType("System.String"));
            isCachable = Convert.ToBoolean(Convert.ToInt16(values[0].ToString(), CultureInfo.InvariantCulture));

            //Get expected result by GetRevealSecretsPolicyForUser(TO!distinguishedName, D) defined in MS-DRSR section 4.1.10.5.14
            bool expectedCachable = GetRevealSecretsPolicyForUser(RODCDN, userDN);

            BaseTestSite.Assert.AreEqual(
                expectedCachable,
                isCachable,
                @"TO!msDS-IsUserCachableAtRodc = GetRevealSecretsPolicyForUser(TO!distinguishedName, D) (procedure GetRevealSecretsPolicyForUser is defined in [MS-DRSR] section 4.1.10.5.14).");

            #endregion
        }
Пример #5
0
        /// <summary>
        /// read msDS-ClaimValueType of a claim from DC
        /// </summary>
        /// <param name="dn">Distinguished Name of claim</param>
        /// <param name="server">DC name or address</param>
        /// <returns>CLAIM_TYPE</returns>
        CLAIM_TYPE getClaimValueType(string dn, string server)
        {
            using (System.DirectoryServices.Protocols.LdapConnection con = new System.DirectoryServices.Protocols.LdapConnection(server))
            {
                System.DirectoryServices.Protocols.SearchRequest req = new System.DirectoryServices.Protocols.SearchRequest(
                    dn,
                    "(objectclass=*)",
                    System.DirectoryServices.Protocols.SearchScope.Base,
                    new string[] { ConstValue.msDSClaimValueType });

                System.DirectoryServices.Protocols.SearchResponse res = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(req);

                object o = res.Entries[0].Attributes[ConstValue.msDSClaimValueType][0];

                return((CLAIM_TYPE)Enum.Parse(typeof(CLAIM_TYPE), o.ToString()));
            }
        }
Пример #6
0
        public static List<DirectoryUser> GetUsersFromResponse(SearchResponse sResponse)
        {
            var users = new List<DirectoryUser>();

            foreach (SearchResultEntry result in sResponse.Entries)
            {
                var user = new DirectoryUser();

                //Grab out the first response entry

                foreach (DirectoryAttribute attr in result.Attributes.Values)
                {
                    switch (attr.Name)
                    {
                        case STR_UID:
                            user.LoginId = attr[0].ToString();
                            break;
                        case STR_GivenName:
                            user.FirstName = attr[0].ToString();
                            break;
                        case STR_SN:
                            user.LastName = attr[0].ToString();
                            break;
                        case STR_Mail:
                            user.EmailAddress = attr[0].ToString();
                            break;
                        case STR_EmployeeNumber:
                            user.EmployeeId = attr[0].ToString();
                            break;
                        case STR_CN:
                            user.FullName = attr[0].ToString();
                            break;
                        case STR_Telephone:
                            user.PhoneNumber = attr[0].ToString();
                            break;
                        default:
                            break;
                    }
                }

                users.Add(user);
            }

            return users;
        }
Пример #7
0
        public void SamrDeleteUser_WithChildObject()
        {
            ConnectAndOpenDomain(_samrProtocolAdapter.pdcFqdn, _samrProtocolAdapter.PrimaryDomainDnsName, out _serverHandle, out _domainHandle);

            LdapConnection con = new LdapConnection(
                new LdapDirectoryIdentifier(_samrProtocolAdapter.PDCIPAddress, int.Parse(_samrProtocolAdapter.ADDSPortNum)),
                new NetworkCredential(_samrProtocolAdapter.DomainAdministratorName,
                                      _samrProtocolAdapter.DomainUserPassword, _samrProtocolAdapter.PrimaryDomainDnsName));

            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;
            string treeRootDN = "CN=testRootDN," + _samrProtocolAdapter.primaryDomainUserContainerDN;
            string treeEntry1 = "CN=testEntry1," + treeRootDN;

            try
            {
                Site.Log.Add(LogEntryKind.TestStep, "Add test user with child object.");
                ManagedAddRequest add = new ManagedAddRequest(treeRootDN, "user");
                System.DirectoryServices.Protocols.AddResponse response = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(add);
                add      = new ManagedAddRequest(treeEntry1, "classStore");
                response = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(add);

                System.DirectoryServices.Protocols.SearchRequest  searchreq  = new System.DirectoryServices.Protocols.SearchRequest(treeRootDN, "(ObjectClass=*)", System.DirectoryServices.Protocols.SearchScope.Base);
                System.DirectoryServices.Protocols.SearchResponse searchresp = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchreq);

                byte[]             values   = (byte[])searchresp.Entries[0].Attributes["objectSid"].GetValues(Type.GetType("System.Byte[]"))[0];
                SecurityIdentifier Sid      = new SecurityIdentifier(values, 0);
                string[]           sidArray = Sid.ToString().Split('-');
                string             rid      = sidArray[sidArray.Length - 1];
                Site.Log.Add(LogEntryKind.TestStep, "SamrOpenUser: obtain the handle to the created user.");
                HRESULT result = _samrProtocolAdapter.SamrOpenUser(_domainHandle, (uint)User_ACCESS_MASK.USER_ALL_ACCESS, uint.Parse(rid), out _userHandle);


                Site.Log.Add(LogEntryKind.TestStep, "SamrDeleteUser: delete the created user.");
                result = _samrProtocolAdapter.SamrDeleteUser(ref _userHandle);
                Site.Assert.AreNotEqual(HRESULT.STATUS_SUCCESS, result, "3.1.5.7.3 In the DC configuration, if U is a parent to another object, an error MUST be returned.");
            }
            finally
            {
                System.DirectoryServices.Protocols.DeleteRequest     delreq      = new System.DirectoryServices.Protocols.DeleteRequest(treeRootDN);
                System.DirectoryServices.Protocols.TreeDeleteControl treeDelCtrl = new TreeDeleteControl();
                delreq.Controls.Add(treeDelCtrl);
                System.DirectoryServices.Protocols.DeleteResponse delresp = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delreq);
            }
        }
Пример #8
0
        private void AddResult(SearchResponse partialResults, SearchResponse newResult)
        {
            if (newResult == null)
            {
                return;
            }

            if (newResult.Entries != null)
            {
                for (int i = 0; i < newResult.Entries.Count; i++)
                {
                    partialResults.Entries.Add(newResult.Entries[i]);
                }
            }

            if (newResult.References != null)
            {
                for (int i = 0; i < newResult.References.Count; i++)
                {
                    partialResults.References.Add(newResult.References[i]);
                }
            }
        }
        public void LDAP_Search_SD_Flags_Control()
        {
            #region variables

            string testUser   = "******";
            string testUserDN = "CN=" + testUser + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            bool   isExist    = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            string         addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress;
            string         port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum;
            LdapConnection con  = new LdapConnection(new LdapDirectoryIdentifier(addr, int.Parse(port)),
                                                     new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                                           AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                                           AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region Add an object for search testing

            if (!Utilities.IsObjectExist(testUserDN, addr, port))
            {
                ManagedAddRequest addReq = new ManagedAddRequest(testUserDN, "user");
                System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }

            #endregion

            #region with SD FLags Control

            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                testUserDN,
                "(objectClass=user)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "ntSecurityDescriptor");
            System.DirectoryServices.Protocols.SecurityDescriptorFlagControl sdFlagsCtrl = new System.DirectoryServices.Protocols.SecurityDescriptorFlagControl(
                System.DirectoryServices.Protocols.SecurityMasks.Owner);
            searchReq.Controls.Add(sdFlagsCtrl);
            System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            DirectoryAttribute attr   = searchRep.Entries[0].Attributes["ntSecurityDescriptor"];
            object[]           values = attr.GetValues(Type.GetType("System.String"));
            if (values != null)
            {
                isExist = true;
            }
            BaseTestSite.Assert.IsTrue(
                isExist,
                @"If the LDAP_SERVER_SD_FLAGS_OID control is present in an LDAP search request, the server returns an SD with the parts specified in the control
                when the SD attribute name is explicitly mentioned in the requested attribute list.");

            isExist = false;
            searchReq.Attributes.Clear();
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["ntSecurityDescriptor"];
            values    = attr.GetValues(Type.GetType("System.String"));
            if (values != null)
            {
                isExist = true;
            }
            BaseTestSite.Assert.IsTrue(
                isExist,
                @"If the LDAP_SERVER_SD_FLAGS_OID control is present in an LDAP search request, the server returns an SD with the parts specified in the control
                when the requested attribute list is empty.");

            isExist = false;
            searchReq.Attributes.Add("*");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["ntSecurityDescriptor"];
            values    = attr.GetValues(Type.GetType("System.String"));
            if (values != null)
            {
                isExist = true;
            }
            BaseTestSite.Assert.IsTrue(
                isExist,
                @"If the LDAP_SERVER_SD_FLAGS_OID control is present in an LDAP search request, the server returns an SD with the parts specified in the control
                when all attributes are requested.");

            #endregion

            #region without SD Flags Control

            isExist = false;
            searchReq.Controls.Clear();
            searchReq.Attributes.Clear();
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["ntSecurityDescriptor"];
            if (attr == null)
            {
                isExist = false;
            }
            else
            {
                isExist = true;
            }
            BaseTestSite.Assert.IsFalse(
                isExist,
                @"Without the presence of this control, the server returns an SD only when the SD attribute name is explicitly mentioned in the requested attribute list.");

            searchReq.Attributes.Add("ntSecurityDescriptor");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            BaseTestSite.Assert.AreEqual(
                1,
                searchRep.Entries[0].Attributes.Count,
                @"Without the presence of this control, the server returns an SD only when the SD attribute name is explicitly mentioned in the requested attribute list.");
            attr   = searchRep.Entries[0].Attributes["ntSecurityDescriptor"];
            values = attr.GetValues(Type.GetType("System.String"));
            if (values != null)
            {
                isExist = true;
            }
            BaseTestSite.Assert.IsTrue(
                isExist,
                @"Without the presence of this control, the server returns an SD only when the SD attribute name is explicitly mentioned in the requested attribute list.");

            #endregion
        }
        private bool GetRevealSecretsPolicyForUser(string rodcObjDN, string userObjDN)
        {
            #region variables

            System.DirectoryServices.Protocols.SearchResultEntry rodcEntry;
            System.DirectoryServices.Protocols.SearchResultEntry userEntry;

            #endregion

            #region connect and get rodc and user object

            LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(AD_LDAPModelAdapter.Instance(Site).PDCNetbiosName),
                                                    new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                                          AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                                          AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;
            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                rodcObjDN,
                "(objectClass=computer)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "msDS-KrbTgtLink",
                "msDS-NeverRevealGroup",
                "msDS-RevealOnDemandGroup");
            System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            rodcEntry = searchRep.Entries[0];
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                userObjDN,
                "(objectClass=user)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "userAccountControl",
                "objectSid");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            userEntry = searchRep.Entries[0];

            #endregion

            #region body
            //An RODC can always cache secrets of its own account
            if (rodcObjDN == userObjDN)
            {
                return(true);
            }

            //An RODC can always cache secrets of its own secondary Kerberos TGT account
            //But not other secondary Kerberos TGT accounts.
            DirectoryAttribute attr   = rodcEntry.Attributes["msDS-KrbTgtLink"];
            object[]           values = attr.GetValues(Type.GetType("System.String"));
            foreach (string value in values)
            {
                if (value.Equals(userObjDN, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(true);
                }
            }
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                AD_LDAPModelAdapter.Instance(Site).rootDomainNC,
                "(objectClass=computer)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "msDS-KrbTgtLink");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in searchRep.Entries)
            {
                if (entry.Attributes["msDS-KrbTgtLink"] != null)
                {
                    values = entry.Attributes["msDS-KrbTgtLink"].GetValues(Type.GetType("System.String"));
                    foreach (string value in values)
                    {
                        if (value.Equals(userObjDN, StringComparison.CurrentCultureIgnoreCase))
                        {
                            return(false);
                        }
                    }
                }
            }

            //Never reveal secrets of inter-domain trust accounts
            attr   = userEntry.Attributes["userAccountControl"];
            values = attr.GetValues(Type.GetType("System.String"));
            foreach (string value in values)
            {
                int userAccountControl = int.Parse(value, CultureInfo.InvariantCulture);
                if (((AdtsUserAccountControl)userAccountControl & AdtsUserAccountControl.ADS_UF_INTERDOMAIN_TRUST_ACCOUNT) != 0)
                {
                    return(false);
                }
            }

            //Never reveal secrets of users reachable from rodcObj!msDS-NeverRevealGroup
            attr   = rodcEntry.Attributes["msDS-NeverRevealGroup"];
            values = attr.GetValues(Type.GetType("System.String"));
            foreach (string groupDN in values)
            {
                if (Utilities.IsGroupMember(
                        AD_LDAPModelAdapter.Instance(Site).PDCNetbiosName,
                        AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName,
                        AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                        AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                        groupDN,
                        userObjDN))
                {
                    return(false);
                }
            }

            //Cache secrets of users reachable from rodcObj!msDS-RevealOnDemandGroup
            attr   = rodcEntry.Attributes["msDS-RevealOnDemandGroup"];
            values = attr.GetValues(Type.GetType("System.String"));
            foreach (string groupDN in values)
            {
                if (Utilities.IsGroupMember(
                        AD_LDAPModelAdapter.Instance(Site).PDCNetbiosName,
                        AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName,
                        AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                        AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                        groupDN,
                        userObjDN))
                {
                    return(true);
                }
            }

            return(false);

            #endregion
        }
 /// <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);
     }
 }
        private void LogServerResponse(SearchResponse response)
        {
            var hasErrorMessage = !string.IsNullOrEmpty(response.ErrorMessage);

            Logger.Log(
                hasErrorMessage ? LogSeverity.Error : LogSeverity.Information, 
                GetType().ToString(),
                string.Format(
                    CultureInfo.InvariantCulture,
                    "LDAP Search Response:{0}{1}",
                    string.Format(CultureInfo.InvariantCulture, "\nResult Code: {0}", response.ResultCode),
                    hasErrorMessage
                        ? string.Format(CultureInfo.InvariantCulture, "\nError Message: {0}", response.ErrorMessage)
                        : string.Empty));
        }
Пример #13
0
        public void LDAP_Delete_Tombstone_Requirements()
        {
            #region variables

            string testGroup   = "testGroup";
            string testGroupDN = "CN=" + testGroup + ",CN=Users," + adLdapModelAdapter.rootDomainNC;
            string testUser    = "******";
            string testUserDN  = "CN=" + testUser + ",CN=Users," + adLdapModelAdapter.rootDomainNC;
            bool   isExist     = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            string         addr = adLdapModelAdapter.PDCIPAddress;
            string         port = adLdapModelAdapter.ADDSPortNum;
            LdapConnection con  = new LdapConnection(
                new LdapDirectoryIdentifier(addr, int.Parse(port)),
                new NetworkCredential(adLdapModelAdapter.DomainAdministratorName,
                                      adLdapModelAdapter.DomainUserPassword,
                                      adLdapModelAdapter.PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region Add the object for delete testing

            try
            {
                System.DirectoryServices.Protocols.DeleteRequest  req = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                System.DirectoryServices.Protocols.DeleteResponse rep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(req);
            }
            catch { }
            ManagedAddRequest addReq = new ManagedAddRequest(testUserDN, "user");
            System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            try
            {
                System.DirectoryServices.Protocols.DeleteRequest  req = new System.DirectoryServices.Protocols.DeleteRequest(testGroupDN);
                System.DirectoryServices.Protocols.DeleteResponse rep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(req);
            }
            catch { }
            addReq = new ManagedAddRequest(testGroupDN, "group");
            addReq.Attributes.Add(new DirectoryAttribute("member", testUserDN));
            addReq.Attributes.Add(new DirectoryAttribute("description", testUserDN));
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);

            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                testGroupDN,
                "(objectClass=group)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                new string[] { "member", "description" });
            System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            DirectoryAttribute attr   = searchRep.Entries[0].Attributes["member"];
            object[]           values = attr.GetValues(Type.GetType("System.String"));
            foreach (string value in values)
            {
                if (value.Contains(testUserDN))
                {
                    isExist = true;
                }
            }
            BaseTestSite.Assert.IsTrue(isExist, @"Entry referencing the to-be-deleted entry should exist before deletion.");
            isExist = false;
            attr    = searchRep.Entries[0].Attributes["description"];
            values  = attr.GetValues(Type.GetType("System.String"));
            foreach (string value in values)
            {
                if (value.Contains(testUserDN))
                {
                    isExist = true;
                }
            }
            BaseTestSite.Assert.IsTrue(isExist, @"Entry referencing the to-be-deleted entry should exist before deletion.");

            #endregion

            #region check the deleted entry

            System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
            System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);

            DirectoryEntry deletedEntry = Utilities.BuildDeletedEntry(
                string.Format(CultureInfo.InvariantCulture, "{0}.{1}", adLdapModelAdapter.PDCNetbiosName, adLdapModelAdapter.PrimaryDomainDnsName),
                AD_LDAPModelAdapter.DELETED_OBJECTS_CONTAINER_GUID,
                adLdapModelAdapter.rootDomainNC);
            SearchResult tombStoneResult = Utilities.GetTombstone(deletedEntry, testUserDN.Split(',')[0].Split('=')[1].Trim());
            BaseTestSite.Assert.IsNotNull(tombStoneResult, "deleted entry: {0} should be found in AD.", deletedEntry);

            #region linked attributes in deleted entry

            isExist = false;
            foreach (string key in tombStoneResult.Properties.PropertyNames)
            {
                foreach (object value in tombStoneResult.Properties[key])
                {
                    if (key.ToLower(CultureInfo.InvariantCulture) == "objectCategory")
                    {
                        if (value != null)
                        {
                            isExist = true;
                        }
                    }
                    if (key.ToLower(CultureInfo.InvariantCulture) == "sAMAccountType")
                    {
                        if (value != null)
                        {
                            isExist = true;
                        }
                    }
                }
            }
            BaseTestSite.Assert.IsFalse(
                isExist,
                @"A tombstone does not retain the attribute values of the original object for the attributes objectCategory and sAMAccountType
                or for any linked attributes even if these attributes would otherwise be retained according to the preceding bullet point. 
                In other words, when an object is deleted and transformed into a tombstone, objectCategory values, sAMAccountType values, 
                and any linked attribute values on it are always removed.");

            #endregion

            #endregion

            #region check the entry referencing the deleted entry

            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                testGroupDN,
                "(objectClass=group)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                new string[] { "member", "description" });
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);

            #region linked attribute in referencing entry

            attr = searchRep.Entries[0].Attributes["member"];
            if (attr == null)
            {
                isExist = false;
            }
            BaseTestSite.Assert.IsFalse(
                isExist,
                @"NC replicas do not contain objects with linked attribute values referencing tombstones. 
                In other words, when an object is deleted and transformed into a tombstone, any linked attribute 
                values on other objects referencing it are also removed."
                );

            #endregion

            #region non linked attribute in referencing entry

            isExist = false;
            attr    = searchRep.Entries[0].Attributes["description"];
            values  = attr.GetValues(Type.GetType("System.String"));
            foreach (string value in values)
            {
                if (value.Contains(testUserDN))
                {
                    isExist = true;
                }
            }
            BaseTestSite.Assert.IsTrue(
                isExist,
                @"If any NC replicas contain other objects with nonlinked attribute values referencing a tombstone,
                then those attribute values on those objects are retained.  In other words, when an object is deleted
                and transformed into a tombstone, any nonlinked attribute values on other objects referencing it are not removed."
                );

            #endregion

            #endregion

            #region clean up

            if (Utilities.IsObjectExist(testUserDN, addr, port))
            {
                System.DirectoryServices.Protocols.DeleteRequest req = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                try
                {
                    System.DirectoryServices.Protocols.DeleteResponse rep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(req);
                }
                catch
                {
                }
            }
            if (Utilities.IsObjectExist(testGroupDN, addr, port))
            {
                System.DirectoryServices.Protocols.DeleteRequest req = new System.DirectoryServices.Protocols.DeleteRequest(testGroupDN);
                try
                {
                    System.DirectoryServices.Protocols.DeleteResponse rep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(req);
                }
                catch
                {
                }
            }

            #endregion
        }
Пример #14
0
        internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
        {
            int error;
            LDAP_TIMEVAL timeout = new LDAP_TIMEVAL();
            timeout.tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond);
            IntPtr ldapResult = (IntPtr)0;
            DirectoryResponse response = null;

            IntPtr requestName = (IntPtr)0;
            IntPtr requestValue = (IntPtr)0;

            IntPtr entryMessage = (IntPtr)0;

            bool needAbandon = true;

            // processing for the partial results retrieval
            if (resultType != ResultAll.LDAP_MSG_ALL)
            {
                // we need to have 0 timeout as we are polling for the results and don't want to wait
                timeout.tv_sec = 0;
                timeout.tv_usec = 0;

                if (resultType == ResultAll.LDAP_MSG_POLLINGALL)
                    resultType = ResultAll.LDAP_MSG_ALL;

                // when doing partial results retrieving, if ldap_result failed, we don't do ldap_abandon here.
                needAbandon = false;
            }

            error = Wldap32.ldap_result(ldapHandle, messageId, (int)resultType, timeout, ref ldapResult);
            if (error != -1 && error != 0)
            {
                // parsing the result
                int serverError = 0;
                try
                {
                    int resulterror = 0;
                    string responseDn = null;
                    string responseMessage = null;
                    Uri[] responseReferral = null;
                    DirectoryControl[] responseControl = null;

                    // ldap_parse_result skips over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERRAL
                    if (error != (int)LdapResult.LDAP_RES_SEARCH_ENTRY && error != (int)LdapResult.LDAP_RES_REFERRAL)
                        resulterror = ConstructParsedResult(ldapResult, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl);

                    if (resulterror == 0)
                    {
                        resulterror = serverError;

                        if (error == (int)LdapResult.LDAP_RES_ADD)
                            response = new AddResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
                        else if (error == (int)LdapResult.LDAP_RES_MODIFY)
                            response = new ModifyResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
                        else if (error == (int)LdapResult.LDAP_RES_DELETE)
                            response = new DeleteResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
                        else if (error == (int)LdapResult.LDAP_RES_MODRDN)
                            response = new ModifyDNResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
                        else if (error == (int)LdapResult.LDAP_RES_COMPARE)
                            response = new CompareResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
                        else if (error == (int)LdapResult.LDAP_RES_EXTENDED)
                        {
                            response = new ExtendedResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
                            if (resulterror == (int)ResultCode.Success)
                            {
                                resulterror = Wldap32.ldap_parse_extended_result(ldapHandle, ldapResult, ref requestName, ref requestValue, 0 /*not free it*/);
                                if (resulterror == 0)
                                {
                                    string name = null;
                                    if (requestName != (IntPtr)0)
                                    {
                                        name = Marshal.PtrToStringUni(requestName);
                                    }

                                    berval val = null;
                                    byte[] requestValueArray = null;
                                    if (requestValue != (IntPtr)0)
                                    {
                                        val = new berval();
                                        Marshal.PtrToStructure(requestValue, val);
                                        if (val.bv_len != 0 && val.bv_val != (IntPtr)0)
                                        {
                                            requestValueArray = new byte[val.bv_len];
                                            Marshal.Copy(val.bv_val, requestValueArray, 0, val.bv_len);
                                        }
                                    }

                                    ((ExtendedResponse)response).name = name;
                                    ((ExtendedResponse)response).value = requestValueArray;
                                }
                            }
                        }
                        else if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT ||
                               error == (int)LdapResult.LDAP_RES_SEARCH_ENTRY ||
                               error == (int)LdapResult.LDAP_RES_REFERRAL)
                        {
                            response = new SearchResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);

                            //set the flag here so our partial result processor knows whether the search is done or not
                            if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT)
                            {
                                ((SearchResponse)response).searchDone = true;
                            }

                            SearchResultEntryCollection searchResultEntries = new SearchResultEntryCollection();
                            SearchResultReferenceCollection searchResultReferences = new SearchResultReferenceCollection();

                            // parsing the resultentry
                            entryMessage = Wldap32.ldap_first_entry(ldapHandle, ldapResult);

                            int entrycount = 0;
                            while (entryMessage != (IntPtr)0)
                            {
                                SearchResultEntry entry = ConstructEntry(entryMessage);
                                if (entry != null)
                                    searchResultEntries.Add(entry);

                                entrycount++;
                                entryMessage = Wldap32.ldap_next_entry(ldapHandle, entryMessage);
                            }

                            // parsing the reference
                            IntPtr referenceMessage = Wldap32.ldap_first_reference(ldapHandle, ldapResult);

                            while (referenceMessage != (IntPtr)0)
                            {
                                SearchResultReference reference = ConstructReference(referenceMessage);
                                if (reference != null)
                                    searchResultReferences.Add(reference);

                                referenceMessage = Wldap32.ldap_next_reference(ldapHandle, referenceMessage);
                            }

                            ((SearchResponse)response).SetEntries(searchResultEntries);
                            ((SearchResponse)response).SetReferences(searchResultReferences);
                        }

                        if (resulterror != (int)ResultCode.Success && resulterror != (int)ResultCode.CompareFalse && resulterror != (int)ResultCode.CompareTrue && resulterror != (int)ResultCode.Referral && resulterror != (int)ResultCode.ReferralV2)
                        {
                            // throw operation exception                   
                            if (Utility.IsResultCode((ResultCode)resulterror))
                            {
                                throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(resulterror));
                            }
                            else
                                // should not occur
                                throw new DirectoryOperationException(response);
                        }

                        return response;
                    }
                    else
                    {
                        // fall over, throw the exception beow
                        error = resulterror;
                    }
                }
                finally
                {
                    if (requestName != (IntPtr)0)
                        Wldap32.ldap_memfree(requestName);

                    if (requestValue != (IntPtr)0)
                        Wldap32.ldap_memfree(requestValue);

                    if (ldapResult != (IntPtr)0)
                    {
                        Wldap32.ldap_msgfree(ldapResult);
                    }
                }
            }
            else
            {
                // ldap_result failed
                if (error == 0)
                {
                    if (exceptionOnTimeOut)
                    {
                        // client side timeout                        
                        error = (int)LdapError.TimeOut;
                    }
                    else
                    {
                        // if we don't throw exception on time out (notification search for example), we just return empty resposne
                        return null;
                    }
                }
                else
                {
                    error = Wldap32.LdapGetLastError();
                }

                // abandon the request
                if (needAbandon)
                    Wldap32.ldap_abandon(ldapHandle, messageId);
            }

            // throw proper exception here            
            throw ConstructException(error, operation);
        }
Пример #15
0
        private void GetResultsHelper(LdapPartialAsyncResult asyncResult)
        {
            LdapConnection connection = asyncResult._con;
            ResultAll      resultType = ResultAll.LDAP_MSG_RECEIVED;

            if (asyncResult._resultStatus == ResultsStatus.CompleteResult)
            {
                resultType = ResultAll.LDAP_MSG_POLLINGALL;
            }

            try
            {
                ValueTask <DirectoryResponse> vt = connection.ConstructResponseAsync(asyncResult._messageID, LdapOperation.LdapSearch, resultType, asyncResult._requestTimeout, false, sync: true);
                Debug.Assert(vt.IsCompleted);
                SearchResponse response = (SearchResponse)vt.GetAwaiter().GetResult();

                // This should only happen in the polling thread case.
                if (response == null)
                {
                    // Only when request time out has not yet expiered.
                    if ((asyncResult._startTime.Ticks + asyncResult._requestTimeout.Ticks) > DateTime.Now.Ticks)
                    {
                        // This is expected, just the client does not have the result yet .
                        return;
                    }
                    else
                    {
                        // time out, now we need to throw proper exception
                        throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut));
                    }
                }

                if (asyncResult._response != null)
                {
                    AddResult(asyncResult._response, response);
                }
                else
                {
                    asyncResult._response = response;
                }

                // If search is done, set the flag.
                if (response.searchDone)
                {
                    asyncResult._resultStatus = ResultsStatus.Done;
                }
            }
            catch (Exception exception)
            {
                if (exception is DirectoryOperationException directoryOperationException)
                {
                    SearchResponse response = (SearchResponse)directoryOperationException.Response;
                    if (asyncResult._response != null)
                    {
                        AddResult(asyncResult._response, response);
                    }
                    else
                    {
                        asyncResult._response = response;
                    }

                    // Set the response back to the exception so it holds all the results up to now.
                    directoryOperationException.Response = asyncResult._response;
                }
                else if (exception is LdapException ldapException)
                {
                    if (asyncResult._response != null)
                    {
                        // add previous retrieved entries if available
                        if (asyncResult._response.Entries != null)
                        {
                            for (int i = 0; i < asyncResult._response.Entries.Count; i++)
                            {
                                ldapException.PartialResults.Add(asyncResult._response.Entries[i]);
                            }
                        }

                        // add previous retrieved references if available
                        if (asyncResult._response.References != null)
                        {
                            for (int i = 0; i < asyncResult._response.References.Count; i++)
                            {
                                ldapException.PartialResults.Add(asyncResult._response.References[i]);
                            }
                        }
                    }
                }

                // Exception occurs, this operation is done.
                asyncResult._exception    = exception;
                asyncResult._resultStatus = ResultsStatus.Done;

                // Need to abandon this request.
                LdapPal.CancelDirectoryAsyncOperation(connection._ldapHandle, asyncResult._messageID);
            }
        }
        public void LDAP_Search_SearchFilters()
        {
            #region variables

            string testUser   = "******";
            string testUserDN = "CN=" + testUser + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            int    errorCode;
            bool   failed = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            string         addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress;
            string         port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum;
            LdapConnection con  = new LdapConnection(new LdapDirectoryIdentifier(addr, int.Parse(port)),
                                                     new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                                           AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                                           AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region Add a dynamic object for search testing

            if (Utilities.IsObjectExist(testUserDN, addr, port))
            {
                System.DirectoryServices.Protocols.DeleteRequest  req = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                System.DirectoryServices.Protocols.DeleteResponse rep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(req);
            }
            ManagedAddRequest addReq = new ManagedAddRequest(testUserDN);
            addReq.Attributes.Add(new DirectoryAttribute("objectClass", new string[] { "dynamicObject", "user" }));
            addReq.Attributes.Add(new DirectoryAttribute("entryTTL", "1800"));
            addReq.Attributes.Add(new DirectoryAttribute("sAMAccountName", testUser));
            System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);

            #endregion

            #region search filter
            //entryTTL is a constructed attribute
            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                testUserDN,
                "(entryTTL=*)",
                System.DirectoryServices.Protocols.SearchScope.Subtree);
            try
            {
                System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.InappropriateMatching)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"Active Directory does not support constructed attributes (defined in section 3.1.1.4.5) in search filters.
                When a search operation is performed with such a search filter, Active Directory fails with inappropriateMatching
                ([RFC2251] section 4.1.10).");

            #endregion

            #region clean up
            if (Utilities.IsObjectExist(testUserDN, addr, port))
            {
                System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            #endregion
        }
        public void LDAP_Modify_SecurityDescriptor_ProcessingSpecifics()
        {
            #region variables

            string netBIOSName = AD_LDAPModelAdapter.Instance(Site).PrimaryDomainNetBiosName;
            string operUser    = "******";
            string operUserDN  = "CN=" + operUser + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string testUser    = "******";
            string testUserDN  = "CN=" + testUser + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string userPwd     = "Password01!";
            bool   failed      = false;
            ActiveDirectorySecurity securityDescriptor = new ActiveDirectorySecurity();
            string testUserOwner = null;

            #endregion

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less then Windows Server 2012");
            string addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress;
            string port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum;

            try
            {
                using (LdapConnection con = new LdapConnection(
                           new LdapDirectoryIdentifier(addr, int.Parse(port)),
                           new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                 AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                 AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)))
                {
                    con.SessionOptions.Sealing = false;
                    con.SessionOptions.Signing = false;

                    #region add a user object for operating the ntSecurityDescriptor modify

                    if (!Utilities.IsObjectExist(operUserDN, addr, port))
                    {
                        Utilities.NewUser(addr, port, "CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC, operUser, userPwd);
                    }

                    #endregion

                    #region add a test user object to be modified

                    if (!Utilities.IsObjectExist(testUserDN, addr, port))
                    {
                        Utilities.NewUser(addr, port, "CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC, testUser, userPwd);
                    }

                    #endregion

                    #region get ntSecurityDescriptor for the test user object to be modified

                    System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                        testUserDN,
                        "(objectClass=user)",
                        System.DirectoryServices.Protocols.SearchScope.Subtree,
                        "ntSecurityDescriptor");
                    System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
                    BaseTestSite.Assert.AreEqual(
                        1,
                        searchRep.Entries[0].Attributes.Count,
                        @"Without the presence of this control, the server returns an SD only when the SD attribute name is explicitly mentioned in the requested attribute list.");
                    DirectoryAttribute attr   = searchRep.Entries[0].Attributes["ntSecurityDescriptor"];
                    object[]           values = attr.GetValues(Type.GetType("System.Byte[]"));
                    byte[]             value  = (byte[])values[0];
                    securityDescriptor.SetSecurityDescriptorBinaryForm(value);

                    //GetsSecurityDescriptorOwner method will return the owner part of Secuirty Descriptor
                    testUserOwner = Utilities.GetSecurityDescriptorOwner(securityDescriptor);

                    #endregion
                }

                using (LdapConnection con = new LdapConnection(
                           new LdapDirectoryIdentifier(addr, int.Parse(port)),
                           new NetworkCredential(operUser, userPwd, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)))
                {
                    #region modify the test user

                    IdentityReference testUserId = new NTAccount(testUserOwner);
                    securityDescriptor.SetOwner(testUserId);
                    byte[] value = securityDescriptor.GetSecurityDescriptorBinaryForm();

                    DirectoryAttributeModification mod = new DirectoryAttributeModification();
                    mod.Name      = "ntSecurityDescriptor";
                    mod.Operation = DirectoryAttributeOperation.Replace;
                    mod.Add(value);
                    System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(testUserDN, mod);
                    try
                    {
                        System.DirectoryServices.Protocols.ModifyResponse modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
                        if (modRep.ResultCode == ResultCode.Success)
                        {
                            failed = false;
                        }
                    }
                    catch (DirectoryOperationException e)
                    {
                        if (e.Response.ResultCode == ResultCode.ConstraintViolation)
                        {
                            int errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                            if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_INVALID_OWNER)
                            {
                                failed = true;
                            }
                        }
                    }

                    BaseTestSite.Assert.IsTrue(
                        failed,
                        @"Microsoft Windows Server 2008 R2 operating system and above impose a restriction on modifying the OWNER field.
                    If a modify operation attempts to set the OWNER SID to a value to which it is currently set, the operation will 
                    fail with a constraintViolation / ERROR_INVALID_OWNER unless at least one of the following conditions applies.
                    Let U be the user performing the modify operation:
                    §	U.SID equals OWNER SID.
                    §	Let G be a group in U.Groups whose SID is being set in the OWNER field. G.Attributes contains SE_GROUP_OWNER but not SE_GROUP_USE_FOR_DENY_ONLY.
                    §	U.Privileges contains SE_RESTORE_PRIVILEGE.
                    This restriction is processed before the security checks described in section 6.1.3.4.");

                    #endregion
                }
            }
            finally
            {
                using (LdapConnection con = new LdapConnection(
                           new LdapDirectoryIdentifier(addr, int.Parse(port)),
                           new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                 AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                 AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)))
                {
                    #region clean up

                    System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                    System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
                    delReq = new System.DirectoryServices.Protocols.DeleteRequest(operUserDN);
                    delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);

                    #endregion
                }
            }
        }
        internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
        {
            LDAP_TIMEVAL timeout = new LDAP_TIMEVAL {
                tv_sec = (int) (requestTimeOut.Ticks / 0x989680L)
            };
            IntPtr zero = IntPtr.Zero;
            DirectoryResponse response = null;
            IntPtr oid = IntPtr.Zero;
            IntPtr data = IntPtr.Zero;
            IntPtr entryMessage = IntPtr.Zero;
            bool flag = true;
            if (resultType != ResultAll.LDAP_MSG_ALL)
            {
                timeout.tv_sec = 0;
                timeout.tv_usec = 0;
                if (resultType == ResultAll.LDAP_MSG_POLLINGALL)
                {
                    resultType = ResultAll.LDAP_MSG_ALL;
                }
                flag = false;
            }
            int error = Wldap32.ldap_result(this.ldapHandle, messageId, (int) resultType, timeout, ref zero);
            switch (error)
            {
                case -1:
                case 0:
                    break;

                default:
                {
                    int serverError = 0;
                    try
                    {
                        int errorCode = 0;
                        string responseDn = null;
                        string responseMessage = null;
                        Uri[] responseReferral = null;
                        DirectoryControl[] responseControl = null;
                        if ((error != 100) && (error != 0x73))
                        {
                            errorCode = this.ConstructParsedResult(zero, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl);
                        }
                        if (errorCode == 0)
                        {
                            errorCode = serverError;
                            switch (error)
                            {
                                case 0x69:
                                    response = new AddResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    break;

                                case 0x67:
                                    response = new ModifyResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    break;

                                case 0x6b:
                                    response = new DeleteResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    break;

                                case 0x6d:
                                    response = new ModifyDNResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    break;

                                case 0x6f:
                                    response = new CompareResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    break;

                                case 120:
                                    response = new ExtendedResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    if (errorCode == 0)
                                    {
                                        errorCode = Wldap32.ldap_parse_extended_result(this.ldapHandle, zero, ref oid, ref data, 0);
                                        if (errorCode == 0)
                                        {
                                            string str3 = null;
                                            if (oid != IntPtr.Zero)
                                            {
                                                str3 = Marshal.PtrToStringUni(oid);
                                            }
                                            berval structure = null;
                                            byte[] destination = null;
                                            if (data != IntPtr.Zero)
                                            {
                                                structure = new berval();
                                                Marshal.PtrToStructure(data, structure);
                                                if ((structure.bv_len != 0) && (structure.bv_val != IntPtr.Zero))
                                                {
                                                    destination = new byte[structure.bv_len];
                                                    Marshal.Copy(structure.bv_val, destination, 0, structure.bv_len);
                                                }
                                            }
                                            ((ExtendedResponse) response).name = str3;
                                            ((ExtendedResponse) response).value = destination;
                                        }
                                    }
                                    break;

                                case 0x65:
                                case 100:
                                case 0x73:
                                {
                                    response = new SearchResponse(responseDn, responseControl, (ResultCode) errorCode, responseMessage, responseReferral);
                                    if (error == 0x65)
                                    {
                                        ((SearchResponse) response).searchDone = true;
                                    }
                                    SearchResultEntryCollection col = new SearchResultEntryCollection();
                                    SearchResultReferenceCollection references = new SearchResultReferenceCollection();
                                    entryMessage = Wldap32.ldap_first_entry(this.ldapHandle, zero);
                                    int num4 = 0;
                                    while (entryMessage != IntPtr.Zero)
                                    {
                                        SearchResultEntry entry = this.ConstructEntry(entryMessage);
                                        if (entry != null)
                                        {
                                            col.Add(entry);
                                        }
                                        num4++;
                                        entryMessage = Wldap32.ldap_next_entry(this.ldapHandle, entryMessage);
                                    }
                                    for (IntPtr ptr5 = Wldap32.ldap_first_reference(this.ldapHandle, zero); ptr5 != IntPtr.Zero; ptr5 = Wldap32.ldap_next_reference(this.ldapHandle, ptr5))
                                    {
                                        SearchResultReference reference = this.ConstructReference(ptr5);
                                        if (reference != null)
                                        {
                                            references.Add(reference);
                                        }
                                    }
                                    ((SearchResponse) response).SetEntries(col);
                                    ((SearchResponse) response).SetReferences(references);
                                    break;
                                }
                            }
                            switch (errorCode)
                            {
                                case 0:
                                case 5:
                                case 6:
                                case 10:
                                case 9:
                                    return response;

                                default:
                                    if (Utility.IsResultCode((ResultCode) errorCode))
                                    {
                                        throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(errorCode));
                                    }
                                    throw new DirectoryOperationException(response);
                            }
                        }
                        error = errorCode;
                        goto Label_03A7;
                    }
                    finally
                    {
                        if (oid != IntPtr.Zero)
                        {
                            Wldap32.ldap_memfree(oid);
                        }
                        if (data != IntPtr.Zero)
                        {
                            Wldap32.ldap_memfree(data);
                        }
                        if (zero != IntPtr.Zero)
                        {
                            Wldap32.ldap_msgfree(zero);
                        }
                    }
                    break;
                }
            }
            if (error == 0)
            {
                if (!exceptionOnTimeOut)
                {
                    return null;
                }
                error = 0x55;
            }
            else
            {
                error = Wldap32.LdapGetLastError();
            }
            if (flag)
            {
                Wldap32.ldap_abandon(this.ldapHandle, messageId);
            }
        Label_03A7:
            throw this.ConstructException(error, operation);
        }
Пример #19
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;
        }
Пример #20
0
		private DirectoryException ConstructException(int error, LdapOperation operation)
		{
			DirectoryResponse extendedResponse = null;
			if (!Utility.IsResultCode((ResultCode)error))
			{
				if (!Utility.IsLdapError((LdapError)error))
				{
					return new LdapException(error);
				}
				else
				{
					string str = LdapErrorMappings.MapResultCode(error);
					string serverErrorMessage = this.options.ServerErrorMessage;
					if (serverErrorMessage == null || serverErrorMessage.Length <= 0)
					{
						return new LdapException(error, str);
					}
					else
					{
						throw new LdapException(error, str, serverErrorMessage);
					}
				}
			}
			else
			{
				if (operation != LdapOperation.LdapAdd)
				{
					if (operation != LdapOperation.LdapModify)
					{
						if (operation != LdapOperation.LdapDelete)
						{
							if (operation != LdapOperation.LdapModifyDn)
							{
								if (operation != LdapOperation.LdapCompare)
								{
									if (operation != LdapOperation.LdapSearch)
									{
										if (operation == LdapOperation.LdapExtendedRequest)
										{
											extendedResponse = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
										}
									}
									else
									{
										extendedResponse = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
									}
								}
								else
								{
									extendedResponse = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
								}
							}
							else
							{
								extendedResponse = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
							}
						}
						else
						{
							extendedResponse = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
						}
					}
					else
					{
						extendedResponse = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
					}
				}
				else
				{
					extendedResponse = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
				}
				string str1 = OperationErrorMappings.MapResultCode(error);
				return new DirectoryOperationException(extendedResponse, str1);
			}
		}
Пример #21
0
		internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
		{
			DirectoryResponse directoryResponse;
			LDAP_TIMEVAL lDAPTIMEVAL = new LDAP_TIMEVAL();
			lDAPTIMEVAL.tv_sec = (int)(requestTimeOut.Ticks / (long)0x989680);
			IntPtr intPtr = (IntPtr)0;
			DirectoryResponse searchResponse = null;
			IntPtr intPtr1 = (IntPtr)0;
			IntPtr intPtr2 = (IntPtr)0;
			bool flag = true;
			if (resultType != ResultAll.LDAP_MSG_ALL)
			{
				lDAPTIMEVAL.tv_sec = 0;
				lDAPTIMEVAL.tv_usec = 0;
				if (resultType == ResultAll.LDAP_MSG_POLLINGALL)
				{
					resultType = ResultAll.LDAP_MSG_ALL;
				}
				flag = false;
			}
			int num = Wldap32.ldap_result(this.ldapHandle, messageId, (int)resultType, lDAPTIMEVAL, ref intPtr);
			if (num == -1 || num == 0)
			{
				if (num != 0)
				{
					num = Wldap32.LdapGetLastError();
				}
				else
				{
					if (!exceptionOnTimeOut)
					{
						return null;
					}
					else
					{
						num = 85;
					}
				}
				if (flag)
				{
					Wldap32.ldap_abandon(this.ldapHandle, messageId);
				}
			}
			else
			{
				int num1 = 0;
				try
				{
					int num2 = 0;
					string str = null;
					string str1 = null;
					Uri[] uriArray = null;
					DirectoryControl[] directoryControlArray = null;
					if (num != 100 && num != 115)
					{
						num2 = this.ConstructParsedResult(intPtr, ref num1, ref str, ref str1, ref uriArray, ref directoryControlArray);
					}
					if (num2 != 0)
					{
						num = num2;
						throw this.ConstructException(num, operation);
					}
					else
					{
						num2 = num1;
						if (num != 105)
						{
							if (num != 103)
							{
								if (num != 107)
								{
									if (num != 109)
									{
										if (num != 111)
										{
											if (num != 120)
											{
												if (num == 101 || num == 100 || num == 115)
												{
													searchResponse = new SearchResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
													if (num == 101)
													{
														((SearchResponse)searchResponse).searchDone = true;
													}
													SearchResultEntryCollection searchResultEntryCollection = new SearchResultEntryCollection();
													SearchResultReferenceCollection searchResultReferenceCollection = new SearchResultReferenceCollection();
													IntPtr intPtr3 = Wldap32.ldap_first_entry(this.ldapHandle, intPtr);
													int num3 = 0;
													while (intPtr3 != (IntPtr)0)
													{
														SearchResultEntry searchResultEntry = this.ConstructEntry(intPtr3);
														if (searchResultEntry != null)
														{
															searchResultEntryCollection.Add(searchResultEntry);
														}
														num3++;
														intPtr3 = Wldap32.ldap_next_entry(this.ldapHandle, intPtr3);
													}
													IntPtr intPtr4 = Wldap32.ldap_first_reference(this.ldapHandle, intPtr);
													while (intPtr4 != (IntPtr)0)
													{
														SearchResultReference searchResultReference = this.ConstructReference(intPtr4);
														if (searchResultReference != null)
														{
															searchResultReferenceCollection.Add(searchResultReference);
														}
														intPtr4 = Wldap32.ldap_next_reference(this.ldapHandle, intPtr4);
													}
													((SearchResponse)searchResponse).SetEntries(searchResultEntryCollection);
													((SearchResponse)searchResponse).SetReferences(searchResultReferenceCollection);
												}
											}
											else
											{
												searchResponse = new ExtendedResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
												if (num2 == 0)
												{
													num2 = Wldap32.ldap_parse_extended_result(this.ldapHandle, intPtr, ref intPtr1, ref intPtr2, 0);
													if (num2 == 0)
													{
														string stringUni = null;
														if (intPtr1 != (IntPtr)0)
														{
															stringUni = Marshal.PtrToStringUni(intPtr1);
														}
														byte[] numArray = null;
														if (intPtr2 != (IntPtr)0)
														{
															berval _berval = new berval();
															Marshal.PtrToStructure(intPtr2, _berval);
															if (_berval.bv_len != 0 && _berval.bv_val != (IntPtr)0)
															{
																numArray = new byte[_berval.bv_len];
																Marshal.Copy(_berval.bv_val, numArray, 0, _berval.bv_len);
															}
														}
														((ExtendedResponse)searchResponse).name = stringUni;
														((ExtendedResponse)searchResponse).@value = numArray;
													}
												}
											}
										}
										else
										{
											searchResponse = new CompareResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
										}
									}
									else
									{
										searchResponse = new ModifyDNResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
									}
								}
								else
								{
									searchResponse = new DeleteResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
								}
							}
							else
							{
								searchResponse = new ModifyResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
							}
						}
						else
						{
							searchResponse = new AddResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
						}
						if (num2 == 0 || num2 == 5 || num2 == 6 || num2 == 10 || num2 == 9)
						{
							directoryResponse = searchResponse;
						}
						else
						{
							if (!Utility.IsResultCode((ResultCode)num2))
							{
								throw new DirectoryOperationException(searchResponse);
							}
							else
							{
								throw new DirectoryOperationException(searchResponse, OperationErrorMappings.MapResultCode(num2));
							}
						}
					}
				}
				finally
				{
					if (intPtr1 != (IntPtr)0)
					{
						Wldap32.ldap_memfree(intPtr1);
					}
					if (intPtr2 != (IntPtr)0)
					{
						Wldap32.ldap_memfree(intPtr2);
					}
					if (intPtr != (IntPtr)0)
					{
						Wldap32.ldap_msgfree(intPtr);
					}
				}
				return directoryResponse;
			}
			throw this.ConstructException(num, operation);
		}
 private static void AuthenticateUser(SearchResponse response, ConnectionSettings settings, LdapConnection connection)
 {
     connection.Bind(
         new NetworkCredential(
             response.Entries[0].DistinguishedName, 
             string.IsNullOrEmpty(settings.UserPassword) ? "*" : settings.UserPassword));
 }
        public void LDAP_Add_Processing_Specifics_SystemFlags()
        {
            #region variables

            string siteObjDN             = "CN=testSite,CN=Sites,CN=Configuration," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string serversContainerObjDN = "CN=testServers," + siteObjDN;
            string serverObjDN           = "CN=testServer," + serversContainerObjDN;
            string ntdsSettingsObjDN     = "CN=NTDS Settings," + serverObjDN;
            string nTDSConnection        = "CN=testnTDSConnection," + ntdsSettingsObjDN;
            string ipObjDN              = "CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string siteLinkObjDN        = "CN=testSiteLink," + ipObjDN;
            string siteLinkBridgeDN     = "CN=testSiteLinkBridge," + ipObjDN;
            string subnetContainerObjDN = "CN=Subnets,CN=Sites,CN=Configuration," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string subnetObjDN          = "CN=192.168.0.0/24," + subnetContainerObjDN;
            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(AD_LDAPModelAdapter.Instance(Site).PDCIPAddress),
                                                    new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                                          AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                                          AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region Site Object
            ManagedAddRequest addReq = new ManagedAddRequest(siteObjDN, "site");
            System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add Site: {0} should succeed.",
                siteObjDN);
            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                siteObjDN,
                "(objectClass=Site)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            DirectoryAttribute attr   = searchRep.Entries[0].Attributes["systemFlags"];
            object[]           values = attr.GetValues(Type.GetType("System.String"));
            int flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                (SystemFlags)flags & (SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME),
                @"The DC sets additional bits in the systemFlags value of the object created:
                site object: FLAG_DISALLOW_MOVE_ON_DELETE and FLAG_CONFIG_ALLOW_RENAME.");
            #endregion

            #region ServersContainer Object
            addReq = new ManagedAddRequest(serversContainerObjDN, "serversContainer");
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add ServersContainer: {0} should succeed.",
                serversContainerObjDN);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                serversContainerObjDN,
                "(objectClass=serversContainer)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE,
                (SystemFlags)flags & SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE,
                @"The DC sets additional bits in the systemFlags value of the object created:
                serversContainer object: FLAG_DISALLOW_MOVE_ON_DELETE.");
            #endregion

            #region Server Object
            addReq = new ManagedAddRequest(serverObjDN, "server");
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add server: {0} should succeed.",
                serverObjDN);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                serverObjDN,
                "(objectClass=server)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME | SystemFlags.FLAG_CONFIG_ALLOW_LIMITED_MOVE,
                (SystemFlags)flags & (SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME | SystemFlags.FLAG_CONFIG_ALLOW_LIMITED_MOVE),
                @"The DC sets additional bits in the systemFlags value of the object created:
                server object: FLAG_DISALLOW_MOVE_ON_DELETE, FLAG_CONFIG_ALLOW_RENAME, and FLAG_CONFIG_ALLOW_LIMITED_MOVE.");
            #endregion

            #region nTDSDSA Object
            System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest("",
                                                                                                                           DirectoryAttributeOperation.Add, "schemaupgradeinprogress", "1");
            System.DirectoryServices.Protocols.ModifyResponse modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(ResultCode.Success, modRep.ResultCode, "Should return success when set SchemaUpgradeInProgress to 1");
            addReq = new ManagedAddRequest(ntdsSettingsObjDN, "nTDSDSA");
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add nTDSDSA: {0} should succeed.",
                ntdsSettingsObjDN);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                ntdsSettingsObjDN,
                "(objectClass=nTDSDSA)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE,
                (SystemFlags)flags & (SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE),
                @"The DC sets additional bits in the systemFlags value of the object created:
                nTDSDSA object: FLAG_DISALLOW_MOVE_ON_DELETE.");
            #endregion

            #region nTDSConnection Object
            addReq = new ManagedAddRequest(nTDSConnection, "nTDSConnection");
            addReq.Attributes.Add(new DirectoryAttribute("options", "1"));
            addReq.Attributes.Add(new DirectoryAttribute("fromServer", ntdsSettingsObjDN));
            addReq.Attributes.Add(new DirectoryAttribute("enabledConnection", "TRUE"));
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);

            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add nTDSConnection: {0} should succeed.",
                nTDSConnection);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                nTDSConnection,
                "(objectClass=nTDSConnection)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                (SystemFlags)flags & (SystemFlags.FLAG_CONFIG_ALLOW_RENAME),
                @"The DC sets additional bits in the systemFlags value of the object created:
                nTDSConnection object: FLAG_CONFIG_ALLOW_RENAME.");
            #endregion

            #region SiteLink Object
            addReq = new ManagedAddRequest(siteLinkObjDN, "siteLink");

            addReq.Attributes.Add(new DirectoryAttribute("siteList", siteObjDN));
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add SiteLink: {0} should succeed.",
                siteLinkObjDN);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                siteLinkObjDN,
                "(objectClass=SiteLink)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                (SystemFlags)flags & SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                @"The DC sets additional bits in the systemFlags value of the object created:
                siteLink object: FLAG_CONFIG_ALLOW_RENAME.");
            #endregion

            #region SiteLinkBridge Object
            addReq = new ManagedAddRequest(siteLinkBridgeDN, "siteLinkBridge");
            addReq.Attributes.Add(new DirectoryAttribute("siteLinkList", siteLinkObjDN));
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add SiteLinkBridge: {0} should succeed.",
                siteLinkBridgeDN);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                siteLinkBridgeDN,
                "(objectClass=SiteLinkBridge)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                (SystemFlags)flags & SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                @"The DC sets additional bits in the systemFlags value of the object created:
                siteLinkBridge object: FLAG_CONFIG_ALLOW_RENAME.");
            #endregion

            #region not above Object with Subnets Container Parent
            addReq = new ManagedAddRequest(subnetObjDN, "subnet");
            addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            BaseTestSite.Assert.AreEqual <ResultCode>(
                ResultCode.Success,
                addRep.ResultCode,
                @"Add subnet: {0} should succeed.",
                subnetObjDN);
            searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                subnetObjDN,
                "(objectClass=Subnet)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "systemFlags");
            searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            attr      = searchRep.Entries[0].Attributes["systemFlags"];
            values    = attr.GetValues(Type.GetType("System.String"));
            flags     = Convert.ToInt32(values[0], CultureInfo.InvariantCulture);
            BaseTestSite.Assert.AreEqual(
                SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                (SystemFlags)flags & SystemFlags.FLAG_CONFIG_ALLOW_RENAME,
                @"The DC sets additional bits in the systemFlags value of the object created:
                subnet object: FLAG_CONFIG_ALLOW_RENAME.");
            #endregion

            #region not above Object with Sites Container Parent except the Subnets Container and the Inter-Site-Transports Container
            #endregion

            #region clean up

            System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(siteObjDN);
            delReq.Controls.Add(new TreeDeleteControl());
            System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            delReq = new System.DirectoryServices.Protocols.DeleteRequest(siteLinkObjDN);
            delReq.Controls.Add(new TreeDeleteControl());
            delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            delReq = new System.DirectoryServices.Protocols.DeleteRequest(siteLinkBridgeDN);
            delReq.Controls.Add(new TreeDeleteControl());
            delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            delReq = new System.DirectoryServices.Protocols.DeleteRequest(subnetObjDN);
            delReq.Controls.Add(new TreeDeleteControl());
            delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);

            #endregion
        }
Пример #24
0
        private string getSearchResponseDSML(System.DirectoryServices.Protocols.SearchResponse response)
        {
            string returnValue = String.Empty;

            if (response != null)
            {
                DataIntegrator.Descriptions.LDAP.DSML.SearchResponse dsmlResponse = new DataIntegrator.Descriptions.LDAP.DSML.SearchResponse();

                dsmlResponse.requestID = response.RequestId;

                if ((response.Entries != null) && (response.Entries.Count > 0))
                {
                    dsmlResponse.searchResultEntry = new DataIntegrator.Descriptions.LDAP.DSML.SearchResultEntry[response.Entries.Count];

                    List <DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr> dsmlAttrs = new List <DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr>();

                    DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr attr = null;

                    System.DirectoryServices.Protocols.DirectoryAttribute directoryAttrb = null;

                    for (int i = 0; i < response.Entries.Count; i++)
                    {
                        dsmlResponse.searchResultEntry[i]           = new DataIntegrator.Descriptions.LDAP.DSML.SearchResultEntry();
                        dsmlResponse.searchResultEntry[i].requestID = response.RequestId;
                        dsmlResponse.searchResultEntry[i].dn        = response.Entries[i].DistinguishedName;

                        if ((response.Entries[i].Attributes != null) && (response.Entries[i].Attributes.Count > 0))
                        {
                            dsmlResponse.searchResultEntry[i].attr = new DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr[response.Entries[i].Attributes.Count];

                            dsmlAttrs = new List <DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr>();

                            foreach (string attrName in response.Entries[i].Attributes.AttributeNames)
                            {
                                directoryAttrb = response.Entries[i].Attributes[attrName];

                                if ((directoryAttrb != null) && (directoryAttrb.Count > 0))
                                {
                                    attr       = new DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr();
                                    attr.name  = attrName;
                                    attr.value = new string[directoryAttrb.Count];

                                    for (int j = 0; j < directoryAttrb.Count; j++)
                                    {
                                        if (directoryAttrb[j] is byte[])
                                        {
                                            attr.value[j] = Convert.ToBase64String((directoryAttrb[j] as byte[]), Base64FormattingOptions.None);
                                        }
                                        else
                                        {
                                            attr.value[j] = directoryAttrb[j].ToString();
                                        }
                                    }

                                    dsmlAttrs.Add(attr);
                                }

                                directoryAttrb = null;
                            }

                            if ((dsmlAttrs != null) && (dsmlAttrs.Count > 0))
                            {
                                dsmlAttrs.CopyTo(dsmlResponse.searchResultEntry[i].attr);
                            }

                            dsmlAttrs = null;
                            attr      = null;
                        }
                    }

                    Type   type  = typeof(DataIntegrator.Descriptions.LDAP.DSML.SearchResponse);
                    Type[] types = new Type[5];
                    types[0] = typeof(DataIntegrator.Descriptions.LDAP.DSML.DsmlAttr);
                    types[1] = typeof(DataIntegrator.Descriptions.LDAP.DSML.SearchResultEntry);
                    types[2] = typeof(DataIntegrator.Descriptions.LDAP.DSML.SearchResultReference);
                    types[3] = typeof(DataIntegrator.Descriptions.LDAP.DSML.LDAPResult);
                    types[4] = typeof(DataIntegrator.Descriptions.LDAP.DSML.ResultCode);

                    XmlSerializer           serializer = new XmlSerializer(type, types);
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add("", "urn:oasis:names:tc:DSML:2:0:core");

                    StringWriter writer = new StringWriter();

                    serializer.Serialize(writer, dsmlResponse, namespaces);

                    writer.Flush();
                    returnValue = writer.ToString();
                    writer.Close();

                    returnValue = returnValue.Replace("&#x", "HEX:");
                }
            }

            return(returnValue);
        }
Пример #25
0
        private void GetResultsHelper(LdapPartialAsyncResult asyncResult)
        {
            LdapConnection con          = asyncResult.con;
            IntPtr         ldapResult   = (IntPtr)0;
            IntPtr         entryMessage = (IntPtr)0;
            ResultAll      resultType   = ResultAll.LDAP_MSG_RECEIVED;

            if (asyncResult.resultStatus == ResultsStatus.CompleteResult)
            {
                resultType = ResultAll.LDAP_MSG_POLLINGALL;
            }

            try
            {
                SearchResponse response = (SearchResponse)con.ConstructResponse(asyncResult.messageID, LdapOperation.LdapSearch, resultType, asyncResult.requestTimeout, false);
                // this should only happen in the polling thread case
                if (response == null)
                {
                    // only when request time out has not yet expiered
                    if ((asyncResult.startTime.Ticks + asyncResult.requestTimeout.Ticks) > DateTime.Now.Ticks)
                    {
                        // this is expected, just the client does not have the result yet
                        return;
                    }
                    else
                    {
                        // time out, now we need to throw proper exception
                        throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut));
                    }
                }

                if (asyncResult.response != null)
                {
                    AddResult(asyncResult.response, response);
                }
                else
                {
                    asyncResult.response = response;
                }

                // if search is done, set the flag
                if (response.searchDone)
                {
                    asyncResult.resultStatus = ResultsStatus.Done;
                }
            }
            catch (Exception e)
            {
                if (e is DirectoryOperationException)
                {
                    SearchResponse response = (SearchResponse)(((DirectoryOperationException)e).Response);

                    if (asyncResult.response != null)
                    {
                        AddResult(asyncResult.response, response);
                    }
                    else
                    {
                        asyncResult.response = response;
                    }

                    // set the response back to the exception so it holds all the results up to now
                    ((DirectoryOperationException)e).Response = asyncResult.response;
                }
                else if (e is LdapException)
                {
                    LdapException ldapE     = (LdapException)e;
                    LdapError     errorCode = (LdapError)ldapE.ErrorCode;

                    if (asyncResult.response != null)
                    {
                        // add previous retrieved entries if available
                        if (asyncResult.response.Entries != null)
                        {
                            for (int i = 0; i < asyncResult.response.Entries.Count; i++)
                            {
                                ldapE.results.Add(asyncResult.response.Entries[i]);
                            }
                        }

                        // add previous retrieved references if available
                        if (asyncResult.response.References != null)
                        {
                            for (int i = 0; i < asyncResult.response.References.Count; i++)
                            {
                                ldapE.results.Add(asyncResult.response.References[i]);
                            }
                        }
                    }
                }

                // exception occurs, this operation is done.
                asyncResult.exception    = e;
                asyncResult.resultStatus = ResultsStatus.Done;

                // need to abandon this request
                Wldap32.ldap_abandon(con.ldapHandle, asyncResult.messageID);
            }
        }
Пример #26
0
        private DirectoryResponse ConstructElement(XmlElement node)
        {
            DirectoryResponse el = null;

            Debug.Assert(node != null);

            switch (node.LocalName)
            {
                case DsmlConstants.DsmlErrorResponse:
                    el = new DsmlErrorResponse(node);
                    break;

                case DsmlConstants.DsmlSearchResponse:
                    el = new SearchResponse(node);
                    break;

                case DsmlConstants.DsmlModifyResponse:
                    el = new ModifyResponse(node);
                    break;

                case DsmlConstants.DsmlAddResponse:
                    el = new AddResponse(node);
                    break;

                case DsmlConstants.DsmlDelResponse:
                    el = new DeleteResponse(node);
                    break;

                case DsmlConstants.DsmlModDNResponse:
                    el = new ModifyDNResponse(node);
                    break;

                case DsmlConstants.DsmlCompareResponse:
                    el = new CompareResponse(node);
                    break;

                case DsmlConstants.DsmlExtendedResponse:
                    el = new ExtendedResponse(node);
                    break;

                case DsmlConstants.DsmlAuthResponse:
                    el = new DsmlAuthResponse(node);
                    break;
                default:
                    throw new DsmlInvalidDocumentException(Res.GetString(Res.UnknownResponseElement));
            }

            Debug.Assert(el != null);

            return el;
        }
Пример #27
0
        private DirectoryException ConstructException(int error, LdapOperation operation)
        {
            DirectoryResponse response = null;

            if (Utility.IsResultCode((ResultCode)error))
            {
                if (operation == LdapOperation.LdapAdd)
                    response = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
                else if (operation == LdapOperation.LdapModify)
                    response = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
                else if (operation == LdapOperation.LdapDelete)
                    response = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
                else if (operation == LdapOperation.LdapModifyDn)
                    response = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
                else if (operation == LdapOperation.LdapCompare)
                    response = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
                else if (operation == LdapOperation.LdapSearch)
                    response = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
                else if (operation == LdapOperation.LdapExtendedRequest)
                    response = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);

                string errorMessage = OperationErrorMappings.MapResultCode(error);
                return new DirectoryOperationException(response, errorMessage);
            }
            else
            {
                if (Utility.IsLdapError((LdapError)error))
                {
                    string errorMessage = LdapErrorMappings.MapResultCode(error);
                    string serverErrorMessage = _options.ServerErrorMessage;
                    if ((serverErrorMessage != null) && (serverErrorMessage.Length > 0))
                    {
                        throw new LdapException(error, errorMessage, serverErrorMessage);
                    }
                    else
                    {
                        return new LdapException(error, errorMessage);
                    }
                }
                else
                    return new LdapException(error);
            }
        }
Пример #28
0
        public void LDAP_Delete_DynamicObject_Requirements()
        {
            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");

            #region Local variables

            string testUser     = "******";
            string testUserDN   = "CN=" + testUser + ",CN=Users," + adLdapModelAdapter.rootDomainNC;
            string testUserGuid = null;
            bool   isExist      = false;
            System.DirectoryServices.Protocols.DeleteRequest  delReq;
            System.DirectoryServices.Protocols.DeleteResponse delRep;

            #endregion

            using (LdapConnection con = new LdapConnection(
                       new LdapDirectoryIdentifier(adLdapModelAdapter.PDCIPAddress),
                       new NetworkCredential(
                           adLdapModelAdapter.DomainAdministratorName,
                           adLdapModelAdapter.DomainUserPassword,
                           adLdapModelAdapter.PrimaryDomainDnsName)))
            {
                con.SessionOptions.Sealing = false;
                con.SessionOptions.Signing = false;

                #region Delete the dynamic object to initialize the test environment

                try
                {
                    delReq = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                    delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
                    BaseTestSite.Assert.AreEqual(ResultCode.Success, delRep.ResultCode, "[Initialize] Deleting the dynamic object should success.");
                }
                catch (Exception e)
                {
                    BaseTestSite.Log.Add(LogEntryKind.Debug, "[Initialize] Deleting the dynamic object failed: {0}", e.Message);
                }

                #endregion

                #region Add the dynamic object to be deleted

                ManagedAddRequest addReq = new ManagedAddRequest(testUserDN);
                addReq.Attributes.Add(new DirectoryAttribute("objectClass", new string[] { "dynamicObject", "user" }));
                addReq.Attributes.Add(new DirectoryAttribute("entryTTL", "1800"));
                addReq.Attributes.Add(new DirectoryAttribute("sAMAccountName", testUser));
                System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
                BaseTestSite.Assert.AreEqual(ResultCode.Success, addRep.ResultCode, "Adding the dynamic object should success.");

                System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                    testUserDN,
                    "(objectClass=user)",
                    System.DirectoryServices.Protocols.SearchScope.Subtree,
                    new string[] { "objectClass" });
                System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
                DirectoryAttribute attr   = searchRep.Entries[0].Attributes["objectClass"];
                object[]           values = attr.GetValues(Type.GetType("System.String"));
                foreach (string value in values)
                {
                    if (value.Contains("dynamicObject"))
                    {
                        isExist = true;
                    }
                }
                BaseTestSite.Assert.IsTrue(isExist, "Dynamic entry should be created successfully.");

                testUserGuid = Utilities.GetUserGuid(
                    adLdapModelAdapter.PDCNetbiosName,
                    adLdapModelAdapter.PrimaryDomainDnsName,
                    adLdapModelAdapter.ADDSPortNum,
                    adLdapModelAdapter.DomainAdministratorName,
                    adLdapModelAdapter.DomainUserPassword,
                    testUser);

                #endregion

                #region delete the dynamic object and verify requirements

                delReq = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN);
                delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
                BaseTestSite.Assert.AreEqual(ResultCode.Success, delRep.ResultCode, "Deleting the dynamic object should success.");
                SearchResult tombStoneResult = Utilities.GetDeletedObject(testUserGuid, adLdapModelAdapter.defaultNC, adLdapModelAdapter.currentWorkingDC.FQDN, adLdapModelAdapter.currentPort);
                if (tombStoneResult == null)
                {
                    isExist = false;
                }
                if (adLdapModelAdapter.isTDI72765fixed)
                {
                    BaseTestSite.Assert.IsFalse(
                        isExist,
                        @"Dynamic objects are objects that are automatically deleted after a period of time. When they are deleted (automatically or manually),
                    they do not transform into any other state, such as a tombstone, deleted-object, or recycled-object. ");
                }

                #endregion
            }
        }
Пример #29
0
 protected virtual void OnTruncatedSearchResponse(string key, SearchResponse resp)
 {
 }
Пример #30
0
		private DirectoryResponse ConstructElement(XmlElement node)
		{
			DirectoryResponse dsmlErrorResponse = null;
			string localName = node.LocalName;
			string str = localName;
			if (localName != null)
			{
				if (str == "errorResponse")
				{
					dsmlErrorResponse = new DsmlErrorResponse(node);
				}
				else if (str == "searchResponse")
				{
					dsmlErrorResponse = new SearchResponse(node);
				}
				else if (str == "modifyResponse")
				{
					dsmlErrorResponse = new ModifyResponse(node);
				}
				else if (str == "addResponse")
				{
					dsmlErrorResponse = new AddResponse(node);
				}
				else if (str == "delResponse")
				{
					dsmlErrorResponse = new DeleteResponse(node);
				}
				else if (str == "modDNResponse")
				{
					dsmlErrorResponse = new ModifyDNResponse(node);
				}
				else if (str == "compareResponse")
				{
					dsmlErrorResponse = new CompareResponse(node);
				}
				else if (str == "extendedResponse")
				{
					dsmlErrorResponse = new ExtendedResponse(node);
				}
				else if (str == "authResponse")
				{
					dsmlErrorResponse = new DsmlAuthResponse(node);
				}
				else
				{
					throw new DsmlInvalidDocumentException(Res.GetString("UnknownResponseElement"));
				}
				return dsmlErrorResponse;
			}
			throw new DsmlInvalidDocumentException(Res.GetString("UnknownResponseElement"));
		}