/// <summary>
		/// Verifies the signature by unrecognized handle.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="signedMessage">The signed message.</param>
		/// <param name="protectionsApplied">The protections applied.</param>
		/// <returns>
		/// The applied protections.
		/// </returns>
		protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) {
			// We did not recognize the association the provider used to sign the message.
			// Ask the provider to check the signature then.
			var indirectSignedResponse = (IndirectSignedResponse)signedMessage;
			var checkSignatureRequest = new CheckAuthenticationRequest(indirectSignedResponse, this.Channel);
			var checkSignatureResponse = this.Channel.Request<CheckAuthenticationResponse>(checkSignatureRequest);
			if (!checkSignatureResponse.IsValid) {
				Logger.Bindings.Error("Provider reports signature verification failed.");
				throw new InvalidSignatureException(message);
			}

			// If the OP confirms that a handle should be invalidated as well, do that.
			if (!string.IsNullOrEmpty(checkSignatureResponse.InvalidateHandle)) {
				if (this.rpAssociations != null) {
					this.rpAssociations.RemoveAssociation(indirectSignedResponse.ProviderEndpoint, checkSignatureResponse.InvalidateHandle);
				}
			}

			// When we're in dumb mode we can't provide our own replay protection,
			// but for OpenID 2.0 Providers we can rely on them providing it as part
			// of signature verification.
			if (message.Version.Major >= 2) {
				protectionsApplied |= MessageProtections.ReplayProtection;
			}

			return protectionsApplied;
		}
Exemplo n.º 2
0
        /// <summary>
        /// Performs any transformation on an incoming message that may be necessary and/or
        /// validates an incoming message based on the rules of this channel binding element.
        /// </summary>
        /// <param name="message">The incoming message to process.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The protections (if any) that this binding element applied to the message.
        /// Null if this binding element did not even apply to this binding element.
        /// </returns>
        /// <exception cref="ProtocolException">
        /// Thrown when the binding element rules indicate that this message is invalid and should
        /// NOT be processed.
        /// </exception>
        public async Task <MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken)
        {
            var signedMessage = message as ITamperResistantOpenIdMessage;

            if (signedMessage != null)
            {
                Logger.Bindings.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature);
                MessageProtections protectionsApplied = MessageProtections.TamperProtection;

                this.EnsureParametersRequiringSignatureAreSigned(signedMessage);

                Association association = this.GetSpecificAssociation(signedMessage);
                if (association != null)
                {
                    string signature = this.GetSignature(signedMessage, association);
                    if (!MessagingUtilities.EqualsConstantTime(signedMessage.Signature, signature))
                    {
                        Logger.Bindings.Error("Signature verification failed.");
                        throw new InvalidSignatureException(message);
                    }
                }
                else
                {
                    ErrorUtilities.VerifyInternal(this.Channel != null, "Cannot verify private association signature because we don't have a channel.");

                    protectionsApplied = await this.VerifySignatureByUnrecognizedHandleAsync(message, signedMessage, protectionsApplied, cancellationToken);
                }

                return(protectionsApplied);
            }

            return(null);
        }
Exemplo n.º 3
0
		internal static Channel CreateChannel(MessageProtections capability, MessageProtections recognition) {
			var bindingElements = new List<IChannelBindingElement>();
			if (capability >= MessageProtections.TamperProtection) {
				bindingElements.Add(new MockSigningBindingElement());
			}
			if (capability >= MessageProtections.Expiration) {
				bindingElements.Add(new StandardExpirationBindingElement());
			}
			if (capability >= MessageProtections.ReplayProtection) {
				bindingElements.Add(new MockReplayProtectionBindingElement());
			}

			bool signing = false, expiration = false, replay = false;
			if (recognition >= MessageProtections.TamperProtection) {
				signing = true;
			}
			if (recognition >= MessageProtections.Expiration) {
				expiration = true;
			}
			if (recognition >= MessageProtections.ReplayProtection) {
				replay = true;
			}

			var typeProvider = new TestMessageFactory(signing, expiration, replay);
			return new TestChannel(typeProvider, bindingElements.ToArray());
		}
Exemplo n.º 4
0
        /// <summary>
        /// Puts binding elements in their correct outgoing message processing order.
        /// </summary>
        /// <param name="protection1">The first protection type to compare.</param>
        /// <param name="protection2">The second protection type to compare.</param>
        /// <returns>
        /// -1 if <paramref name="element1"/> should be applied to an outgoing message before <paramref name="element2"/>.
        /// 1 if <paramref name="element2"/> should be applied to an outgoing message before <paramref name="element1"/>.
        /// 0 if it doesn't matter.
        /// </returns>
        private static int BindingElementOutgoingMessageApplicationOrder(MessageProtections protection1, MessageProtections protection2)
        {
            ErrorUtilities.VerifyInternal(protection1 != MessageProtections.None || protection2 != MessageProtections.None, "This comparison function should only be used to compare protection binding elements.  Otherwise we change the order of user-defined message transformations.");

            // Now put the protection ones in the right order.
            return(-((int)protection1).CompareTo((int)protection2));            // descending flag ordinal order
        }
Exemplo n.º 5
0
        protected virtual void ProcessIncomingMessageAsync1_ccp(IProtocolMessage message, CancellationToken cancellationToken)
        {
            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.IncomingBindingElements)
            {
                MessageProtections?elementProtection = bindingElement.ProcessIncomingMessage(message, cancellationToken);
                if (elementProtection.HasValue)
                {
                    appliedProtection |= elementProtection.Value;
                }
            }

            //write to global object
            GloabalState.appliedProtection = appliedProtection;

            // Ensure that the message's protection requirements have been satisfied.
            int a = (int)((IndirectSignedResponse)message).RequiredProtection;
            int b = (int)appliedProtection;

            if ((a & b) != a)
            {
                Contract.Assume(false);
            }

            PositiveAssertionResponse1 _msg = (PositiveAssertionResponse1)message;

            _msg.EnsureValidMessage();
        }
Exemplo n.º 6
0
        protected virtual async Task ProcessIncomingMessageAsync_ccp(IProtocolMessage message, CancellationToken cancellationToken)
        {
            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.IncomingBindingElements)
            {
                Assumes.True(bindingElement.Channel != null); // CC bug: this.IncomingBindingElements ensures this... why must we assume it here?
                MessageProtections?elementProtection = await bindingElement.ProcessIncomingMessageAsync(message, cancellationToken);

                if (elementProtection.HasValue)
                {
                    appliedProtection |= elementProtection.Value;
                }
            }

            // Ensure that the message's protection requirements have been satisfied.
            if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection)
            {
                throw new UnprotectedMessageException(message, appliedProtection);
            }

            // We do NOT verify that all required message parts are present here... the
            // message deserializer did for us.  It would be too late to do it here since
            // they might look initialized by the time we have an IProtocolMessage instance.
            message.EnsureValidMessage();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct response messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="originatingRequest">The request that asked for this direct response.</param>
        protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest)
        {
            ErrorUtilities.VerifyArgumentNotNull(originatingRequest, "originatingRequest");

            this.protectionRequired = protectionRequired;
            this.transport = MessageTransport.Direct;
            this.originatingRequest = originatingRequest;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct response messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="originatingRequest">The request that asked for this direct response.</param>
        protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest)
        {
            ErrorUtilities.VerifyArgumentNotNull(originatingRequest, "originatingRequest");

            this.protectionRequired = protectionRequired;
            this.transport          = MessageTransport.Direct;
            this.originatingRequest = originatingRequest;
        }
Exemplo n.º 9
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageBase"/> class for direct response messages.
		/// </summary>
		/// <param name="protectionRequired">The level of protection the message requires.</param>
		/// <param name="originatingRequest">The request that asked for this direct response.</param>
		/// <param name="version">The OAuth version.</param>
		protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest, Version version) {
			Contract.Requires<ArgumentNullException>(originatingRequest != null);
			Contract.Requires<ArgumentNullException>(version != null);

			this.protectionRequired = protectionRequired;
			this.transport = MessageTransport.Direct;
			this.originatingRequest = originatingRequest;
			this.Version = version;
		}
Exemplo n.º 10
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages.
		/// </summary>
		/// <param name="protectionRequired">The level of protection the message requires.</param>
		/// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
		/// <param name="recipient">The URI that a directed message will be delivered to.</param>
		/// <param name="version">The OAuth version.</param>
		protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version) {
			Requires.NotNull(recipient, "recipient");
			Requires.NotNull(version, "version");

			this.protectionRequired = protectionRequired;
			this.transport = transport;
			this.recipient = recipient;
			this.Version = version;
		}
Exemplo n.º 11
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageBase"/> class for direct response messages.
		/// </summary>
		/// <param name="protectionRequired">The level of protection the message requires.</param>
		/// <param name="originatingRequest">The request that asked for this direct response.</param>
		/// <param name="version">The OAuth version.</param>
		protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest, Version version) {
			Requires.NotNull(originatingRequest, "originatingRequest");
			Requires.NotNull(version, "version");

			this.protectionRequired = protectionRequired;
			this.transport = MessageTransport.Direct;
			this.originatingRequest = originatingRequest;
			this.Version = version;
		}
Exemplo n.º 12
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages.
		/// </summary>
		/// <param name="protectionRequired">The level of protection the message requires.</param>
		/// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
		/// <param name="recipient">The URI that a directed message will be delivered to.</param>
		/// <param name="version">The OAuth version.</param>
		protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version) {
			Contract.Requires<ArgumentNullException>(recipient != null);
			Contract.Requires<ArgumentNullException>(version != null);

			this.protectionRequired = protectionRequired;
			this.transport = transport;
			this.recipient = recipient;
			this.Version = version;
		}
Exemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
        /// <param name="recipient">The URI that a directed message will be delivered to.</param>
        /// <param name="version">The OAuth version.</param>
        protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version)
        {
            Contract.Requires <ArgumentNullException>(recipient != null);
            Contract.Requires <ArgumentNullException>(version != null);

            this.protectionRequired = protectionRequired;
            this.transport          = transport;
            this.recipient          = recipient;
            this.Version            = version;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct response messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="originatingRequest">The request that asked for this direct response.</param>
        /// <param name="version">The OAuth version.</param>
        protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest, Version version)
        {
            Contract.Requires <ArgumentNullException>(originatingRequest != null);
            Contract.Requires <ArgumentNullException>(version != null);

            this.protectionRequired = protectionRequired;
            this.transport          = MessageTransport.Direct;
            this.originatingRequest = originatingRequest;
            this.Version            = version;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct response messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="originatingRequest">The request that asked for this direct response.</param>
        /// <param name="version">The OAuth version.</param>
        protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest, Version version)
        {
            Requires.NotNull(originatingRequest, "originatingRequest");
            Requires.NotNull(version, "version");

            this.protectionRequired = protectionRequired;
            this.transport          = MessageTransport.Direct;
            this.originatingRequest = originatingRequest;
            this.Version            = version;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
        /// <param name="recipient">The URI that a directed message will be delivered to.</param>
        /// <param name="version">The OAuth version.</param>
        protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version)
        {
            Requires.NotNull(recipient, "recipient");
            Requires.NotNull(version, "version");

            this.protectionRequired = protectionRequired;
            this.transport          = transport;
            this.recipient          = recipient;
            this.Version            = version;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
        /// <param name="recipient">The URI that a directed message will be delivered to.</param>
        protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient)
        {
            if (recipient == null)
            {
                throw new ArgumentNullException("recipient");
            }

            this.protectionRequired = protectionRequired;
            this.transport          = transport;
            this.recipient          = recipient;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Prepares a message for transmit by applying signatures, nonces, etc.
        /// </summary>
        /// <param name="message">The message to prepare for sending.</param>
        /// <remarks>
        /// This method should NOT be called by derived types
        /// except when sending ONE WAY request messages.
        /// </remarks>
        protected void PrepareMessageForSending(IProtocolMessage message)
        {
            ErrorUtilities.VerifyArgumentNotNull(message, "message");

            Logger.DebugFormat("Preparing to send {0} ({1}) message.", message.GetType().Name, message.Version);
            this.OnSending(message);

            // Give the message a chance to do custom serialization.
            IMessageWithEvents eventedMessage = message as IMessageWithEvents;

            if (eventedMessage != null)
            {
                eventedMessage.OnSending();
            }

            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.outgoingBindingElements)
            {
                if (bindingElement.PrepareMessageForSending(message))
                {
                    Logger.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName);

                    // Ensure that only one protection binding element applies to this message
                    // for each protection type.
                    ErrorUtilities.VerifyProtocol((appliedProtection & bindingElement.Protection) == 0, MessagingStrings.TooManyBindingsOfferingSameProtection, bindingElement.Protection);
                    appliedProtection |= bindingElement.Protection;
                }
                else
                {
                    Logger.DebugFormat("Binding element {0} did not apply to message.", bindingElement.GetType().FullName);
                }
            }

            // Ensure that the message's protection requirements have been satisfied.
            if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection)
            {
                throw new UnprotectedMessageException(message, appliedProtection);
            }

            EnsureValidMessageParts(message);
            message.EnsureValidMessage();

            if (Logger.IsDebugEnabled)
            {
                Logger.DebugFormat(
                    "Sending {0} ({1}) message: {2}{3}",
                    message.GetType().Name,
                    message.Version,
                    Environment.NewLine,
                    new MessageDictionary(message).ToStringDeferred());
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Verifies the integrity and applicability of an incoming message.
        /// </summary>
        /// <param name="message">The message just received.</param>
        /// <exception cref="ProtocolException">
        /// Thrown when the message is somehow invalid.
        /// This can be due to tampering, replay attack or expiration, among other things.
        /// </exception>
        protected virtual void VerifyMessageAfterReceiving(IProtocolMessage message)
        {
            Debug.Assert(message != null, "message == null");

            if (Logger.IsDebugEnabled)
            {
                Logger.DebugFormat(
                    "Preparing to receive {0} ({1}) message:{2}{3}",
                    message.GetType().Name,
                    message.Version,
                    Environment.NewLine,
                    new MessageDictionary(message).ToStringDeferred());
            }

            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.incomingBindingElements)
            {
                if (bindingElement.PrepareMessageForReceiving(message))
                {
                    Logger.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName);

                    // Ensure that only one protection binding element applies to this message
                    // for each protection type.
                    ErrorUtilities.VerifyInternal((appliedProtection & bindingElement.Protection) == 0, MessagingStrings.TooManyBindingsOfferingSameProtection, bindingElement.Protection);
                    appliedProtection |= bindingElement.Protection;
                }
                else
                {
                    Logger.DebugFormat("Binding element {0} did not apply to message.", bindingElement.GetType().FullName);
                }
            }

            // Ensure that the message's protection requirements have been satisfied.
            if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection)
            {
                throw new UnprotectedMessageException(message, appliedProtection);
            }

            // Give the message a chance to do custom serialization.
            IMessageWithEvents eventedMessage = message as IMessageWithEvents;

            if (eventedMessage != null)
            {
                eventedMessage.OnReceiving();
            }

            // We do NOT verify that all required message parts are present here... the
            // message deserializer did for us.  It would be too late to do it here since
            // they might look initialized by the time we have an IProtocolMessage instance.
            message.EnsureValidMessage();
        }
Exemplo n.º 20
0
        protected void ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken)
        {
            Logger.Channel.DebugFormat("Preparing to send {0} ({1}) message.", message.GetType().Name, message.Version);
            this.OnSending(message);
            IMessageWithEvents eventedMessage = message as IMessageWithEvents;

            if (eventedMessage != null)
            {
                eventedMessage.OnSending();
            }
            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.outgoingBindingElements)
            {
                Assumes.True(bindingElement.Channel != null);
                MessageProtections?elementProtection = bindingElement.ProcessOutgoingMessageAsync(message, cancellationToken);
                if (elementProtection.HasValue)
                {
                    Logger.Bindings.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName);
                    ErrorUtilities.VerifyProtocol((appliedProtection & elementProtection.Value) == 0, MessagingStrings.TooManyBindingsOfferingSameProtection, elementProtection.Value);
                    appliedProtection |= elementProtection.Value;
                }
                else
                {
                    Logger.Bindings.DebugFormat("Binding element {0} did not apply to message.", bindingElement.GetType().FullName);
                }
            }
            if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection)
            {
                throw new UnprotectedMessageException(message, appliedProtection);
            }
            this.EnsureValidMessageParts(message);
            message.EnsureValidMessage();
            if (this.OutgoingMessageFilter != null)
            {
                this.OutgoingMessageFilter(message);
            }
            if (Logger.Channel.IsInfoEnabled()) // 日志
            {
                var    directedMessage = message as IDirectedProtocolMessage;
                string recipient       = (directedMessage != null && directedMessage.Recipient != null) ? directedMessage.Recipient.AbsoluteUri : "<response>";
                var    messageAccessor = this.MessageDescriptions.GetAccessor(message);
                Logger.Channel.InfoFormat(
                    "Prepared outgoing {0} ({1}) message for {2}: {3}{4}",
                    message.GetType().Name,
                    message.Version,
                    recipient,
                    Environment.NewLine,
                    messageAccessor.ToStringDeferred());
            }
        }
Exemplo n.º 21
0
        protected virtual void ProcessIncomingMessageAsync1_ccp(IProtocolMessage message, CancellationToken cancellationToken)
        {
            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.IncomingBindingElements)
            {
                MessageProtections?elementProtection = bindingElement.ProcessIncomingMessage(message, cancellationToken);
                if (elementProtection.HasValue)
                {
                    appliedProtection |= elementProtection.Value;
                }
            }

            //write to global object
            GlobalState.appliedProtection = appliedProtection;

            // Ensure that the message's protection requirements have been satisfied.
            int a = (int)((IndirectSignedResponse)message).RequiredProtection;
            int b = (int)appliedProtection;

            if ((a & b) != a)
            {
                Contract.Assume(false);
            }

            PositiveAssertionResponse1 _msg = (PositiveAssertionResponse1)message;

            if (!(_msg.ReturnTo.Scheme == HttpContext.Current.Request.Url.Scheme))
            {
                Contract.Assume(false);
            }

            if (!(_msg.ReturnTo.Authority == HttpContext.Current.Request.Url.Authority))
            {
                Contract.Assume(false);
            }

            if (!(_msg.ReturnTo.AbsolutePath == HttpContext.Current.Request.Url.AbsolutePath))
            {
                Contract.Assume(false);
            }

            if (!(_msg.ReturnTo == HttpContext.Current.Request.Url))
            {
                Contract.Assume(false);
            }
        }
Exemplo n.º 22
0
        protected async Task ProcessOutgoingMessageAsync_CCP(IProtocolMessage message, CancellationToken cancellationToken)
        {
            Requires.NotNull(message, "message");

            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.outgoingBindingElements)
            {
                Assumes.True(bindingElement.Channel != null);
                MessageProtections?elementProtection = await bindingElement.ProcessOutgoingMessageAsync(message, cancellationToken);

                if (elementProtection.HasValue)
                {
                    // Ensure that only one protection binding element applies to this message
                    // for each protection type.
                    ErrorUtilities.VerifyProtocol((appliedProtection & elementProtection.Value) == 0, MessagingStrings.TooManyBindingsOfferingSameProtection, elementProtection.Value);
                    appliedProtection |= elementProtection.Value;
                }
            }

            message.EnsureValidMessage();
        }
Exemplo n.º 23
0
        protected void ProcessOutgoingMessageAsync_CCP(PositiveAssertionResponse1 message, CancellationToken cancellationToken)
        {
            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.outgoingBindingElements)
            {
                Assumes.True(bindingElement.Channel != null);
                MessageProtections?elementProtection = bindingElement.ProcessOutgoingMessage(message, cancellationToken);
                if (elementProtection.HasValue)
                {
                    // Ensure that only one protection binding element applies to this message
                    // for each protection type.

                    if ((appliedProtection & elementProtection.Value) != 0)
                    {
                        Contract.Assume(false);
                    }

                    appliedProtection |= elementProtection.Value;
                }
            }
            message.EnsureValidMessage();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SigningBindingElementChain"/> class.
        /// </summary>
        /// <param name="signers">
        /// The signing binding elements that may be used for some outgoing message,
        /// in preferred use order.
        /// </param>
        internal SigningBindingElementChain(ITamperProtectionChannelBindingElement[] signers)
        {
            if (signers == null)
            {
                throw new ArgumentNullException("signers");
            }
            if (signers.Length == 0)
            {
                throw new ArgumentException(MessagingStrings.SequenceContainsNoElements, "signers");
            }
            if (signers.Contains(null))
            {
                throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, "signers");
            }
            MessageProtections protection = signers[0].Protection;

            if (signers.Any(element => element.Protection != protection))
            {
                throw new ArgumentException(OAuthStrings.SigningElementsMustShareSameProtection, "signers");
            }

            this.signers = signers;
        }
Exemplo n.º 25
0
        internal static Channel CreateChannel(MessageProtections capability, MessageProtections recognition)
        {
            var bindingElements = new List <IChannelBindingElement>();

            if (capability >= MessageProtections.TamperProtection)
            {
                bindingElements.Add(new MockSigningBindingElement());
            }
            if (capability >= MessageProtections.Expiration)
            {
                bindingElements.Add(new StandardExpirationBindingElement());
            }
            if (capability >= MessageProtections.ReplayProtection)
            {
                bindingElements.Add(new MockReplayProtectionBindingElement());
            }

            bool signing = false, expiration = false, replay = false;

            if (recognition >= MessageProtections.TamperProtection)
            {
                signing = true;
            }
            if (recognition >= MessageProtections.Expiration)
            {
                expiration = true;
            }
            if (recognition >= MessageProtections.ReplayProtection)
            {
                replay = true;
            }

            var typeProvider = new TestMessageFactory(signing, expiration, replay);

            return(new TestChannel(typeProvider, bindingElements.ToArray()));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Verifies the signature by unrecognized handle.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="signedMessage">The signed message.</param>
        /// <param name="protectionsApplied">The protections applied.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The applied protections.
        /// </returns>
        protected override Task <MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken)
        {
            // If we're on the Provider, then the RP sent us a check_auth with a signature
            // we don't have an association for.  (It may have expired, or it may be a faulty RP).
            var tcs = new TaskCompletionSource <MessageProtections>();

            tcs.SetException(new InvalidSignatureException(message));
            return(tcs.Task);
        }
		/// <summary>
		/// Verifies the signature by unrecognized handle.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="signedMessage">The signed message.</param>
		/// <param name="protectionsApplied">The protections applied.</param>
		/// <returns>
		/// The applied protections.
		/// </returns>
		protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) {
			throw new NotImplementedException();
		}
Exemplo n.º 28
0
        protected virtual void ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken)
        {
            if (Logger.Channel.IsInfoEnabled()) // 日志记录
            {
                var messageAccessor = this.MessageDescriptions.GetAccessor(message, true);
                Logger.Channel.InfoFormat(
                    "Processing incoming {0} ({1}) message:{2}{3}",
                    message.GetType().Name,
                    message.Version,
                    Environment.NewLine,
                    messageAccessor.ToStringDeferred());
            }
            if (this.IncomingMessageFilter != null)
            {
                this.IncomingMessageFilter(message);
            }

            MessageProtections appliedProtection = MessageProtections.None;

            foreach (IChannelBindingElement bindingElement in this.IncomingBindingElements)
            {
                Assumes.True(bindingElement.Channel != null);
                MessageProtections?elementProtection = bindingElement.ProcessIncomingMessageAsync(message, cancellationToken);
                if (elementProtection.HasValue)
                {
                    Logger.Bindings.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName);
                    if ((appliedProtection & elementProtection.Value) != 0)
                    {
                        Logger.Bindings.WarnFormat(MessagingStrings.TooManyBindingsOfferingSameProtection, elementProtection.Value);
                    }
                    appliedProtection |= elementProtection.Value;
                }
                else
                {
                    Logger.Bindings.DebugFormat("Binding element {0} did not apply to message.", bindingElement.GetType().FullName);
                }
            }
            if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection)
            {
                throw new UnprotectedMessageException(message, appliedProtection);
            }

            IMessageWithEvents eventedMessage = message as IMessageWithEvents;

            if (eventedMessage != null)
            {
                eventedMessage.OnReceiving();
            }

            if (Logger.Channel.IsDebugEnabled()) // 日志记录
            {
                var messageAccessor = this.MessageDescriptions.GetAccessor(message);
                Logger.Channel.DebugFormat(
                    "After binding element processing, the received {0} ({1}) message is: {2}{3}",
                    message.GetType().Name,
                    message.Version,
                    Environment.NewLine,
                    messageAccessor.ToStringDeferred());
            }

            message.EnsureValidMessage();
        }
		/// <summary>
		/// Verifies the signature by unrecognized handle.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="signedMessage">The signed message.</param>
		/// <param name="protectionsApplied">The protections applied.</param>
		/// <returns>
		/// The applied protections.
		/// </returns>
		protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) {
			// If we're on the Provider, then the RP sent us a check_auth with a signature
			// we don't have an association for.  (It may have expired, or it may be a faulty RP).
			throw new InvalidSignatureException(message);
		}
 /// <summary>
 /// Verifies the signature by unrecognized handle.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="signedMessage">The signed message.</param>
 /// <param name="protectionsApplied">The protections applied.</param>
 /// <returns>
 /// The applied protections.
 /// </returns>
 protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied)
 {
     // If we're on the Provider, then the RP sent us a check_auth with a signature
     // we don't have an association for.  (It may have expired, or it may be a faulty RP).
     throw new InvalidSignatureException(message);
 }
        /// <summary>
        /// Verifies the signature by unrecognized handle.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="signedMessage">The signed message.</param>
        /// <param name="protectionsApplied">The protections applied.</param>
        /// <returns>
        /// The applied protections.
        /// </returns>
        protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied)
        {
            // We did not recognize the association the provider used to sign the message.
            // Ask the provider to check the signature then.
            var indirectSignedResponse = (IndirectSignedResponse)signedMessage;
            var checkSignatureRequest  = new CheckAuthenticationRequest(indirectSignedResponse, this.Channel);
            var checkSignatureResponse = this.Channel.Request <CheckAuthenticationResponse>(checkSignatureRequest);

            if (!checkSignatureResponse.IsValid)
            {
                Logger.Bindings.Error("Provider reports signature verification failed.");
                throw new InvalidSignatureException(message);
            }

            // If the OP confirms that a handle should be invalidated as well, do that.
            if (!string.IsNullOrEmpty(checkSignatureResponse.InvalidateHandle))
            {
                if (this.rpAssociations != null)
                {
                    this.rpAssociations.RemoveAssociation(indirectSignedResponse.ProviderEndpoint, checkSignatureResponse.InvalidateHandle);
                }
            }

            // When we're in dumb mode we can't provide our own replay protection,
            // but for OpenID 2.0 Providers we can rely on them providing it as part
            // of signature verification.
            if (message.Version.Major >= 2)
            {
                protectionsApplied |= MessageProtections.ReplayProtection;
            }

            return(protectionsApplied);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Performs any transformation on an incoming message that may be necessary and/or
        /// validates an incoming message based on the rules of this channel binding element.
        /// </summary>
        /// <param name="message">The incoming message to process.</param>
        /// <returns>
        /// The protections (if any) that this binding element applied to the message.
        /// Null if this binding element did not even apply to this binding element.
        /// </returns>
        /// <exception cref="ProtocolException">
        /// Thrown when the binding element rules indicate that this message is invalid and should
        /// NOT be processed.
        /// </exception>
        public MessageProtections?ProcessIncomingMessage(IProtocolMessage message)
        {
            var signedMessage = message as ITamperResistantOpenIdMessage;

            if (signedMessage != null)
            {
                Logger.Bindings.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature);
                MessageProtections protectionsApplied = MessageProtections.TamperProtection;

                this.EnsureParametersRequiringSignatureAreSigned(signedMessage);

                Association association = this.GetSpecificAssociation(signedMessage);
                if (association != null)
                {
                    string signature = this.GetSignature(signedMessage, association);
                    if (!MessagingUtilities.EqualsConstantTime(signedMessage.Signature, signature))
                    {
                        Logger.Bindings.Error("Signature verification failed.");
                        throw new InvalidSignatureException(message);
                    }
                }
                else
                {
                    ErrorUtilities.VerifyInternal(this.Channel != null, "Cannot verify private association signature because we don't have a channel.");

                    // If we're on the Provider, then the RP sent us a check_auth with a signature
                    // we don't have an association for.  (It may have expired, or it may be a faulty RP).
                    if (this.IsOnProvider)
                    {
                        throw new InvalidSignatureException(message);
                    }

                    // We did not recognize the association the provider used to sign the message.
                    // Ask the provider to check the signature then.
                    var indirectSignedResponse = (IndirectSignedResponse)signedMessage;
                    var checkSignatureRequest  = new CheckAuthenticationRequest(indirectSignedResponse, this.Channel);
                    var checkSignatureResponse = this.Channel.Request <CheckAuthenticationResponse>(checkSignatureRequest);
                    if (!checkSignatureResponse.IsValid)
                    {
                        Logger.Bindings.Error("Provider reports signature verification failed.");
                        throw new InvalidSignatureException(message);
                    }

                    // If the OP confirms that a handle should be invalidated as well, do that.
                    if (!string.IsNullOrEmpty(checkSignatureResponse.InvalidateHandle))
                    {
                        if (this.rpAssociations != null)
                        {
                            this.rpAssociations.RemoveAssociation(indirectSignedResponse.ProviderEndpoint, checkSignatureResponse.InvalidateHandle);
                        }
                    }

                    // When we're in dumb mode we can't provide our own replay protection,
                    // but for OpenID 2.0 Providers we can rely on them providing it as part
                    // of signature verification.
                    if (message.Version.Major >= 2)
                    {
                        protectionsApplied |= MessageProtections.ReplayProtection;
                    }
                }

                return(protectionsApplied);
            }

            return(null);
        }
		/// <summary>
		/// Verifies the signature by unrecognized handle.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="signedMessage">The signed message.</param>
		/// <param name="protectionsApplied">The protections applied.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// The applied protections.
		/// </returns>
		protected override Task<MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken) {
			// If we're on the Provider, then the RP sent us a check_auth with a signature
			// we don't have an association for.  (It may have expired, or it may be a faulty RP).
			var tcs = new TaskCompletionSource<MessageProtections>();
			tcs.SetException(new InvalidSignatureException(message));
			return tcs.Task;
		}
Exemplo n.º 34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages.
        /// </summary>
        /// <param name="protectionRequired">The level of protection the message requires.</param>
        /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
        /// <param name="recipient">The URI that a directed message will be delivered to.</param>
        protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient)
        {
            if (recipient == null) {
                throw new ArgumentNullException("recipient");
            }

            this.protectionRequired = protectionRequired;
            this.transport = transport;
            this.recipient = recipient;
        }
Exemplo n.º 35
0
		internal static Channel CreateChannel(MessageProtections capabilityAndRecognition) {
			return CreateChannel(capabilityAndRecognition, capabilityAndRecognition);
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="UnprotectedMessageException"/> class.
		/// </summary>
		/// <param name="faultedMessage">The message whose protection requirements could not be met.</param>
		/// <param name="appliedProtection">The protection requirements that were fulfilled.</param>
		internal UnprotectedMessageException(IProtocolMessage faultedMessage, MessageProtections appliedProtection)
			: base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.InsufficientMessageProtection, faultedMessage.GetType().Name, faultedMessage.RequiredProtection, appliedProtection), faultedMessage) {
		}
 /// <summary>
 /// Verifies the signature by unrecognized handle.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="signedMessage">The signed message.</param>
 /// <param name="protectionsApplied">The protections applied.</param>
 /// <returns>The applied protections.</returns>
 protected abstract MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied);
Exemplo n.º 38
0
 /// <summary>
 /// Verifies the signature by unrecognized handle.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="signedMessage">The signed message.</param>
 /// <param name="protectionsApplied">The protections applied.</param>
 /// <returns>
 /// The applied protections.
 /// </returns>
 protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 39
0
		internal Channel CreateChannel(MessageProtections capabilityAndRecognition) {
			return this.CreateChannel(capabilityAndRecognition, capabilityAndRecognition);
		}
Exemplo n.º 40
0
		/// <summary>
		/// Verifies the signature by unrecognized handle.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="signedMessage">The signed message.</param>
		/// <param name="protectionsApplied">The protections applied.</param>
		/// <returns>The applied protections.</returns>
		protected abstract MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied);
Exemplo n.º 41
0
 /// <summary>
 /// Verifies the signature by unrecognized handle.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="signedMessage">The signed message.</param>
 /// <param name="protectionsApplied">The protections applied.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The applied protections.</returns>
 protected abstract Task <MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken);
Exemplo n.º 42
0
 internal static Channel CreateChannel(MessageProtections capabilityAndRecognition)
 {
     return(CreateChannel(capabilityAndRecognition, capabilityAndRecognition));
 }
Exemplo n.º 43
0
 public UnprotectedMessageException(IProtocolMessage faultedMessage, MessageProtections appliedProtection)
     : base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.InsufficientMessageProtection, faultedMessage.GetType().Name, faultedMessage.RequiredProtection, appliedProtection), faultedMessage)
 {
 }
Exemplo n.º 44
0
		/// <summary>
		/// Verifies the signature by unrecognized handle.
		/// </summary>
		/// <param name="message">The message.</param>
		/// <param name="signedMessage">The signed message.</param>
		/// <param name="protectionsApplied">The protections applied.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>The applied protections.</returns>
		protected abstract Task<MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken);