Пример #1
0
        public IssuedTokensHeader(XmlReader xmlReader, MessageVersion version, SecurityStandardsManager standardsManager)
            : base()
        {
            if (xmlReader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlReader");
            }
            if (standardsManager == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
            }
            this.standardsManager = standardsManager;
            XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(xmlReader);

            MessageHeader.GetHeaderAttributes(reader, version, out this.actor, out this.mustUnderstand, out this.relay, out this.isRefParam);
            reader.ReadStartElement(this.Name, this.Namespace);
            Collection <RequestSecurityTokenResponse> coll = new Collection <RequestSecurityTokenResponse>();

            if (this.standardsManager.TrustDriver.IsAtRequestSecurityTokenResponseCollection(reader))
            {
                RequestSecurityTokenResponseCollection rstrColl = this.standardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(reader);
                foreach (RequestSecurityTokenResponse rstr in rstrColl.RstrCollection)
                {
                    coll.Add(rstr);
                }
            }
            else
            {
                RequestSecurityTokenResponse rstr = this.standardsManager.TrustDriver.CreateRequestSecurityTokenResponse(reader);
                coll.Add(rstr);
            }
            this.tokenIssuances = new ReadOnlyCollection <RequestSecurityTokenResponse>(coll);
            reader.ReadEndElement();
        }
Пример #2
0
        private GenericXmlSecurityToken ExtractToken(Message response, object requestState)
        {
            // get the claims corresponding to the server
            SecurityMessageProperty serverContextProperty = response.Properties.Security;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            if (serverContextProperty != null && serverContextProperty.ServiceSecurityContext != null)
            {
                authorizationPolicies = serverContextProperty.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }

            RequestSecurityTokenResponse rstr       = null;
            XmlDictionaryReader          bodyReader = response.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    rstr = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponse(bodyReader);
                }
                else if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
                {
                    RequestSecurityTokenResponseCollection rstrc = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);
                    foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
                    {
                        if (rstr != null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MoreThanOneRSTRInRSTRC));
                        }

                        rstr = rstrItem;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                response.ReadFromBodyContentsToEnd(bodyReader);
            }

            byte[] requestorEntropy;
            if (requestState != null)
            {
                requestorEntropy = (byte[])requestState;
            }
            else
            {
                requestorEntropy = null;
            }

            GenericXmlSecurityToken issuedToken = rstr.GetIssuedToken(null, null, KeyEntropyMode, requestorEntropy, _sctUri, authorizationPolicies, SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            return(issuedToken);
        }
        protected override BodyWriter GetNextOutgoingMessageBody(Message incomingMessage, AcceleratedTokenProviderState negotiationState)
        {
            ThrowIfFault(incomingMessage, TargetAddress);
            if (incomingMessage.Headers.Action != RequestSecurityTokenResponseAction.Value)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidActionForNegotiationMessage, incomingMessage.Headers.Action)), incomingMessage);
            }
            // get the claims corresponding to the server
            SecurityMessageProperty serverContextProperty = incomingMessage.Properties.Security;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            if (serverContextProperty != null && serverContextProperty.ServiceSecurityContext != null)
            {
                authorizationPolicies = serverContextProperty.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            RequestSecurityTokenResponse rstr       = null;
            XmlDictionaryReader          bodyReader = incomingMessage.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    rstr = RequestSecurityTokenResponse.CreateFrom(StandardsManager, bodyReader);
                }
                else if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
                {
                    RequestSecurityTokenResponseCollection rstrc = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);

                    foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
                    {
                        if (rstr != null)
                        {
                            // More than one RSTR is found. So throw an exception.
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MoreThanOneRSTRInRSTRC));
                        }
                        rstr = rstrItem;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                incomingMessage.ReadFromBodyContentsToEnd(bodyReader);
            }
            if (rstr.Context != negotiationState.Context)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.BadSecurityNegotiationContext), incomingMessage);
            }
            byte[] keyEntropy = negotiationState.GetRequestorEntropy();
            GenericXmlSecurityToken serviceToken = rstr.GetIssuedToken(null, null, _keyEntropyMode, keyEntropy, SecurityContextTokenUri, authorizationPolicies, SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            negotiationState.SetServiceToken(serviceToken);
            return(null);
        }
Пример #4
0
 protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
 {
     if (this.tokenIssuances.Count == 1)
     {
         this.standardsManager.TrustDriver.WriteRequestSecurityTokenResponse(this.tokenIssuances[0], writer);
     }
     else
     {
         RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(this.tokenIssuances, this.standardsManager);
         rstrCollection.WriteTo(writer);
     }
 }
Пример #5
0
            public override void WriteRequestSecurityTokenResponseCollection(RequestSecurityTokenResponseCollection rstrCollection, XmlWriter xmlWriter)
            {
                if (rstrCollection == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rstrCollection");
                }

                XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter);

                writer.WriteStartElement(DriverDictionary.Prefix.Value, DriverDictionary.RequestSecurityTokenResponseCollection, DriverDictionary.Namespace);
                foreach (RequestSecurityTokenResponse rstr in rstrCollection.RstrCollection)
                {
                    rstr.WriteTo(writer);
                }
                writer.WriteEndElement();
            }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                if (requestSecurityToken.RequestType != null && requestSecurityToken.RequestType != this.StandardsManager.TrustDriver.RequestTypeIssue)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidRstRequestType, requestSecurityToken.RequestType)), request);
                }
                if (requestSecurityToken.TokenType != null && requestSecurityToken.TokenType != this.SecurityContextTokenUri)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotIssueRstTokenType, requestSecurityToken.TokenType)), request);
                }

                EndpointAddress        appliesTo;
                DataContractSerializer appliesToSerializer;
                string appliesToName;
                string appliesToNamespace;
                requestSecurityToken.GetAppliesToQName(out appliesToName, out appliesToNamespace);
                if (appliesToName == AddressingStrings.EndpointReference && appliesToNamespace == request.Version.Addressing.Namespace)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddress10>(appliesToSerializer).ToEndpointAddress();
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(appliesToSerializer).ToEndpointAddress();
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                else
                {
                    appliesTo           = null;
                    appliesToSerializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    SecurityUtils.MatchRstWithEndpointFilter(request, this.EndpointFilterTable, this.ListenUri);
                }
                int           issuedKeySize;
                byte[]        issuerEntropy;
                byte[]        proofKey;
                SecurityToken proofToken;
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, this.SecurityAlgorithmSuite,
                                                     out issuedKeySize, out issuerEntropy, out proofKey, out proofToken);
                UniqueId contextId      = SecurityUtils.GenerateUniqueId();
                string   id             = SecurityUtils.GenerateId();
                DateTime effectiveTime  = DateTime.UtcNow;
                DateTime expirationTime = TimeoutHelper.Add(effectiveTime, this.ServiceTokenLifetime);
                // ensure that a SecurityContext is present in the message
                SecurityMessageProperty securityProperty = request.Properties.Security;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;
                if (securityProperty != null)
                {
                    authorizationPolicies = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(securityProperty, expirationTime);
                }
                else
                {
                    authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken serviceToken = this.IssueSecurityContextToken(contextId, id, proofKey, effectiveTime, expirationTime, authorizationPolicies,
                                                                                           this.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    serviceToken.BootstrapMessageProperty = (securityProperty == null) ? null : (SecurityMessageProperty)securityProperty.CreateCopy();
                    SecurityUtils.ErasePasswordInUsernameTokenIfPresent(serviceToken.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
                rstr.Context = requestSecurityToken.Context;
                rstr.KeySize = issuedKeySize;
                rstr.RequestedUnattachedReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                rstr.RequestedAttachedReference   = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);
                rstr.TokenType = this.SecurityContextTokenUri;
                rstr.RequestedSecurityToken = serviceToken;
                if (issuerEntropy != null)
                {
                    rstr.SetIssuerEntropy(issuerEntropy);
                    rstr.ComputeKey = true;
                }
                if (proofToken != null)
                {
                    rstr.RequestedProofToken = proofToken;
                }
                if (appliesTo != null)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                rstr.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(serviceToken);

                if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(rstr);
                }
                else if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversation13)
                {
                    List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(1);
                    rstrList.Add(rstr);
                    RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
                    return(rstrCollection);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
        }
Пример #7
0
 // RSTR Collection method
 public abstract void WriteRequestSecurityTokenResponseCollection(RequestSecurityTokenResponseCollection rstrCollection, XmlWriter writer);
 protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
 {
     if (this.tokenIssuances.Count == 1)
     {
         this.standardsManager.TrustDriver.WriteRequestSecurityTokenResponse(this.tokenIssuances[0], writer);
     }
     else
     {
         RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(this.tokenIssuances, this.standardsManager);
         rstrCollection.WriteTo(writer);
     }
 }
        BodyWriter ProcessNegotiation(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
        {
            ISspiNegotiation sspiNegotiation = negotiationState.SspiNegotiation;

            byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(),
                                                                  SecurityUtils.GetChannelBindingFromMessage(incomingMessage),
                                                                  this.extendedProtectionPolicy);

            if (sspiNegotiation.IsValidContext == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidSspiNegotiation)), incomingMessage);
            }
            // if there is no blob to send back the nego must be complete from the server side
            if (outgoingBlob == null && sspiNegotiation.IsCompleted == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.NoBinaryNegoToSend)), incomingMessage);
            }
            BinaryNegotiation outgoingBinaryNegotiation;

            if (outgoingBlob != null)
            {
                outgoingBinaryNegotiation = GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
            }
            else
            {
                outgoingBinaryNegotiation = null;
            }
            BodyWriter replyBody;

            if (sspiNegotiation.IsCompleted)
            {
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = ValidateSspiNegotiation(sspiNegotiation);
                SecurityContextSecurityToken serviceToken;
                WrappedKeySecurityToken      proofToken;
                int issuedKeySize;
                IssueServiceToken(negotiationState, authorizationPolicies, out serviceToken, out proofToken, out issuedKeySize);
                negotiationState.SetServiceToken(serviceToken);

                SecurityKeyIdentifierClause externalTokenReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                SecurityKeyIdentifierClause internalTokenReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);

                RequestSecurityTokenResponse dummyRstr = new RequestSecurityTokenResponse(this.StandardsManager);
                dummyRstr.Context   = negotiationState.Context;
                dummyRstr.KeySize   = issuedKeySize;
                dummyRstr.TokenType = this.SecurityContextTokenUri;
                if (outgoingBinaryNegotiation != null)
                {
                    dummyRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                dummyRstr.RequestedUnattachedReference = externalTokenReference;
                dummyRstr.RequestedAttachedReference   = internalTokenReference;
                dummyRstr.SetLifetime(serviceToken.ValidFrom, serviceToken.ValidTo);
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(
                                                                       negotiationState.AppliesTo),
                                                                   negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(
                                                                               negotiationState.AppliesTo),
                                                                           negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                dummyRstr.MakeReadOnly();
                AddToDigest(negotiationState, dummyRstr, false);
                RequestSecurityTokenResponse negotiationRstr = new RequestSecurityTokenResponse(this.StandardsManager);
                negotiationRstr.RequestedSecurityToken = serviceToken;

                negotiationRstr.RequestedProofToken = proofToken;
                negotiationRstr.Context             = negotiationState.Context;
                negotiationRstr.KeySize             = issuedKeySize;
                negotiationRstr.TokenType           = this.SecurityContextTokenUri;
                if (outgoingBinaryNegotiation != null)
                {
                    negotiationRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                negotiationRstr.RequestedAttachedReference   = internalTokenReference;
                negotiationRstr.RequestedUnattachedReference = externalTokenReference;
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                negotiationRstr.MakeReadOnly();

                byte[] authenticator = ComputeAuthenticator(negotiationState, serviceToken.GetKeyBytes());
                RequestSecurityTokenResponse authenticatorRstr = new RequestSecurityTokenResponse(this.StandardsManager);
                authenticatorRstr.Context = negotiationState.Context;
                authenticatorRstr.SetAuthenticator(authenticator);
                authenticatorRstr.MakeReadOnly();

                List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(2);
                rstrList.Add(negotiationRstr);
                rstrList.Add(authenticatorRstr);
                replyBody = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
            }
            else
            {
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
                rstr.Context = negotiationState.Context;
                rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                rstr.MakeReadOnly();
                AddToDigest(negotiationState, rstr, false);
                replyBody = rstr;
            }

            return(replyBody);
        }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            BodyWriter writer;

            if (request == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                EndpointAddress        address;
                DataContractSerializer serializer;
                string        str;
                string        str2;
                int           num;
                byte[]        buffer;
                byte[]        buffer2;
                SecurityToken token;
                ReadOnlyCollection <IAuthorizationPolicy> instance;
                if ((requestSecurityToken.RequestType != null) && (requestSecurityToken.RequestType != base.StandardsManager.TrustDriver.RequestTypeIssue))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidRstRequestType", new object[] { requestSecurityToken.RequestType })), request);
                }
                if ((requestSecurityToken.TokenType != null) && (requestSecurityToken.TokenType != base.SecurityContextTokenUri))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("CannotIssueRstTokenType", new object[] { requestSecurityToken.TokenType })), request);
                }
                requestSecurityToken.GetAppliesToQName(out str, out str2);
                if ((str == "EndpointReference") && (str2 == request.Version.Addressing.Namespace))
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(serializer).ToEndpointAddress();
                    }
                    else
                    {
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddress10>(serializer).ToEndpointAddress();
                    }
                }
                else
                {
                    address    = null;
                    serializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    System.ServiceModel.Security.SecurityUtils.MatchRstWithEndpointFilter(request, base.EndpointFilterTable, base.ListenUri);
                }
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, base.SecurityAlgorithmSuite, out num, out buffer, out buffer2, out token);
                UniqueId contextId               = System.ServiceModel.Security.SecurityUtils.GenerateUniqueId();
                string   id                      = System.ServiceModel.Security.SecurityUtils.GenerateId();
                DateTime utcNow                  = DateTime.UtcNow;
                DateTime expirationTime          = TimeoutHelper.Add(utcNow, base.ServiceTokenLifetime);
                SecurityMessageProperty security = request.Properties.Security;
                if (security != null)
                {
                    instance = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(security, expirationTime);
                }
                else
                {
                    instance = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken token2 = base.IssueSecurityContextToken(contextId, id, buffer2, utcNow, expirationTime, instance, base.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    token2.BootstrapMessageProperty = (security == null) ? null : ((SecurityMessageProperty)security.CreateCopy());
                    System.ServiceModel.Security.SecurityUtils.ErasePasswordInUsernameTokenIfPresent(token2.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context = requestSecurityToken.Context,
                    KeySize = num,
                    RequestedUnattachedReference = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.External),
                    RequestedAttachedReference   = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.Internal),
                    TokenType = base.SecurityContextTokenUri,
                    RequestedSecurityToken = token2
                };
                if (buffer != null)
                {
                    response.SetIssuerEntropy(buffer);
                    response.ComputeKey = true;
                }
                if (token != null)
                {
                    response.RequestedProofToken = token;
                }
                if (address != null)
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        response.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(address), serializer);
                    }
                    else
                    {
                        response.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(address), serializer);
                    }
                }
                response.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(token2);
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(response);
                }
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion != SecureConversationVersion.WSSecureConversation13)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
                RequestSecurityTokenResponseCollection responses = new RequestSecurityTokenResponseCollection(new List <RequestSecurityTokenResponse>(1)
                {
                    response
                }, base.StandardsManager);
                writer = responses;
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
            return(writer);
        }
        protected override BodyWriter GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState)
        {
            try
            {
                ThrowIfFault(incomingMessage, this.TargetAddress);
            }
            catch (FaultException fault)
            {
                if (fault.Code.IsSenderFault)
                {
                    if (fault.Code.SubCode.Name == TrustApr2004Strings.FailedAuthenticationFaultCode || fault.Code.SubCode.Name == TrustFeb2005Strings.FailedAuthenticationFaultCode)
                    {
                        throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.AuthenticationOfClientFailed), fault), incomingMessage);
                    }

                    throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.FailedSspiNegotiation), fault), incomingMessage);
                }
                else
                {
                    throw;
                }
            }
            RequestSecurityTokenResponse negotiationRstr   = null;
            RequestSecurityTokenResponse authenticatorRstr = null;
            XmlDictionaryReader          bodyReader        = incomingMessage.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (this.StandardsManager.TrustDriver.IsAtRequestSecurityTokenResponseCollection(bodyReader))
                {
                    RequestSecurityTokenResponseCollection rstrCollection = this.StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);
                    using (IEnumerator <RequestSecurityTokenResponse> enumerator = rstrCollection.RstrCollection.GetEnumerator())
                    {
                        enumerator.MoveNext();
                        negotiationRstr = enumerator.Current;
                        if (enumerator.MoveNext())
                        {
                            authenticatorRstr = enumerator.Current;
                        }
                    }
                    if (authenticatorRstr == null)
                    {
                        throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.AuthenticatorNotPresentInRSTRCollection)), incomingMessage);
                    }
                    else if (authenticatorRstr.Context != negotiationRstr.Context)
                    {
                        throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.RSTRAuthenticatorHasBadContext)), incomingMessage);
                    }
                    AddToDigest(sspiState, negotiationRstr, true, true);
                }
                else if (this.StandardsManager.TrustDriver.IsAtRequestSecurityTokenResponse(bodyReader))
                {
                    negotiationRstr = RequestSecurityTokenResponse.CreateFrom(this.StandardsManager, bodyReader);
                    AddToDigest(sspiState, negotiationRstr, true, false);
                }
                else
                {
                    this.StandardsManager.TrustDriver.OnRSTRorRSTRCMissingException();
                }
                incomingMessage.ReadFromBodyContentsToEnd(bodyReader);
            }
            if (negotiationRstr.Context != sspiState.Context)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.BadSecurityNegotiationContext)), incomingMessage);
            }
            BinaryNegotiation incomingBinaryNego = negotiationRstr.GetBinaryNegotiation();

            byte[] incomingBlob;
            if (incomingBinaryNego != null)
            {
                ValidateIncomingBinaryNegotiation(incomingBinaryNego);
                incomingBlob = incomingBinaryNego.GetNegotiationData();
            }
            else
            {
                incomingBlob = null;
            }
            BodyWriter nextMessageBody;

            if (incomingBlob == null && sspiState.SspiNegotiation.IsCompleted == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.NoBinaryNegoToReceive)), incomingMessage);
            }
            else if (incomingBlob == null && sspiState.SspiNegotiation.IsCompleted == true)
            {
                // the incoming RSTR must have the negotiated token
                OnNegotiationComplete(sspiState, negotiationRstr, authenticatorRstr);
                nextMessageBody = null;
            }
            else
            {
                // we got an incoming blob. Process it and see if there is an outgoing blob
                byte[] outgoingBlob = sspiState.SspiNegotiation.GetOutgoingBlob(incomingBlob,
                                                                                SecurityUtils.GetChannelBindingFromMessage(incomingMessage),
                                                                                null);

                if (outgoingBlob == null && sspiState.SspiNegotiation.IsCompleted == false)
                {
                    throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.NoBinaryNegoToSend)), incomingMessage);
                }
                else if (outgoingBlob == null && sspiState.SspiNegotiation.IsCompleted == true)
                {
                    // the incoming RSTR had the last blob. It must have the token too
                    this.OnNegotiationComplete(sspiState, negotiationRstr, authenticatorRstr);
                    nextMessageBody = null;
                }
                else
                {
                    nextMessageBody = PrepareRstr(sspiState, outgoingBlob);
                }
            }
            return(nextMessageBody);
        }