Ejemplo n.º 1
0
 protected static void AssertSuccess(ModifyResponse response)
 {
     if (response == null)
         throw new LdapException("Incorrect response returned from server.");
     if (response.ResultCode != ResultCode.Success)
         throw new LdapException(string.Format("Modify request returned '{0}' with message '{1}'.", response.ResultCode, response.ErrorMessage));
 }
Ejemplo n.º 2
0
        private DirectoryResponse ConstructElement(XmlElement node)
        {
            DirectoryResponse el = null;

            Debug.Assert(node != null);

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

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

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

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

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

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

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

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

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

            default:
                throw new DsmlInvalidDocumentException(Res.GetString(Res.UnknownResponseElement));
            }

            Debug.Assert(el != null);

            return(el);
        }
Ejemplo n.º 3
0
        private DirectoryResponse ConstructElement(XmlElement node)
        {
            DirectoryResponse dsmlErrorResponse = null;
            string            localName         = node.LocalName;
            string            str = localName;

            if (localName != null)
            {
                if (str == "errorResponse")
                {
                    dsmlErrorResponse = new DsmlErrorResponse(node);
                }
                else if (str == "searchResponse")
                {
                    dsmlErrorResponse = new SearchResponse(node);
                }
                else if (str == "modifyResponse")
                {
                    dsmlErrorResponse = new ModifyResponse(node);
                }
                else if (str == "addResponse")
                {
                    dsmlErrorResponse = new AddResponse(node);
                }
                else if (str == "delResponse")
                {
                    dsmlErrorResponse = new DeleteResponse(node);
                }
                else if (str == "modDNResponse")
                {
                    dsmlErrorResponse = new ModifyDNResponse(node);
                }
                else if (str == "compareResponse")
                {
                    dsmlErrorResponse = new CompareResponse(node);
                }
                else if (str == "extendedResponse")
                {
                    dsmlErrorResponse = new ExtendedResponse(node);
                }
                else if (str == "authResponse")
                {
                    dsmlErrorResponse = new DsmlAuthResponse(node);
                }
                else
                {
                    throw new DsmlInvalidDocumentException(Res.GetString("UnknownResponseElement"));
                }
                return(dsmlErrorResponse);
            }
            throw new DsmlInvalidDocumentException(Res.GetString("UnknownResponseElement"));
        }
Ejemplo n.º 4
0
        private DirectoryException ConstructException(int error, LdapOperation operation)
        {
            DirectoryResponse response = null;

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

                string errorMessage = OperationErrorMappings.MapResultCode(error);
                return new DirectoryOperationException(response, errorMessage);
            }
            else
            {
                if (Utility.IsLdapError((LdapError)error))
                {
                    string errorMessage = LdapErrorMappings.MapResultCode(error);
                    string serverErrorMessage = _options.ServerErrorMessage;
                    if ((serverErrorMessage != null) && (serverErrorMessage.Length > 0))
                    {
                        throw new LdapException(error, errorMessage, serverErrorMessage);
                    }
                    else
                    {
                        return new LdapException(error, errorMessage);
                    }
                }
                else
                    return new LdapException(error);
            }
        }
Ejemplo n.º 5
0
        internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
        {
            int error;
            LDAP_TIMEVAL timeout = new LDAP_TIMEVAL();
            timeout.tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond);
            IntPtr ldapResult = (IntPtr)0;
            DirectoryResponse response = null;

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

            IntPtr entryMessage = (IntPtr)0;

            bool needAbandon = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // throw proper exception here            
            throw ConstructException(error, operation);
        }
        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
        }
Ejemplo n.º 7
0
        private DirectoryResponse ConstructElement(XmlElement node)
        {
            DirectoryResponse el = null;

            Debug.Assert(node != null);

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

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

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

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

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

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

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

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

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

            Debug.Assert(el != null);

            return el;
        }
        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_Modify_ObjectClass_Updates()
        {
            #region variables

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

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2003, "Server OS version should be not less than Windows Server 2003");
            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));

            #endregion

            #region Modify Object Class Update for class user

            System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(
                userDN,
                DirectoryAttributeOperation.Replace,
                "objectClass",
                "computer");
            System.DirectoryServices.Protocols.ModifyResponse modRep = null;
            try
            {
                modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
            }
            catch (DirectoryOperationException e)
            {
                if (EnvironmentConfig.ServerVer == ServerVersion.Win2003)
                {
                    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;
                        }
                    }
                }
                else if (EnvironmentConfig.ServerVer >= ServerVersion.Win2008)
                {
                    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_ILLEGAL_MOD_OPERATION)
                        {
                            failed = true;
                        }
                    }
                }
                else
                {
                    failed = false;
                }
            }
            BaseTestSite.Assert.IsTrue(
                failed,
                @"If the DC functional level is DS_BEHAVIOR_WIN2003, unwillingToPerform / ERROR_DS_ILLEGAL_MOD_OPERATION is returned.
                If the DC functional level is DS_BEHAVIOR_WIN2008 or greater, objectClassViolation / ERROR_DS_ILLEGAL_MOD_OPERATION is returned.");

            #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
        }
        public void LDAP_Modify_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");
            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 Modify Enforce Schema Constraints RangeUpper

            if (!Utilities.IsObjectExist(userDN, addr, port))
            {
                ManagedAddRequest addReq = new ManagedAddRequest(userDN, "user");
                System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq);
            }
            System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(
                userDN,
                DirectoryAttributeOperation.Add,
                attrName,
                attrValueOutOfRange);
            System.DirectoryServices.Protocols.ModifyResponse modRep = null;
            try
            {
                modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq);
            }
            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

            #region delete the test user

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

            #endregion
        }
Ejemplo n.º 13
0
		private DirectoryException ConstructException(int error, LdapOperation operation)
		{
			DirectoryResponse extendedResponse = null;
			if (!Utility.IsResultCode((ResultCode)error))
			{
				if (!Utility.IsLdapError((LdapError)error))
				{
					return new LdapException(error);
				}
				else
				{
					string str = LdapErrorMappings.MapResultCode(error);
					string serverErrorMessage = this.options.ServerErrorMessage;
					if (serverErrorMessage == null || serverErrorMessage.Length <= 0)
					{
						return new LdapException(error, str);
					}
					else
					{
						throw new LdapException(error, str, serverErrorMessage);
					}
				}
			}
			else
			{
				if (operation != LdapOperation.LdapAdd)
				{
					if (operation != LdapOperation.LdapModify)
					{
						if (operation != LdapOperation.LdapDelete)
						{
							if (operation != LdapOperation.LdapModifyDn)
							{
								if (operation != LdapOperation.LdapCompare)
								{
									if (operation != LdapOperation.LdapSearch)
									{
										if (operation == LdapOperation.LdapExtendedRequest)
										{
											extendedResponse = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
										}
									}
									else
									{
										extendedResponse = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
									}
								}
								else
								{
									extendedResponse = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
								}
							}
							else
							{
								extendedResponse = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
							}
						}
						else
						{
							extendedResponse = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
						}
					}
					else
					{
						extendedResponse = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
					}
				}
				else
				{
					extendedResponse = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
				}
				string str1 = OperationErrorMappings.MapResultCode(error);
				return new DirectoryOperationException(extendedResponse, str1);
			}
		}
Ejemplo n.º 14
0
		internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
		{
			DirectoryResponse directoryResponse;
			LDAP_TIMEVAL lDAPTIMEVAL = new LDAP_TIMEVAL();
			lDAPTIMEVAL.tv_sec = (int)(requestTimeOut.Ticks / (long)0x989680);
			IntPtr intPtr = (IntPtr)0;
			DirectoryResponse searchResponse = null;
			IntPtr intPtr1 = (IntPtr)0;
			IntPtr intPtr2 = (IntPtr)0;
			bool flag = true;
			if (resultType != ResultAll.LDAP_MSG_ALL)
			{
				lDAPTIMEVAL.tv_sec = 0;
				lDAPTIMEVAL.tv_usec = 0;
				if (resultType == ResultAll.LDAP_MSG_POLLINGALL)
				{
					resultType = ResultAll.LDAP_MSG_ALL;
				}
				flag = false;
			}
			int num = Wldap32.ldap_result(this.ldapHandle, messageId, (int)resultType, lDAPTIMEVAL, ref intPtr);
			if (num == -1 || num == 0)
			{
				if (num != 0)
				{
					num = Wldap32.LdapGetLastError();
				}
				else
				{
					if (!exceptionOnTimeOut)
					{
						return null;
					}
					else
					{
						num = 85;
					}
				}
				if (flag)
				{
					Wldap32.ldap_abandon(this.ldapHandle, messageId);
				}
			}
			else
			{
				int num1 = 0;
				try
				{
					int num2 = 0;
					string str = null;
					string str1 = null;
					Uri[] uriArray = null;
					DirectoryControl[] directoryControlArray = null;
					if (num != 100 && num != 115)
					{
						num2 = this.ConstructParsedResult(intPtr, ref num1, ref str, ref str1, ref uriArray, ref directoryControlArray);
					}
					if (num2 != 0)
					{
						num = num2;
						throw this.ConstructException(num, operation);
					}
					else
					{
						num2 = num1;
						if (num != 105)
						{
							if (num != 103)
							{
								if (num != 107)
								{
									if (num != 109)
									{
										if (num != 111)
										{
											if (num != 120)
											{
												if (num == 101 || num == 100 || num == 115)
												{
													searchResponse = new SearchResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
													if (num == 101)
													{
														((SearchResponse)searchResponse).searchDone = true;
													}
													SearchResultEntryCollection searchResultEntryCollection = new SearchResultEntryCollection();
													SearchResultReferenceCollection searchResultReferenceCollection = new SearchResultReferenceCollection();
													IntPtr intPtr3 = Wldap32.ldap_first_entry(this.ldapHandle, intPtr);
													int num3 = 0;
													while (intPtr3 != (IntPtr)0)
													{
														SearchResultEntry searchResultEntry = this.ConstructEntry(intPtr3);
														if (searchResultEntry != null)
														{
															searchResultEntryCollection.Add(searchResultEntry);
														}
														num3++;
														intPtr3 = Wldap32.ldap_next_entry(this.ldapHandle, intPtr3);
													}
													IntPtr intPtr4 = Wldap32.ldap_first_reference(this.ldapHandle, intPtr);
													while (intPtr4 != (IntPtr)0)
													{
														SearchResultReference searchResultReference = this.ConstructReference(intPtr4);
														if (searchResultReference != null)
														{
															searchResultReferenceCollection.Add(searchResultReference);
														}
														intPtr4 = Wldap32.ldap_next_reference(this.ldapHandle, intPtr4);
													}
													((SearchResponse)searchResponse).SetEntries(searchResultEntryCollection);
													((SearchResponse)searchResponse).SetReferences(searchResultReferenceCollection);
												}
											}
											else
											{
												searchResponse = new ExtendedResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
												if (num2 == 0)
												{
													num2 = Wldap32.ldap_parse_extended_result(this.ldapHandle, intPtr, ref intPtr1, ref intPtr2, 0);
													if (num2 == 0)
													{
														string stringUni = null;
														if (intPtr1 != (IntPtr)0)
														{
															stringUni = Marshal.PtrToStringUni(intPtr1);
														}
														byte[] numArray = null;
														if (intPtr2 != (IntPtr)0)
														{
															berval _berval = new berval();
															Marshal.PtrToStructure(intPtr2, _berval);
															if (_berval.bv_len != 0 && _berval.bv_val != (IntPtr)0)
															{
																numArray = new byte[_berval.bv_len];
																Marshal.Copy(_berval.bv_val, numArray, 0, _berval.bv_len);
															}
														}
														((ExtendedResponse)searchResponse).name = stringUni;
														((ExtendedResponse)searchResponse).@value = numArray;
													}
												}
											}
										}
										else
										{
											searchResponse = new CompareResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
										}
									}
									else
									{
										searchResponse = new ModifyDNResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
									}
								}
								else
								{
									searchResponse = new DeleteResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
								}
							}
							else
							{
								searchResponse = new ModifyResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
							}
						}
						else
						{
							searchResponse = new AddResponse(str, directoryControlArray, (ResultCode)num2, str1, uriArray);
						}
						if (num2 == 0 || num2 == 5 || num2 == 6 || num2 == 10 || num2 == 9)
						{
							directoryResponse = searchResponse;
						}
						else
						{
							if (!Utility.IsResultCode((ResultCode)num2))
							{
								throw new DirectoryOperationException(searchResponse);
							}
							else
							{
								throw new DirectoryOperationException(searchResponse, OperationErrorMappings.MapResultCode(num2));
							}
						}
					}
				}
				finally
				{
					if (intPtr1 != (IntPtr)0)
					{
						Wldap32.ldap_memfree(intPtr1);
					}
					if (intPtr2 != (IntPtr)0)
					{
						Wldap32.ldap_memfree(intPtr2);
					}
					if (intPtr != (IntPtr)0)
					{
						Wldap32.ldap_msgfree(intPtr);
					}
				}
				return directoryResponse;
			}
			throw this.ConstructException(num, operation);
		}
Ejemplo n.º 15
0
		private DirectoryResponse ConstructElement(XmlElement node)
		{
			DirectoryResponse dsmlErrorResponse = null;
			string localName = node.LocalName;
			string str = localName;
			if (localName != null)
			{
				if (str == "errorResponse")
				{
					dsmlErrorResponse = new DsmlErrorResponse(node);
				}
				else if (str == "searchResponse")
				{
					dsmlErrorResponse = new SearchResponse(node);
				}
				else if (str == "modifyResponse")
				{
					dsmlErrorResponse = new ModifyResponse(node);
				}
				else if (str == "addResponse")
				{
					dsmlErrorResponse = new AddResponse(node);
				}
				else if (str == "delResponse")
				{
					dsmlErrorResponse = new DeleteResponse(node);
				}
				else if (str == "modDNResponse")
				{
					dsmlErrorResponse = new ModifyDNResponse(node);
				}
				else if (str == "compareResponse")
				{
					dsmlErrorResponse = new CompareResponse(node);
				}
				else if (str == "extendedResponse")
				{
					dsmlErrorResponse = new ExtendedResponse(node);
				}
				else if (str == "authResponse")
				{
					dsmlErrorResponse = new DsmlAuthResponse(node);
				}
				else
				{
					throw new DsmlInvalidDocumentException(Res.GetString("UnknownResponseElement"));
				}
				return dsmlErrorResponse;
			}
			throw new DsmlInvalidDocumentException(Res.GetString("UnknownResponseElement"));
		}
        internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
        {
            LDAP_TIMEVAL timeout = new LDAP_TIMEVAL {
                tv_sec = (int) (requestTimeOut.Ticks / 0x989680L)
            };
            IntPtr zero = IntPtr.Zero;
            DirectoryResponse response = null;
            IntPtr oid = IntPtr.Zero;
            IntPtr data = IntPtr.Zero;
            IntPtr entryMessage = IntPtr.Zero;
            bool flag = true;
            if (resultType != ResultAll.LDAP_MSG_ALL)
            {
                timeout.tv_sec = 0;
                timeout.tv_usec = 0;
                if (resultType == ResultAll.LDAP_MSG_POLLINGALL)
                {
                    resultType = ResultAll.LDAP_MSG_ALL;
                }
                flag = false;
            }
            int error = Wldap32.ldap_result(this.ldapHandle, messageId, (int) resultType, timeout, ref zero);
            switch (error)
            {
                case -1:
                case 0:
                    break;

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

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

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

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

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

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

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

                                default:
                                    if (Utility.IsResultCode((ResultCode) errorCode))
                                    {
                                        throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(errorCode));
                                    }
                                    throw new DirectoryOperationException(response);
                            }
                        }
                        error = errorCode;
                        goto Label_03A7;
                    }
                    finally
                    {
                        if (oid != IntPtr.Zero)
                        {
                            Wldap32.ldap_memfree(oid);
                        }
                        if (data != IntPtr.Zero)
                        {
                            Wldap32.ldap_memfree(data);
                        }
                        if (zero != IntPtr.Zero)
                        {
                            Wldap32.ldap_msgfree(zero);
                        }
                    }
                    break;
                }
            }
            if (error == 0)
            {
                if (!exceptionOnTimeOut)
                {
                    return null;
                }
                error = 0x55;
            }
            else
            {
                error = Wldap32.LdapGetLastError();
            }
            if (flag)
            {
                Wldap32.ldap_abandon(this.ldapHandle, messageId);
            }
        Label_03A7:
            throw this.ConstructException(error, operation);
        }