public void LDAP_Add_EnforceSchemaConstrains_rDNAttID()
        {
            #region variables

            // OrganizationalUnit rDNAttID should be "OU=" instead of "CN="
            // Specify wrong rDNAttID to cause expected errorcode
            string userName = "******";
            string userDN   = "CN=" + userName + "," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            int    errorCode;
            bool   failed = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012R2, "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 Add Enforce Schema Constraints rDNAttID
            try
            {
                System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(userDN);
                System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            catch { }
            ManagedAddRequest addReq = new ManagedAddRequest(userDN, "organizationalUnit");
            System.DirectoryServices.Protocols.AddResponse addRep = null;
            try
            {
                addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.NamingViolation)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_RDN_DOESNT_MATCH_SCHEMA)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"The attributeType of the first label of the object DN matches the rDNAttID of 
                    the structural object class or the 88 object class. Otherwise, 
                    namingViolation / ERROR_DS_RDN_DOESNT_MATCH_SCHEMA is returned. 
                    For example, it is not allowed to create an organizationalUnit with CN=test RDN; 
                    the correct RDN for an organizationalUnit object is OU=test. If there is no class C 
                    for which the attributeType is equal to C!rDNAttID, namingViolation / <unrestricted> 
                    is returned.");
            #endregion
        }
        public void LDAP_Add_EnforceSchemaConstrains_Range()
        {
            #region variables

            //set employeeID attribute out of range, upperRange is 16
            const int upperRange          = 16;
            string    attrName            = "employeeID";
            string    attrValueOutOfRange = new string('1', upperRange + 10);
            string    userName            = "******";
            string    userDN = "CN=" + userName + ",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");
            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 Add Enforce Schema Constraints RangeUpper
            try
            {
                System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(userDN);
                System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            catch { }
            ManagedAddRequest addReq = new ManagedAddRequest(userDN, "user");
            addReq.Attributes.Add(new DirectoryAttribute(attrName, attrValueOutOfRange));
            System.DirectoryServices.Protocols.AddResponse addRep = null;
            try
            {
                addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.ConstraintViolation)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_RANGE_CONSTRAINT)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"All attribute values must be compliant with the rangeUpper and rangeLower constraints 
                    of the schema (see section 3.1.1.2.3). If a supplied value violates a rangeUpper or rangeLower
                    constraint, then the Add fails with constraintViolation / ERROR_DS_RANGE_CONSTRAINT.");
            #endregion
        }
Пример #3
0
        public void LDAP_Delete_Constraints_Protected()
        {
            #region variables

            int    errorCode;
            bool   failed         = false;
            string protectedObjDN = "cn=RID Set,cn=" + adLdapModelAdapter.PDCNetbiosName + ",ou=domain controllers," + adLdapModelAdapter.rootDomainNC;

            #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(adLdapModelAdapter.PDCNetbiosName),
                                                    new NetworkCredential(adLdapModelAdapter.DomainAdministratorName,
                                                                          adLdapModelAdapter.DomainUserPassword,
                                                                          adLdapModelAdapter.PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region delete protected

            System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(protectedObjDN);
            delReq.Controls.Add(new TreeDeleteControl());
            System.DirectoryServices.Protocols.DeleteResponse delRep = null;
            try
            {
                delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.UnwillingToPerform)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_CANT_DELETE)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"If the object being deleted is protected (see section 3.1.1.5.5.3, Protected Objects) and does not fall into
                the two categories above, unwillingToPerform / ERROR_DS_CANT_DELETE is returned.");
            failed = false;

            #endregion
        }
Пример #4
0
        public void LDAP_Delete_Constraints_nTDSDSA()
        {
            #region variables

            bool   failed = false;
            int    errorCode;
            string serverDN = "cn=" + adLdapModelAdapter.PDCNetbiosName + ",cn=servers,cn=default-first-site-name,cn=sites,cn=configuration," + adLdapModelAdapter.rootDomainNC;

            #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(adLdapModelAdapter.PDCIPAddress),
                                                    new NetworkCredential(adLdapModelAdapter.DomainAdministratorName,
                                                                          adLdapModelAdapter.DomainUserPassword,
                                                                          adLdapModelAdapter.PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region Delete constraint for class nTDSDSA

            System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(serverDN);
            delReq.Controls.Add(new TreeDeleteControl());
            System.DirectoryServices.Protocols.DeleteResponse delRep = null;
            try
            {
                delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.UnwillingToPerform)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_CANT_DELETE_DSA_OBJ)
                    {
                        failed = true;
                    }
                }
            }

            BaseTestSite.Assert.IsTrue(
                failed,
                @"If the object being deleted is the DC's nTDSDSA object or any of its ancestors, 
                unwillingToPerform / ERROR_DS_CANT_DELETE_DSA_OBJ is returned.");

            #endregion
        }
Пример #5
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);
            }
        }
Пример #6
0
        public void Delete(LdapConnection ldap)
        {
            CheckForDeletion();

            if (this.IsNewEntry)
            {
                throw new InvalidOperationException(String.Format("Entry {0} was never committed - cannot delete", 
                    this.DistinguishedName));
            }

            DeleteRequest del = new DeleteRequest(this.DistinguishedName);
            ldap.SendRequest(del);
            
            this.IsDeleted = true;
        }
Пример #7
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
        }
Пример #8
0
        public void LDAP_Delete_Truncate_RDN()
        {
            //This case is implemented to test the RDN size limitations on a deleted object
            //MS-ADTS section 3.1.5.5:
            //If O is the object that is deleted, the delete-mangled RDN is the concatenation of O!name,
            //the character with value 0x0A, the string "DEL:", and the dashed string representation ([RFC4122] section 3)
            //of O!objectGUID. During this concatenation, if required, the O!name part is truncated to ensure that the
            //length of the delete-mangled RDN does not violate the RDN size constraint in section 3.1.1.5.1.2.
            //MS-ADTS section 3.1.1.5.1.2:
            //The RDN must not contain a character with value 0xA
            //The RDN must not contain a charater with value 0x0
            //The RDN size must be less than 255 characters

            //However, When trying to form a RDN that will exceed the size limitation when deleted:
            //MS-ADA1 section 2.110: Attribute cn has rangeUpper: 64
            //That said, the length of a delete-mangled RDN can only be up to 107 characters (not including the terminating NUL character):
            //{delete-mangled RDN: length} = {rangeUpper:64} + {'\\' :2} + {0x0A :1} + {'DEL:':4} + {dashed-string-Guid:36} = 107 < 255.
            //Therefore, the delete-managled RDN can never be larger than 255 characters.

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            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 variables
            const int maxRDNLen    = 255;
            const int maxCNLen     = 64;
            string    delObjName   = new string('a', maxCNLen);
            string    delObjDN     = "CN=" + delObjName + ",CN=Users," + adLdapModelAdapter.rootDomainNC;
            string    tombStoneDN  = null;
            string    tombStoneRDN = null;

            #endregion

            #region Add the object for delete testing
            try
            {
                ManagedAddRequest addReq = new ManagedAddRequest(delObjDN, "user");
                System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }
            catch { }
            #endregion

            System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(delObjDN);
            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, delObjDN.Split(',')[0].Split('=')[1].Trim());
            if (tombStoneResult != null)
            {
                foreach (string key in tombStoneResult.Properties.PropertyNames)
                {
                    foreach (object value in tombStoneResult.Properties[key])
                    {
                        if (key.ToLower(CultureInfo.InvariantCulture) == "distinguishedname")
                        {
                            tombStoneDN = value.ToString();
                        }
                    }
                }
            }
            tombStoneRDN = tombStoneDN.Split(',')[0].Split('=')[1].Trim();
            BaseTestSite.Assert.IsTrue(tombStoneRDN.Length <= maxRDNLen, "MS-ADTS section 3.1.1.5.1.2: The RDN size must be less than 255 characters");
        }
Пример #9
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
            }
        }
Пример #10
0
        /// <summary>
        /// Eliminar un usuario del ADAM
        /// </summary>
        /// <param name="UserLogin">LoginName</param>
        /// <returns></returns>
        public ResultCode DeleteUser(string UserLogin)
        {
            if (!this.UserExist(UserLogin))
                return ResultCode.NoSuchObject;

            this.OpenConnection();
            string userDN = string.Format("CN={0},{1}", UserLogin, this._usersDistinguishedName);

            DeleteRequest delRequest = new DeleteRequest(userDN);
            DeleteResponse delResponse = (DeleteResponse)this._adamConnection.SendRequest(delRequest);

            this.CloseConnection();
            return delResponse.ResultCode;
        }
Пример #11
0
        /// <summary>
        /// Deletes an entry from the LDAP directory with the specified distinguished name.
        /// </summary>
        /// <param name="dn">The distinguished name of the entry to delete.</param>
        /// <returns>True if deleted, false otherwise.</returns>
        public bool Delete(string dn)
        {
            if (!string.IsNullOrWhiteSpace(dn))
            {
                DeleteRequest request = new DeleteRequest(dn);
                try
                {
                    DeleteResponse response = (DeleteResponse)connection.SendRequest(request);

                    // Check that a response was received.
                    if (response != null)
                    {
                        // A response was received.
                        if (response.ResultCode == ResultCode.Success)
                        {
                            return true;
                        }
                    }
                    else
                    {
                        // A response was not received.
                        return false;
                    }
                }
                catch
                {
                }
            }
            return false;
        }
        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
                }
            }
        }
        public void LDAP_AD_DS_Modify_Constraints_DisallowedAttributes()
        {
            #region variables

            //The values of the attributes are not important, but should be complied with the attribute syntax
            string attrValue = "100";
            int    attrNum;
            int    errorCode;
            bool   failed      = false;
            string userName    = "******";
            string userDN      = "CN=" + userName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string groupName   = "tempGroup";
            string groupDN     = "CN=" + groupName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            string testObjName = "tempObj";
            string testObjDN   = "CN=" + testObjName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;

            #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 user, a group and a non SAM-specific object(classStore) to test modify constraints

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

            #endregion

            #region Modify constraint for class user
            attrNum = 15;
            System.DirectoryServices.Protocols.DirectoryAttributeModification[] modAttr1 = new DirectoryAttributeModification[attrNum];
            for (int i = 0; i < attrNum; i++)
            {
                modAttr1[i]           = new DirectoryAttributeModification();
                modAttr1[i].Operation = DirectoryAttributeOperation.Replace;
                modAttr1[i].Add(attrValue);
            }
            modAttr1[0].Name  = "badPasswordTime";
            modAttr1[1].Name  = "badPwdCount";
            modAttr1[2].Name  = "dBCSPwd";
            modAttr1[3].Name  = "lastLogoff";
            modAttr1[4].Name  = "lastLogon";
            modAttr1[5].Name  = "lastLogonTimestamp";
            modAttr1[6].Name  = "lmPwdHistory";
            modAttr1[7].Name  = "logonCount";
            modAttr1[8].Name  = "memberOf";
            modAttr1[9].Name  = "msDS-User-Account-Control-Computed";
            modAttr1[10].Name = "ntPwdHistory";
            modAttr1[11].Name = "rid";
            modAttr1[12].Name = "sAMAccountType";
            modAttr1[13].Name = "supplementalCredentials";
            modAttr1[14].Name = "isCriticalSystemObject";
            modAttr1[14].Clear();
            modAttr1[14].Add("TRUE");

            for (int i = 0; i < attrNum; i++)
            {
                System.DirectoryServices.Protocols.ModifyRequest  modReq = new System.DirectoryServices.Protocols.ModifyRequest(userDN, modAttr1[i]);
                System.DirectoryServices.Protocols.ModifyResponse modRep = null;
                try
                {
                    modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
                }
                catch (DirectoryOperationException e)
                {
                    if (e.Response.ResultCode == ResultCode.UnwillingToPerform)
                    {
                        errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                        if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ATTRIBUTE_OWNED_BY_SAM)
                        {
                            failed = true;
                        }
                    }
                }
                BaseTestSite.Assert.IsTrue(
                    failed,
                    @"In AD DS, the following attributes are disallowed in a Modify for an object of class user:
                    badPasswordTime, badPwdCount, dBCSPwd, isCriticalSystemObject, lastLogoff, lastLogon, 
                    lastLogonTimestamp, lmPwdHistory, logonCount, memberOf, msDS-User-Account-Control-Computed, 
                    ntPwdHistory, objectSid, rid, sAMAccountType, and supplementalCredentials. If one of these 
                    attributes is specified in an Add, the Add returns unwillingToPerform / ERROR_DS_ATTRIBUTE_OWNED_BY_SAM.");
                failed = false;
            }

            #endregion

            #region Modify constraint for class group
            attrNum = 5;
            System.DirectoryServices.Protocols.DirectoryAttributeModification[] modAttr2 = new DirectoryAttributeModification[attrNum];
            for (int i = 0; i < attrNum; i++)
            {
                modAttr2[i]           = new DirectoryAttributeModification();
                modAttr2[i].Operation = DirectoryAttributeOperation.Replace;
                modAttr2[i].Add(attrValue);
            }
            modAttr2[0].Name = "memberOf";
            modAttr2[1].Name = "rid";
            modAttr2[1].Clear();
            modAttr2[1].Add("512");
            modAttr2[2].Name = "sAMAccountType";
            modAttr2[2].Clear();
            modAttr2[2].Add("805306370");
            modAttr2[3].Name = "userPassword";
            modAttr2[4].Name = "isCriticalSystemObject";
            modAttr2[4].Clear();
            modAttr2[4].Add("TRUE");

            for (int i = 0; i < attrNum; i++)
            {
                System.DirectoryServices.Protocols.ModifyRequest  modReq = new System.DirectoryServices.Protocols.ModifyRequest(groupDN, modAttr2[i]);
                System.DirectoryServices.Protocols.ModifyResponse modRep = null;
                try
                {
                    modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
                }
                catch (DirectoryOperationException e)
                {
                    if (e.Response.ResultCode == ResultCode.UnwillingToPerform)
                    {
                        errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                        if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ATTRIBUTE_OWNED_BY_SAM)
                        {
                            failed = true;
                        }
                    }
                }
                BaseTestSite.Assert.IsTrue(
                    failed,
                    @"In AD DS, the following attributes are disallowed in a Modify for an object of class group:
                    isCriticalSystemObject, memberOf, objectSid, rid, sAMAccountType, and userPassword. 
                    If one of these attributes is specified in an Add, the Add returns unwillingToPerform / ERROR_DS_ATTRIBUTE_OWNED_BY_SAM.");
                failed = false;
            }

            #endregion

            #region Modify constraint for class not a SAM-specific object class

            attrNum = 7;
            System.DirectoryServices.Protocols.DirectoryAttributeModification[] modAttr3 = new DirectoryAttributeModification[attrNum];
            for (int i = 0; i < attrNum; i++)
            {
                modAttr3[i]           = new DirectoryAttributeModification();
                modAttr3[i].Operation = DirectoryAttributeOperation.Replace;
                modAttr3[i].Add(attrValue);
            }
            modAttr3[0].Name = "lmPwdHistory";
            modAttr3[1].Name = "ntPwdHistory";
            modAttr3[2].Name = "samAccountName";
            modAttr3[3].Name = "sAMAccountType";
            modAttr3[3].Clear();
            modAttr3[3].Add("805306370");
            modAttr3[4].Name = "supplementalCredentials";
            modAttr3[5].Name = "unicodePwd";
            modAttr3[6].Name = "isCriticalSystemObject";
            modAttr3[6].Clear();
            modAttr3[6].Add("TRUE");

            for (int i = 0; i < attrNum; i++)
            {
                System.DirectoryServices.Protocols.ModifyRequest  modReq = new System.DirectoryServices.Protocols.ModifyRequest(testObjDN, modAttr3[i]);
                System.DirectoryServices.Protocols.ModifyResponse modRep = null;
                try
                {
                    modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
                }
                catch (DirectoryOperationException e)
                {
                    if (e.Response.ResultCode == ResultCode.UnwillingToPerform)
                    {
                        errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                        if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ILLEGAL_MOD_OPERATION)
                        {
                            failed = true;
                        }
                    }
                }
                BaseTestSite.Assert.IsTrue(
                    failed,
                    @"In AD DS, the following attributes are disallowed in an Add for an object whose
                    class is not a SAM-specific object class (see 3.1.1.5.2.3): isCriticalSystemObject,
                    lmPwdHistory, ntPwdHistory, objectSid, samAccountName, sAMAccountType, supplementalCredentials,
                    and unicodePwd. If one of these attributes is specified in an Add, the Add returns
                    unwillingToPerform / ERROR_DS_ILLEGAL_MOD_OPERATION.");
                failed = false;
            }

            #endregion

            #region Delete all the test user, groups and not SAM-specific objects

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

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

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

            #endregion
        }
        public void LDAP_AD_DS_Modify_Constraints_MultipleDescriptions()
        {
            #region variables

            string userName = "******";
            string userDN   = "CN=" + userName + ",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 an object for modify constraint test

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

            #endregion

            #region Modify constraint for class user

            System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(
                userDN,
                DirectoryAttributeOperation.Add,
                "description",
                new string[] { "aaa", "bbb" });
            System.DirectoryServices.Protocols.ModifyResponse modRep = null;
            try
            {
                modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.AttributeOrValueExists)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_SINGLE_VALUE_CONSTRAINT)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"If the modify operation adds or replaces values of the description attribute on a SAM-specific object
                    (section 3.1.1.5.2.3), and results in more than one value in the attribute, then the modification fails 
                    with attributeOrValueExists / ERROR_DS_SINGLE_VALUE_CONSTRAINT.");

            #endregion

            #region Delete the user for modify test

            System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(
                "CN=testModifyConstraints,CN=users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC);
            System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);

            #endregion
        }
Пример #15
0
        static void Delete(string server, string searchBase, string filter, int connCount, System.Net.NetworkCredential nc)
        {
            using (LdapConnection conn = new LdapConnection(server))
            {
                conn.SessionOptions.ProtocolVersion = 3;
                conn.Credential = nc ?? System.Net.CredentialCache.DefaultNetworkCredentials;
                conn.AutoBind = false;
                conn.Bind();

                IList<LdapConnection> conns = new List<LdapConnection>();
                for (int i = 0; i < connCount; i++)
                {
                    var c = new LdapConnection(server);

                    c.SessionOptions.ProtocolVersion = 3;
                    c.Credential = nc;
                    c.AutoBind = false;
                    c.Bind();

                    conns.Add(c);
                }

                Console.WriteLine("Created {0} connections", conns.Count);

                var req = new SearchRequest
                {
                    DistinguishedName = searchBase,
                    Filter = filter ?? "(&(objectClass=person)(cn=*CNF:*))"
                };

                req.Attributes.Add("1.1");

                req.Controls.Add(new PageResultRequestControl(1000)
                {
                    IsCritical = false
                });

                while (true)
                {
                    var resp = (SearchResponse)conn.SendRequest(req);
                    var lazy = new LazyCommitControl() { IsCritical = false };

                    Parallel.ForEach(ISE(resp.Entries), entry =>
                    {
                        try
                        {
                            var delreq = new DeleteRequest(entry.DistinguishedName);
                            delreq.Controls.Add(lazy);

                            conns[Thread.CurrentThread.ManagedThreadId % connCount].SendRequest(delreq);

                            Console.Error.WriteLine("Deleted {0}", entry.DistinguishedName);
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine("Failed to delete {0}: {1}", entry.DistinguishedName, ex.Message);
                            throw;
                        }
                    }
                    );

                    if (resp.Controls.Length == 0)
                        break;

                    var prc = (PageResultResponseControl)resp.Controls[0];
                    if (prc.Cookie.Length == 0)
                        break;

                    Console.WriteLine("On to the next page!");

                    req.Controls.Clear();
                    req.Controls.Add(new PageResultRequestControl(prc.Cookie));
                }

                Console.WriteLine("Complete");
            }
        }
Пример #16
0
 /// <summary>
 /// This method shows how to delete anything by its distinguised name (DN).
 /// </summary>
 /// <param name="dn">Distinguished name of the entry to delete</param>
 public void delete(string dn)
 {
     var request = new DeleteRequest(dn);
     connection.SendRequest(request);
 }
        public void LDAP_Add_EnforceSchemaConstrains_mustContain()
        {
            #region variables

            string userName = "******";
            string userDN   = "CN=" + userName + ",CN=users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            int    errorCode;
            bool   failed = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012R2, "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 Add Enforce Schema Constraints mustContain
            try
            {
                System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(userDN);
                System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            catch { }
            ManagedAddRequest addReq = new ManagedAddRequest(userDN, "groupOfUniqueNames");
            // classSchema for groupOfUniqueNames mustContain requires a uniqueMember attribtue
            // Not specifying the mustContain attribute when operating LDAP add will cause objectClassViolation error.
            System.DirectoryServices.Protocols.AddResponse addRep = null;
            try
            {
                addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.ObjectClassViolation)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_MISSING_REQUIRED_ATT)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"The mayContain/mustContain constraints that are applicable based on the 
                      selected objectClass values are enforced. The computation of the 
                      mayContain/mustContain set takes into consideration the complete inheritance 
                      chain of the structural objectClass and the 88 object class as well as any 
                      auxiliary classes supplied. If any attributes in the mustContain set are not 
                      provided, the Add fails with objectClassViolation / <unrestricted>. If any 
                      attributes provided are not present in either the mayContain or mustContain 
                      sets, the Add fails with objectClassViolation / <unrestricted>.");
            #endregion
        }
Пример #18
0
        public void LDAP_Delete_Constraints_CrossRef_CantOnNonLeaf()
        {
            #region variables

            int    errorCode;
            bool   failed            = false;
            string fullDomainName    = adLdapModelAdapter.PrimaryDomainDnsName;
            string netBiosDomainName = adLdapModelAdapter.PrimaryDomainNetBiosName;

            // This "default domain NC" CrossRef object has nCName attribute DN1 which is ancestor of
            // "config NC" CrossRef object's nCName attribute DN2, DN2 is ancestor of
            // "schema NC" CrossRef object's nCName attribute DN3, which is actually the leaf node
            // Ancestor relationship: DN1 -> DN2 -> DN3
            string[] crossRefDN = new string[3];
            crossRefDN[0] = "cn=" + netBiosDomainName + ",cn=partitions,cn=configuration," + adLdapModelAdapter.rootDomainNC;
            crossRefDN[1] = "cn=enterprise configuration,cn=partitions,cn=configuration," + adLdapModelAdapter.rootDomainNC;

            #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(adLdapModelAdapter.PDCIPAddress),
                                                    new NetworkCredential(adLdapModelAdapter.DomainAdministratorName,
                                                                          adLdapModelAdapter.DomainUserPassword,
                                                                          adLdapModelAdapter.PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region crossRef

            for (int i = 0; i < 2; i++)
            {
                System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(crossRefDN[i]);
                delReq.Controls.Add(new TreeDeleteControl());
                System.DirectoryServices.Protocols.DeleteResponse delRep = null;
                try
                {
                    delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
                }
                catch (DirectoryOperationException e)
                {
                    if (e.Response.ResultCode == ResultCode.NotAllowedOnNonLeaf)
                    {
                        errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                        if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_CANT_ON_NON_LEAF)
                        {
                            failed = true;
                        }
                    }
                }
                BaseTestSite.Assert.IsTrue(
                    failed,
                    @"If the crossRef object is a child of the CN=Partitions child of the config NC and the nCName attribute of 
                    the crossRef object is set to the value DN1 and there exists another crossRef object with the same parent where
                    the nCName attribute of the second crossRef object is set to the value DN2, and the object referred to by DN1 
                    is an ancestor of the object referred to by DN2, then notAllowedOnNonLeaf / ERROR_DS_CANT_ON_NON_LEAF is returned.");
                failed = false;
            }

            #endregion
        }
        public void LDAP_Add_EnforceSchemaConstrains_isSingleValued()
        {
            #region variables

            // [MS-ADA1] section 2.217 Attibute employeeID
            // isSingleValued: TRUE
            // set employeeID attribute with multiple values, will cause constraint violation
            string attrName   = "employeeID";
            string attrValue1 = "1";
            string attrValue2 = "2";
            string attrValue3 = "3";
            string userName   = "******";
            string userDN     = "CN=" + userName + ",CN=users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            int    errorCode;
            bool   failed = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012R2, "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 Add Enforce Schema Constraints isSingleValued
            try
            {
                System.DirectoryServices.Protocols.DeleteRequest  delReq = new System.DirectoryServices.Protocols.DeleteRequest(userDN);
                System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
            }
            catch { }
            ManagedAddRequest addReq = new ManagedAddRequest(userDN, "user");
            addReq.Attributes.Add(new DirectoryAttribute(attrName, attrValue1, attrValue2, attrValue3));
            System.DirectoryServices.Protocols.AddResponse addRep = null;
            try
            {
                addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }
            catch (DirectoryOperationException e)
            {
                if (e.Response.ResultCode == ResultCode.ConstraintViolation)
                {
                    errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                    if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_SINGLE_VALUE_CONSTRAINT)
                    {
                        failed = true;
                    }
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"All attribute values must be compliant with the isSingleValued constraint of the schema 
                    (see section 3.1.1.2.3). If multiple values are provided for an attribute that is single-valued, 
                    then the Add fails with constraintViolation / <unrestricted>.");
            #endregion
        }
Пример #20
0
        public void LDAP_Delete_Constraints_CrossRef_NCStillHasDsas()
        {
            #region variables

            int    errorCode;
            bool   failed            = false;
            string fullDomainName    = adLdapModelAdapter.PrimaryDomainDnsName;
            string netBiosDomainName = adLdapModelAdapter.PrimaryDomainNetBiosName;

            // This "default domain NC" CrossRef object has nCName attribute DN1 which is ancestor of
            // "config NC" CrossRef object's nCName attribute DN2, DN2 is ancestor of
            // "schema NC" CrossRef object's nCName attribute DN3, which is actually the leaf node
            // Ancestor relationship: DN1 -> DN2 -> DN3
            // "schema NC" is hosted by this connnected domain controller
            string[] crossRefDN = new string[1];
            crossRefDN[0] = "cn=enterprise schema,cn=partitions,cn=configuration," + adLdapModelAdapter.rootDomainNC;

            #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(adLdapModelAdapter.PDCIPAddress),
                                                    new NetworkCredential(adLdapModelAdapter.DomainAdministratorName,
                                                                          adLdapModelAdapter.DomainUserPassword,
                                                                          adLdapModelAdapter.PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region crossRef

            for (int i = 0; i < 1; i++)
            {
                System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(crossRefDN[i]);
                delReq.Controls.Add(new TreeDeleteControl());
                System.DirectoryServices.Protocols.DeleteResponse delRep = null;
                try
                {
                    delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq);
                }
                catch (DirectoryOperationException e)
                {
                    if (e.Response.ResultCode == ResultCode.UnwillingToPerform)
                    {
                        errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);
                        if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_NC_STILL_HAS_DSAS)
                        {
                            failed = true;
                        }
                    }
                }
                BaseTestSite.Assert.IsTrue(
                    failed,
                    @"Else if the crossRef object is a child of the CN=Partitions child of the config NC, 
                    and the crossRef object’s NC is hosted by some domain controller, unwillingToPerform / ERROR_DS_NC_STILL_HAS_DSAS
                    is returned.");
                failed = false;
            }

            #endregion
        }
        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
        }
        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
        }