internal static Message End(IAsyncResult result, out SecurityProtocolCorrelationState newCorrelationState)
            {
                SecureOutgoingMessageAsyncResult self = AsyncResult.End <SecureOutgoingMessageAsyncResult>(result);

                newCorrelationState = self.newCorrelationState;
                return(self.message);
            }
Ejemplo n.º 2
0
        // try to get the token if it can be obtained within the
        // synchronous requirements of the call; return true iff a
        // token not required OR a token is required AND has been
        // obtained within the specified synchronous requirements.
        bool TryGetTokenSynchronouslyForOutgoingSecurity(Message message, SecurityProtocolCorrelationState correlationState, bool isBlockingCall, TimeSpan timeout, out SecurityToken token, out SecurityTokenParameters tokenParameters, out SecurityToken prerequisiteWrappingToken, out IList <SupportingTokenSpecification> supportingTokens, out SecurityProtocolCorrelationState newCorrelationState)
        {
            SymmetricSecurityProtocolFactory factory = this.Factory;

            supportingTokens          = null;
            prerequisiteWrappingToken = null;
            token               = null;
            tokenParameters     = null;
            newCorrelationState = null;
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (factory.ApplyIntegrity || factory.ApplyConfidentiality)
            {
                if (factory.ActAsInitiator)
                {
                    if (!isBlockingCall || !TryGetSupportingTokens(factory, this.Target, this.Via, message, timeoutHelper.RemainingTime(), isBlockingCall, out supportingTokens))
                    {
                        return(false);
                    }
                    SecurityTokenProvider provider      = GetTokenProvider();
                    SecurityToken         providerToken = GetTokenAndEnsureOutgoingIdentity(provider, factory.ApplyConfidentiality, timeoutHelper.RemainingTime(), this.initiatorTokenAuthenticator);
                    token = GetInitiatorToken(providerToken, message, timeoutHelper.RemainingTime(), out tokenParameters, out prerequisiteWrappingToken);
                    newCorrelationState = GetCorrelationState(token);
                }
                else
                {
                    token           = GetCorrelationToken(correlationState);
                    tokenParameters = this.Factory.GetProtectionTokenParameters();
                }
            }
            return(true);
        }
Ejemplo n.º 3
0
        void SetUpDelayedSecurityExecution(ref Message message,
                                           SecurityToken prerequisiteToken,
                                           SecurityToken primaryToken,
                                           SecurityTokenParameters primaryTokenParameters,
                                           IList <SupportingTokenSpecification> supportingTokens,
                                           SecurityProtocolCorrelationState correlationState
                                           )
        {
            string             actor          = string.Empty;
            SendSecurityHeader securityHeader = ConfigureSendSecurityHeader(message, actor, supportingTokens, correlationState);

            if (prerequisiteToken != null)
            {
                securityHeader.AddPrerequisiteToken(prerequisiteToken);
            }
            if (this.Factory.ApplyIntegrity || securityHeader.HasSignedTokens)
            {
                if (!this.Factory.ApplyIntegrity)
                {
                    securityHeader.SignatureParts = MessagePartSpecification.NoParts;
                }
                securityHeader.SetSigningToken(primaryToken, primaryTokenParameters);
            }
            if (Factory.ApplyConfidentiality || securityHeader.HasEncryptedTokens)
            {
                if (!this.Factory.ApplyConfidentiality)
                {
                    securityHeader.EncryptionParts = MessagePartSpecification.NoParts;
                }
                securityHeader.SetEncryptionToken(primaryToken, primaryTokenParameters);
            }
            message = securityHeader.SetupExecution();
        }
        public override SecurityProtocolCorrelationState SecureOutgoingMessage(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
        {
            SecurityProtocolCorrelationState state2;

            try
            {
                base.CommunicationObject.ThrowIfClosedOrNotOpen();
                this.ValidateOutgoingState(message);
                if (!this.RequiresOutgoingSecurityProcessing && (message.Properties.Security == null))
                {
                    return(null);
                }
                SecurityProtocolCorrelationState state = this.SecureOutgoingMessageCore(ref message, timeout, correlationState);
                base.OnOutgoingMessageSecured(message);
                state2 = state;
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                base.OnSecureOutgoingMessageFailure(message);
                throw;
            }
            return(state2);
        }
 public SecureOutgoingMessageAsyncResult(Message m, AsymmetricSecurityProtocol binding,
                                         SecurityTokenProvider primaryProvider, SecurityTokenProvider secondaryProvider, bool doIdentityChecks, SecurityTokenAuthenticator identityCheckAuthenticator,
                                         SecurityProtocolCorrelationState correlationState, TimeSpan timeout, AsyncCallback callback, object state)
     : base(m, binding, primaryProvider, secondaryProvider, doIdentityChecks, identityCheckAuthenticator, correlationState, timeout, callback, state)
 {
     Start();
 }
 public override void EndSecureOutgoingMessage(IAsyncResult result, out Message message, out SecurityProtocolCorrelationState newCorrelationState)
 {
     if (result == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
     }
     newCorrelationState = null;
     try
     {
         if (result is CompletedAsyncResult<Message>)
         {
             message = CompletedAsyncResult<Message>.End(result);
         }
         else
         {
             message = this.EndSecureOutgoingMessageAtInitiatorCore(result);
         }
         base.OnOutgoingMessageSecured(message);
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         base.OnSecureOutgoingMessageFailure(null);
         throw;
     }
 }
 public override IAsyncResult BeginSecureOutgoingMessage(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     IAsyncResult result;
     if (message == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     base.CommunicationObject.ThrowIfClosedOrNotOpen();
     string actor = string.Empty;
     try
     {
         if (base.SecurityProtocolFactory.ActAsInitiator)
         {
             return this.BeginSecureOutgoingMessageAtInitiatorCore(message, actor, timeout, callback, state);
         }
         this.SecureOutgoingMessageAtResponder(ref message, actor);
         result = new CompletedAsyncResult<Message>(message, callback, state);
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         base.OnSecureOutgoingMessageFailure(message);
         throw;
     }
     return result;
 }
        public override IAsyncResult BeginSecureOutgoingMessage(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            this.CommunicationObject.ThrowIfClosedOrNotOpen();
            string actor = string.Empty; // message.Version.Envelope.UltimateDestinationActor;
            try
            {
                if (this.SecurityProtocolFactory.ActAsInitiator)
                {
                    return this.BeginSecureOutgoingMessageAtInitiatorCore(message, actor, timeout, callback, state);
                }
                else
                {
                    SecureOutgoingMessageAtResponder(ref message, actor);
                    return new CompletedAsyncResult<Message>(message, callback, state);
                }
            }
            catch (Exception exception)
            {
                // Always immediately rethrow fatal exceptions.
                if (Fx.IsFatal(exception)) throw;

                base.OnSecureOutgoingMessageFailure(message);
                throw;
            }
        }
 protected SecurityToken GetCorrelationToken(SecurityProtocolCorrelationState correlationState)
 {
     if ((correlationState == null) || (correlationState.Token == null))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("CannotFindCorrelationStateForApplyingSecurity")));
     }
     return(correlationState.Token);
 }
 protected override SecurityProtocolCorrelationState SecureOutgoingMessageCore(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityTokenParameters parameters;
     this.GetTokensForOutgoingMessages(out token, out token2, out parameters);
     this.SetUpDelayedSecurityExecution(ref message, token, token2, parameters, correlationState);
     return null;
 }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityTokenParameters parameters;
     this.GetTokensForOutgoingMessages(out token, out token2, out parameters);
     this.SetUpDelayedSecurityExecution(ref message, token, token2, parameters, correlationState);
     return new CompletedAsyncResult<Message>(message, callback, state);
 }
 protected override void EndSecureOutgoingMessageCore(IAsyncResult result, out Message message, out SecurityProtocolCorrelationState newCorrelationState)
 {
     if (result is CompletedAsyncResult<Message, SecurityProtocolCorrelationState>)
     {
         message = CompletedAsyncResult<Message, SecurityProtocolCorrelationState>.End(result, out newCorrelationState);
     }
     else
     {
         message = MessageSecurityProtocol.GetOneTokenAndSetUpSecurityAsyncResult.End(result, out newCorrelationState);
     }
 }
        protected void Begin(Message message, SecurityProtocolCorrelationState correlationState)
        {
            IAsyncResult result = this.binding.BeginSecureOutgoingMessage(message, this.timeoutHelper.RemainingTime(), correlationState, ApplySecurityAndSendAsyncResult <MessageSenderType> .sharedCallback, this);

            if (result.CompletedSynchronously)
            {
                this.binding.EndSecureOutgoingMessage(result, out message, out this.newCorrelationState);
                if (this.OnSecureOutgoingMessageComplete(message))
                {
                    base.Complete(true);
                }
            }
        }
Ejemplo n.º 14
0
        protected override SecurityProtocolCorrelationState SecureOutgoingMessageCore(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
        {
            SecurityToken           token;
            SecurityToken           token2;
            SecurityToken           token3;
            SecurityTokenParameters parameters;
            IList <SupportingTokenSpecification> list;

            this.GetTokensForOutgoingMessages(out token, out token2, out token3, out parameters);
            SecurityProtocolCorrelationState state = this.CreateCorrelationStateIfRequired();

            base.TryGetSupportingTokens(base.SecurityProtocolFactory, base.Target, base.Via, message, timeout, true, out list);
            this.SetUpDelayedSecurityExecution(ref message, token, token2, token3, parameters, list, state);
            return(state);
        }
        protected override SecurityProtocolCorrelationState SecureOutgoingMessageCore(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
        {
            SecurityToken           signingToken;
            SecurityToken           encryptionToken;
            SecurityToken           sourceToken;
            SecurityTokenParameters tokenParameters;

            this.GetTokensForOutgoingMessages(out signingToken, out encryptionToken, out sourceToken, out tokenParameters);
            SecurityProtocolCorrelationState     newCorrelationState = CreateCorrelationStateIfRequired();
            IList <SupportingTokenSpecification> supportingTokens;

            this.TryGetSupportingTokens(this.SecurityProtocolFactory, this.Target, this.Via, message, timeout, true, out supportingTokens);
            SetUpDelayedSecurityExecution(ref message, signingToken, encryptionToken, sourceToken, tokenParameters, supportingTokens, newCorrelationState);
            return(newCorrelationState);
        }
        void SetUpDelayedSecurityExecution(ref Message message, SecurityToken signingToken, SecurityToken encryptionToken,
                                           SecurityTokenParameters tokenParameters, SecurityProtocolCorrelationState correlationState)
        {
            string             actor          = string.Empty;
            SendSecurityHeader securityHeader = ConfigureSendSecurityHeader(message, actor, null, correlationState);

            if (this.Factory.ApplyIntegrity)
            {
                securityHeader.SetSigningToken(signingToken, tokenParameters);
            }
            if (Factory.ApplyConfidentiality)
            {
                securityHeader.SetEncryptionToken(encryptionToken, tokenParameters);
            }
            message = securityHeader.SetupExecution();
        }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityToken token3;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     this.GetTokensForOutgoingMessages(out token, out token2, out token3, out parameters);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (base.TryGetSupportingTokens(this.Factory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         SecurityProtocolCorrelationState state2 = this.CreateCorrelationStateIfRequired();
         this.SetUpDelayedSecurityExecution(ref message, token, token2, token3, parameters, list, state2);
         return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, state2, callback, state);
     }
     return new SecureOutgoingMessageAsyncResult(message, this, token, token2, token3, parameters, helper.RemainingTime(), callback, state);
 }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     SecurityToken token2;
     SecurityProtocolCorrelationState state2;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.TryGetTokenSynchronouslyForOutgoingSecurity(message, correlationState, false, helper.RemainingTime(), out token, out parameters, out token2, out list, out state2))
     {
         this.SetUpDelayedSecurityExecution(ref message, token2, token, parameters, list, base.GetSignatureConfirmationCorrelationState(correlationState, state2));
         return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, state2, callback, state);
     }
     if (!this.Factory.ActAsInitiator)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ProtocolMustBeInitiator", new object[] { base.GetType().ToString() })));
     }
     return new SecureOutgoingMessageAsyncResult(message, this, this.GetTokenProvider(), this.Factory.ApplyConfidentiality, this.initiatorTokenAuthenticator, correlationState, helper.RemainingTime(), callback, state);
 }
Ejemplo n.º 19
0
        protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
        {
            SecurityToken           token;
            SecurityToken           token2;
            SecurityToken           token3;
            SecurityTokenParameters parameters;
            IList <SupportingTokenSpecification> list;

            this.GetTokensForOutgoingMessages(out token, out token2, out token3, out parameters);
            TimeoutHelper helper = new TimeoutHelper(timeout);

            if (base.TryGetSupportingTokens(this.Factory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
            {
                SecurityProtocolCorrelationState state2 = this.CreateCorrelationStateIfRequired();
                this.SetUpDelayedSecurityExecution(ref message, token, token2, token3, parameters, list, state2);
                return(new CompletedAsyncResult <Message, SecurityProtocolCorrelationState>(message, state2, callback, state));
            }
            return(new SecureOutgoingMessageAsyncResult(message, this, token, token2, token3, parameters, helper.RemainingTime(), callback, state));
        }
Ejemplo n.º 20
0
        bool TryGetTokenSynchronouslyForOutgoingSecurity(Message message, SecurityProtocolCorrelationState correlationState, bool isBlockingCall, TimeSpan timeout,
                                                         out SecurityToken encryptingToken, out SecurityToken signingToken, out IList <SupportingTokenSpecification> supportingTokens, out SecurityProtocolCorrelationState newCorrelationState)
        {
            AsymmetricSecurityProtocolFactory factory = this.Factory;

            encryptingToken     = null;
            signingToken        = null;
            newCorrelationState = null;
            supportingTokens    = null;
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (factory.ActAsInitiator)
            {
                if (!isBlockingCall || !TryGetSupportingTokens(this.Factory, this.Target, this.Via, message, timeoutHelper.RemainingTime(), isBlockingCall, out supportingTokens))
                {
                    return(false);
                }
                if (factory.ApplyConfidentiality)
                {
                    encryptingToken = GetTokenAndEnsureOutgoingIdentity(this.initiatorAsymmetricTokenProvider, true, timeoutHelper.RemainingTime(), this.initiatorAsymmetricTokenAuthenticator);
                }
                if (factory.ApplyIntegrity)
                {
                    signingToken        = GetToken(this.initiatorCryptoTokenProvider, this.Target, timeoutHelper.RemainingTime());
                    newCorrelationState = GetCorrelationState(signingToken);
                }
            }
            else
            {
                if (factory.ApplyConfidentiality)
                {
                    encryptingToken = GetCorrelationToken(correlationState);
                }
                if (factory.ApplyIntegrity)
                {
                    signingToken = GetToken(factory.RecipientAsymmetricTokenProvider, null, timeoutHelper.RemainingTime());
                }
            }
            return(true);
        }
        public override SecurityProtocolCorrelationState VerifyIncomingMessage(ref Message message, TimeSpan timeout, params SecurityProtocolCorrelationState[] correlationStates)
        {
            SecurityProtocolCorrelationState state2;

            try
            {
                base.CommunicationObject.ThrowIfClosedOrNotOpen();
                if (this.PerformIncomingAndOutgoingMessageExpectationChecks && !this.factory.ExpectIncomingMessages)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SecurityBindingNotSetUpToProcessIncomingMessages")));
                }
                if (message == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
                }
                if (!this.RequiresIncomingSecurityProcessing(message))
                {
                    return(null);
                }
                string actor = string.Empty;
                SecurityProtocolCorrelationState state = this.VerifyIncomingMessageCore(ref message, actor, timeout, correlationStates);
                base.OnIncomingMessageVerified(message);
                state2 = state;
            }
            catch (MessageSecurityException exception)
            {
                base.OnVerifyIncomingMessageFailure(message, exception);
                throw;
            }
            catch (Exception exception2)
            {
                if (Fx.IsFatal(exception2))
                {
                    throw;
                }
                base.OnVerifyIncomingMessageFailure(message, exception2);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("MessageSecurityVerificationFailed"), exception2));
            }
            return(state2);
        }
        protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
        {
            SecurityToken           signingToken;
            SecurityToken           encryptionToken;
            SecurityToken           sourceToken;
            SecurityTokenParameters tokenParameters;

            this.GetTokensForOutgoingMessages(out signingToken, out encryptionToken, out sourceToken, out tokenParameters);
            IList <SupportingTokenSpecification> supportingTokens;
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (TryGetSupportingTokens(this.Factory, this.Target, this.Via, message, timeoutHelper.RemainingTime(), false, out supportingTokens))
            {
                SecurityProtocolCorrelationState newCorrelationState = CreateCorrelationStateIfRequired();
                SetUpDelayedSecurityExecution(ref message, signingToken, encryptionToken, sourceToken, tokenParameters, supportingTokens, newCorrelationState);
                return(new CompletedAsyncResult <Message, SecurityProtocolCorrelationState>(message, newCorrelationState, callback, state));
            }
            else
            {
                return(new SecureOutgoingMessageAsyncResult(message, this, signingToken, encryptionToken, sourceToken, tokenParameters, timeoutHelper.RemainingTime(), callback, state));
            }
        }
 public override IAsyncResult BeginSecureOutgoingMessage(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     IAsyncResult result;
     try
     {
         base.CommunicationObject.ThrowIfClosedOrNotOpen();
         this.ValidateOutgoingState(message);
         if (!this.RequiresOutgoingSecurityProcessing && (message.Properties.Security == null))
         {
             return new CompletedAsyncResult<Message>(message, callback, state);
         }
         result = this.BeginSecureOutgoingMessageCore(message, timeout, correlationState, callback, state);
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         base.OnSecureOutgoingMessageFailure(message);
         throw;
     }
     return result;
 }
        protected void ProcessSecurityHeader(ReceiveSecurityHeader securityHeader, ref Message message,
            SecurityToken requiredSigningToken, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            securityHeader.ReplayDetectionEnabled = this.factory.DetectReplays;
            securityHeader.SetTimeParameters(this.factory.NonceCache, this.factory.ReplayWindow, this.factory.MaxClockSkew);

            securityHeader.Process(timeoutHelper.RemainingTime(), SecurityUtils.GetChannelBindingFromMessage(message), this.factory.ExtendedProtectionPolicy);
            if (this.factory.AddTimestamp && securityHeader.Timestamp == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.RequiredTimestampMissingInSecurityHeader)));
            }

            if (requiredSigningToken != null && requiredSigningToken != securityHeader.SignatureToken)
            {
                throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ReplyWasNotSignedWithRequiredSigningToken)), message);
            }

            if (this.DoAutomaticEncryptionMatch)
            {
                SecurityUtils.EnsureExpectedSymmetricMatch(securityHeader.SignatureToken, securityHeader.EncryptionToken, message);
            }

            if (securityHeader.MaintainSignatureConfirmationState && this.factory.ActAsInitiator)
            {
                CheckSignatureConfirmation(securityHeader, correlationStates);
            }

            message = securityHeader.ProcessedMessage;
        }
        protected ReceiveSecurityHeader ConfigureReceiveSecurityHeader(Message message, string actor, SecurityProtocolCorrelationState[] correlationStates, SecurityStandardsManager standardsManager, out IList<SupportingTokenAuthenticatorSpecification> supportingAuthenticators)
        {
            MessageSecurityProtocolFactory factory = this.MessageSecurityProtocolFactory;
            MessageDirection direction = factory.ActAsInitiator ? MessageDirection.Output : MessageDirection.Input;
            ReceiveSecurityHeader securityHeader = CreateSecurityHeader(message, actor, direction, standardsManager);

            string action = message.Headers.Action;
            supportingAuthenticators = GetSupportingTokenAuthenticatorsAndSetExpectationFlags(this.factory, message, securityHeader);
            if (factory.RequireIntegrity || securityHeader.ExpectSignedTokens)
            {
                securityHeader.RequiredSignatureParts = factory.GetIncomingSignatureParts(action);
            }
            if (factory.RequireConfidentiality || securityHeader.ExpectBasicTokens)
            {
                securityHeader.RequiredEncryptionParts = factory.GetIncomingEncryptionParts(action);
            }

            securityHeader.ExpectEncryption = factory.RequireConfidentiality || securityHeader.ExpectBasicTokens;
            securityHeader.ExpectSignature = factory.RequireIntegrity || securityHeader.ExpectSignedTokens;
            securityHeader.SetRequiredProtectionOrder(factory.MessageProtectionOrder);

            // On the receiving side if protectTokens is enabled
            // 1. If we are service, we make sure that the client always signs the primary token( can be any token type)else we throw.
            //    But currently the service can sign the primary token in reply only if the primary token is an issued token 
            // 2. If we are client, we do not care if the service signs the primary token or not. Otherwise it will be impossible to have a wcf client /service talk to each other unless we 
            // either use a symmetric binding with issued tokens or asymmetric bindings with both the intiator and recipient parameters being issued tokens( later one is rare).
            securityHeader.RequireSignedPrimaryToken = !factory.ActAsInitiator && factory.SecurityBindingElement.ProtectTokens;

            if (factory.ActAsInitiator && factory.DoRequestSignatureConfirmation && HasCorrelationState(correlationStates))
            {
                securityHeader.MaintainSignatureConfirmationState = true;
                securityHeader.ExpectSignatureConfirmation = true;
            }
            else if (!factory.ActAsInitiator && factory.DoRequestSignatureConfirmation)
            {
                securityHeader.MaintainSignatureConfirmationState = true;
            }
            else
            {
                securityHeader.MaintainSignatureConfirmationState = false;
            }
            return securityHeader;
        }
 protected ReceiveSecurityHeader ConfigureReceiveSecurityHeader(Message message, string actor, SecurityProtocolCorrelationState[] correlationStates, out IList<SupportingTokenAuthenticatorSpecification> supportingAuthenticators)
 {
     return ConfigureReceiveSecurityHeader(message, actor, correlationStates, null, out supportingAuthenticators);
 }
 internal static Message End(IAsyncResult result, out SecurityProtocolCorrelationState newCorrelationState)
 {
     GetTwoTokensAndSetUpSecurityAsyncResult self = AsyncResult.End<GetTwoTokensAndSetUpSecurityAsyncResult>(result);
     newCorrelationState = self.newCorrelationState;
     return self.message;
 }
 internal SecurityProtocolCorrelationState GetSignatureConfirmationCorrelationState(SecurityProtocolCorrelationState oldCorrelationState, SecurityProtocolCorrelationState newCorrelationState)
 {
     if (this.factory.ActAsInitiator)
     {
         return newCorrelationState;
     }
     else
     {
         return oldCorrelationState;
     }
 }
 protected abstract SecurityProtocolCorrelationState SecureOutgoingMessageCore(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState);
 protected SecurityProtocolCorrelationState GetCorrelationState(SecurityToken correlationToken, ReceiveSecurityHeader securityHeader)
 {
     SecurityProtocolCorrelationState result = new SecurityProtocolCorrelationState(correlationToken);
     if (securityHeader.MaintainSignatureConfirmationState && !this.factory.ActAsInitiator)
     {
         result.SignatureConfirmations = securityHeader.GetSentSignatureValues();
     }
     return result;
 }
 protected abstract void EndSecureOutgoingMessageCore(IAsyncResult result, out Message message, out SecurityProtocolCorrelationState newCorrelationState);
        public override void EndSecureOutgoingMessage(IAsyncResult result, out Message message, out SecurityProtocolCorrelationState newCorrelationState)
        {
            if (result == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
            }
            try
            {
                EndSecureOutgoingMessageCore(result, out message, out newCorrelationState);
                base.OnOutgoingMessageSecured(message);
            }
            catch (Exception exception)
            {
                // Always immediately rethrow fatal exceptions.
                if (Fx.IsFatal(exception)) throw;

                base.OnSecureOutgoingMessageFailure(null);
                throw;
            }
        }
 protected abstract IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state);
 protected override SecurityProtocolCorrelationState VerifyIncomingMessageCore(ref Message message, string actor, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
 {
     SessionSymmetricMessageSecurityProtocolFactory factory = this.Factory;
     IList<SupportingTokenAuthenticatorSpecification> supportingAuthenticators;
     ReceiveSecurityHeader securityHeader = ConfigureReceiveSecurityHeader(message, string.Empty, correlationStates, (this.requireDerivedKeys) ? this.sessionStandardsManager : null, out supportingAuthenticators);
     securityHeader.ConfigureSymmetricBindingServerReceiveHeader(this.sessionTokenAuthenticator, this.Factory.SecurityTokenParameters, supportingAuthenticators);
     securityHeader.ConfigureOutOfBandTokenResolver(MergeOutOfBandResolvers(supportingAuthenticators, this.sessionResolverList));
     // do not enforce key derivation requirement for Cancel messages due to WSE interop
     securityHeader.EnforceDerivedKeyRequirement = (message.Headers.Action != factory.StandardsManager.SecureConversationDriver.CloseAction.Value);
     ProcessSecurityHeader(securityHeader, ref message, null, timeout, correlationStates);
     SecurityToken signingToken = securityHeader.SignatureToken;
     SecurityContextSecurityToken signingSct = (signingToken as SecurityContextSecurityToken);
     if (signingSct == null || signingSct.ContextId != sessionId)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.GetString(SR.NoSessionTokenPresentInMessage)));
     }
     AttachRecipientSecurityProperty(message, signingToken, false, securityHeader.BasicSupportingTokens, securityHeader.EndorsingSupportingTokens, securityHeader.SignedEndorsingSupportingTokens,
         securityHeader.SignedSupportingTokens, securityHeader.SecurityTokenAuthorizationPoliciesMapping);
     return GetCorrelationState(null, securityHeader);
 }
 void SetUpDelayedSecurityExecution(ref Message message, SecurityToken signingToken, SecurityToken encryptionToken, 
     SecurityTokenParameters tokenParameters, SecurityProtocolCorrelationState correlationState)
 {
     string actor = string.Empty;
     SendSecurityHeader securityHeader = ConfigureSendSecurityHeader(message, actor, null, correlationState);
     if (this.Factory.ApplyIntegrity)
     {
         securityHeader.SetSigningToken(signingToken, tokenParameters);
     }
     if (Factory.ApplyConfidentiality)
     {
         securityHeader.SetEncryptionToken(encryptionToken, tokenParameters);
     }
     message = securityHeader.SetupExecution();
 }
 protected void CheckSignatureConfirmation(ReceiveSecurityHeader securityHeader, SecurityProtocolCorrelationState[] correlationStates)
 {
     SignatureConfirmations receivedConfirmations = securityHeader.GetSentSignatureConfirmations();
     SignatureConfirmations sentSignatures = null;
     if (correlationStates != null)
     {
         for (int i = 0; i < correlationStates.Length; ++i)
         {
             if (correlationStates[i].SignatureConfirmations != null)
             {
                 sentSignatures = correlationStates[i].SignatureConfirmations;
                 break;
             }
         }
     }
     if (sentSignatures == null)
     {
         if (receivedConfirmations != null && receivedConfirmations.Count > 0)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.FoundUnexpectedSignatureConfirmations)));
         }
         return;
     }
     bool allSignaturesConfirmed = false;
     if (receivedConfirmations != null && sentSignatures.Count == receivedConfirmations.Count)
     {
         bool[] matchingSigIndexes = new bool[sentSignatures.Count];
         for (int i = 0; i < sentSignatures.Count; ++i)
         {
             byte[] sentSignature;
             bool wasSentSigEncrypted;
             sentSignatures.GetConfirmation(i, out sentSignature, out wasSentSigEncrypted);
             for (int j = 0; j < receivedConfirmations.Count; ++j)
             {
                 byte[] receivedSignature;
                 bool wasReceivedSigEncrypted;
                 if (matchingSigIndexes[j])
                 {
                     continue;
                 }
                 receivedConfirmations.GetConfirmation(j, out receivedSignature, out wasReceivedSigEncrypted);
                 if ((wasReceivedSigEncrypted == wasSentSigEncrypted) && CryptoHelper.IsEqual(receivedSignature, sentSignature))
                 {
                     matchingSigIndexes[j] = true;
                     break;
                 }
             }
         }
         int k;
         for (k = 0; k < matchingSigIndexes.Length; ++k)
         {
             if (!matchingSigIndexes[k])
             {
                 break;
             }
         }
         if (k == matchingSigIndexes.Length)
         {
             allSignaturesConfirmed = true;
         }
     }
     if (!allSignaturesConfirmed)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NotAllSignaturesConfirmed)));
     }
 }
        public override SecurityProtocolCorrelationState SecureOutgoingMessage(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
        {
            try
            {
                this.CommunicationObject.ThrowIfClosedOrNotOpen();
                ValidateOutgoingState(message);
                if (!this.RequiresOutgoingSecurityProcessing && message.Properties.Security == null)
                {
                    return null;
                }
                SecurityProtocolCorrelationState newCorrelationState = SecureOutgoingMessageCore(ref message, timeout, correlationState);
                base.OnOutgoingMessageSecured(message);
                return newCorrelationState;
            }
            catch (Exception exception)
            {
                // Always immediately rethrow fatal exceptions.
                if (Fx.IsFatal(exception)) throw;

                base.OnSecureOutgoingMessageFailure(message);
                throw;
            }
        }
 protected SecurityToken GetCorrelationToken(SecurityProtocolCorrelationState[] correlationStates)
 {
     SecurityToken token = null;
     if (correlationStates != null)
     {
         for (int i = 0; i < correlationStates.Length; ++i)
         {
             if (correlationStates[i].Token == null)
                 continue;
             if (token == null)
             {
                 token = correlationStates[i].Token;
             }
             else if (!object.ReferenceEquals(token, correlationStates[i].Token))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MultipleCorrelationTokensFound)));
             }
         }
     }
     if (token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoCorrelationTokenFound)));
     }
     return token;
 }
 protected abstract SecurityProtocolCorrelationState VerifyIncomingMessageCore(ref Message message, string actor, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates);
 protected SecurityToken GetCorrelationToken(SecurityProtocolCorrelationState correlationState)
 {
     if (correlationState == null || correlationState.Token == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.CannotFindCorrelationStateForApplyingSecurity)));
     }
     return correlationState.Token;
 }
 public GetTwoTokensAndSetUpSecurityAsyncResult(Message m, MessageSecurityProtocol binding,
     SecurityTokenProvider primaryProvider, SecurityTokenProvider secondaryProvider, bool doIdentityChecks, SecurityTokenAuthenticator identityCheckAuthenticator,
     SecurityProtocolCorrelationState oldCorrelationState,
     TimeSpan timeout,
     AsyncCallback callback, object state)
     : base(m, binding, timeout, callback, state)
 {
     this.message = m;
     this.binding = binding;
     this.primaryProvider = primaryProvider;
     this.secondaryProvider = secondaryProvider;
     this.doIdentityChecks = doIdentityChecks;
     this.identityCheckAuthenticator = identityCheckAuthenticator;
     this.oldCorrelationState = oldCorrelationState;
 }
        protected SendSecurityHeader ConfigureSendSecurityHeader(Message message, string actor, IList<SupportingTokenSpecification> supportingTokens, SecurityProtocolCorrelationState correlationState)
        {
            MessageSecurityProtocolFactory factory = this.MessageSecurityProtocolFactory;
            SendSecurityHeader securityHeader = CreateSendSecurityHeader(message, actor, factory);
            securityHeader.SignThenEncrypt = factory.MessageProtectionOrder != MessageProtectionOrder.EncryptBeforeSign;
            // If ProtectTokens is enabled then we make sure that both the client side and the service side sign the primary token 
            // ( if it is an issued token, the check exists in sendsecurityheader)in the primary signature while sending a message.
            securityHeader.ShouldProtectTokens = factory.SecurityBindingElement.ProtectTokens;
            securityHeader.EncryptPrimarySignature = factory.MessageProtectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;

            if (factory.DoRequestSignatureConfirmation && correlationState != null)
            {
                if (factory.ActAsInitiator)
                {
                    securityHeader.MaintainSignatureConfirmationState = true;
                    securityHeader.CorrelationState = correlationState;
                }
                else if (correlationState.SignatureConfirmations != null)
                {
                    securityHeader.AddSignatureConfirmations(correlationState.SignatureConfirmations);
                }
            }

            string action = message.Headers.Action;
            if (this.factory.ApplyIntegrity)
            {
                securityHeader.SignatureParts = this.factory.GetOutgoingSignatureParts(action);
            }

            if (factory.ApplyConfidentiality)
            {
                securityHeader.EncryptionParts = this.factory.GetOutgoingEncryptionParts(action);
            }
            AddSupportingTokens(securityHeader, supportingTokens);
            return securityHeader;
        }
 protected void SetCorrelationToken(SecurityToken token)
 {
     newCorrelationState = new SecurityProtocolCorrelationState(token);
 }
 bool HasCorrelationState(SecurityProtocolCorrelationState[] correlationState)
 {
     if (correlationState == null || correlationState.Length == 0)
     {
         return false;
     }
     else if (correlationState.Length == 1 && correlationState[0] == null)
     {
         return false;
     }
     else
     {
         return true;
     }
 }