Added openid.invalidate_handle handling to the RP and OP.
[dotnetoauth.git] / src / DotNetOpenAuth / OpenId / ChannelElements / SigningBindingElement.cs
blob5fda0b700b6b35982125c953901be9667c1a1ddb
1 //-----------------------------------------------------------------------
2 // <copyright file="SigningBindingElement.cs" company="Andrew Arnott">
3 // Copyright (c) Andrew Arnott. All rights reserved.
4 // </copyright>
5 //-----------------------------------------------------------------------
7 namespace DotNetOpenAuth.OpenId.ChannelElements {
8 using System;
9 using System.Collections.Generic;
10 using System.Diagnostics;
11 using System.Linq;
12 using System.Net.Security;
13 using DotNetOpenAuth.Messaging;
14 using DotNetOpenAuth.Messaging.Bindings;
15 using DotNetOpenAuth.Messaging.Reflection;
16 using DotNetOpenAuth.OpenId.Messages;
18 /// <summary>
19 /// Signs and verifies authentication assertions.
20 /// </summary>
21 internal class SigningBindingElement : IChannelBindingElement {
22 /// <summary>
23 /// The association store used by Relying Parties to look up the secrets needed for signing.
24 /// </summary>
25 private readonly IAssociationStore<Uri> rpAssociations;
27 /// <summary>
28 /// The association store used by Providers to look up the secrets needed for signing.
29 /// </summary>
30 private readonly IAssociationStore<AssociationRelyingPartyType> opAssociations;
32 /// <summary>
33 /// Initializes a new instance of the SigningBindingElement class for use by a Relying Party.
34 /// </summary>
35 /// <param name="associations">The association store used to look up the secrets needed for signing.</param>
36 internal SigningBindingElement(IAssociationStore<Uri> associations) {
37 this.rpAssociations = associations;
40 /// <summary>
41 /// Initializes a new instance of the SigningBindingElement class for use by a Provider.
42 /// </summary>
43 /// <param name="associations">The association store used to look up the secrets needed for signing.</param>
44 internal SigningBindingElement(IAssociationStore<AssociationRelyingPartyType> associations) {
45 ErrorUtilities.VerifyArgumentNotNull(associations, "associations");
47 this.opAssociations = associations;
50 #region IChannelBindingElement Properties
52 /// <summary>
53 /// Gets the protection offered (if any) by this binding element.
54 /// </summary>
55 /// <value><see cref="MessageProtections.TamperProtection"/></value>
56 public MessageProtections Protection {
57 get { return MessageProtections.TamperProtection; }
60 /// <summary>
61 /// Gets or sets the channel that this binding element belongs to.
62 /// </summary>
63 public Channel Channel { get; set; }
65 #endregion
67 /// <summary>
68 /// Gets a value indicating whether this binding element is on a Provider channel.
69 /// </summary>
70 private bool IsOnProvider {
71 get { return this.opAssociations != null; }
74 #region IChannelBindingElement Methods
76 /// <summary>
77 /// Prepares a message for sending based on the rules of this channel binding element.
78 /// </summary>
79 /// <param name="message">The message to prepare for sending.</param>
80 /// <returns>
81 /// True if the <paramref name="message"/> applied to this binding element
82 /// and the operation was successful. False otherwise.
83 /// </returns>
84 public bool PrepareMessageForSending(IProtocolMessage message) {
85 var signedMessage = message as ITamperResistantOpenIdMessage;
86 if (signedMessage != null) {
87 Logger.DebugFormat("Signing {0} message.", message.GetType().Name);
88 Association association = this.GetAssociation(signedMessage);
89 signedMessage.AssociationHandle = association.Handle;
90 signedMessage.SignedParameterOrder = GetSignedParameterOrder(signedMessage);
91 signedMessage.Signature = this.GetSignature(signedMessage, association);
92 return true;
95 return false;
98 /// <summary>
99 /// Performs any transformation on an incoming message that may be necessary and/or
100 /// validates an incoming message based on the rules of this channel binding element.
101 /// </summary>
102 /// <param name="message">The incoming message to process.</param>
103 /// <returns>
104 /// True if the <paramref name="message"/> applied to this binding element
105 /// and the operation was successful. False if the operation did not apply to this message.
106 /// </returns>
107 /// <exception cref="ProtocolException">
108 /// Thrown when the binding element rules indicate that this message is invalid and should
109 /// NOT be processed.
110 /// </exception>
111 public bool PrepareMessageForReceiving(IProtocolMessage message) {
112 var signedMessage = message as ITamperResistantOpenIdMessage;
113 if (signedMessage != null) {
114 Logger.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature);
116 EnsureParametersRequiringSignatureAreSigned(signedMessage);
118 Association association = this.GetSpecificAssociation(signedMessage);
119 if (association != null) {
120 string signature = this.GetSignature(signedMessage, association);
121 if (!string.Equals(signedMessage.Signature, signature, StringComparison.Ordinal)) {
122 Logger.Error("Signature verification failed.");
123 throw new InvalidSignatureException(message);
125 } else {
126 ErrorUtilities.VerifyInternal(this.Channel != null, "Cannot verify private association signature because we don't have a channel.");
128 // We did not recognize the association the provider used to sign the message.
129 // Ask the provider to check the signature then.
130 var indirectSignedResponse = (IndirectSignedResponse)signedMessage;
131 var checkSignatureRequest = new CheckAuthenticationRequest(indirectSignedResponse);
132 var checkSignatureResponse = this.Channel.Request<CheckAuthenticationResponse>(checkSignatureRequest);
133 if (!checkSignatureResponse.IsValid) {
134 Logger.Error("Provider reports signature verification failed.");
135 throw new InvalidSignatureException(message);
138 // If the OP confirms that a handle should be invalidated as well, do that.
139 if (!string.IsNullOrEmpty(checkSignatureResponse.InvalidateHandle)) {
140 this.rpAssociations.RemoveAssociation(indirectSignedResponse.ProviderEndpoint, checkSignatureResponse.InvalidateHandle);
144 return true;
147 return false;
150 #endregion
152 /// <summary>
153 /// Ensures that all message parameters that must be signed are in fact included
154 /// in the signature.
155 /// </summary>
156 /// <param name="signedMessage">The signed message.</param>
157 private static void EnsureParametersRequiringSignatureAreSigned(ITamperResistantOpenIdMessage signedMessage) {
158 // Verify that the signed parameter order includes the mandated fields.
159 // We do this in such a way that derived classes that add mandated fields automatically
160 // get included in the list of checked parameters.
161 Protocol protocol = Protocol.Lookup(signedMessage.Version);
162 var partsRequiringProtection = from part in MessageDescription.Get(signedMessage.GetType(), signedMessage.Version).Mapping.Values
163 where part.RequiredProtection != ProtectionLevel.None
164 select part.Name;
165 ErrorUtilities.VerifyInternal(partsRequiringProtection.All(name => name.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal)), "Signing only works when the parameters start with the 'openid.' prefix.");
166 string[] signedParts = signedMessage.SignedParameterOrder.Split(',');
167 var unsignedParts = from partName in partsRequiringProtection
168 where !signedParts.Contains(partName.Substring(protocol.openid.Prefix.Length))
169 select partName;
170 ErrorUtilities.VerifyProtocol(!unsignedParts.Any(), OpenIdStrings.SignatureDoesNotIncludeMandatoryParts, string.Join(", ", unsignedParts.ToArray()));
173 /// <summary>
174 /// Gets the value to use for the openid.signed parameter.
175 /// </summary>
176 /// <param name="signedMessage">The signable message.</param>
177 /// <returns>
178 /// A comma-delimited list of parameter names, omitting the 'openid.' prefix, that determines
179 /// the inclusion and order of message parts that will be signed.
180 /// </returns>
181 private static string GetSignedParameterOrder(ITamperResistantOpenIdMessage signedMessage) {
182 ErrorUtilities.VerifyArgumentNotNull(signedMessage, "signedMessage");
184 MessageDescription description = MessageDescription.Get(signedMessage.GetType(), signedMessage.Version);
185 var signedParts = from part in description.Mapping.Values
186 where (part.RequiredProtection & System.Net.Security.ProtectionLevel.Sign) != 0
187 && part.GetValue(signedMessage) != null
188 select part.Name;
189 string prefix = Protocol.V20.openid.Prefix;
190 Debug.Assert(signedParts.All(name => name.StartsWith(prefix, StringComparison.Ordinal)), "All signed message parts must start with 'openid.'.");
191 int skipLength = prefix.Length;
192 string signedFields = string.Join(",", signedParts.Select(name => name.Substring(skipLength)).ToArray());
193 return signedFields;
196 /// <summary>
197 /// Calculates the signature for a given message.
198 /// </summary>
199 /// <param name="signedMessage">The message to sign or verify.</param>
200 /// <param name="association">The association to use to sign the message.</param>
201 /// <returns>The calculated signature of the method.</returns>
202 private string GetSignature(ITamperResistantOpenIdMessage signedMessage, Association association) {
203 ErrorUtilities.VerifyArgumentNotNull(signedMessage, "signedMessage");
204 ErrorUtilities.VerifyNonZeroLength(signedMessage.SignedParameterOrder, "signedMessage.SignedParameterOrder");
205 ErrorUtilities.VerifyArgumentNotNull(association, "association");
207 // Prepare the parts to sign, taking care to replace an openid.mode value
208 // of check_authentication with its original id_res so the signature matches.
209 Protocol protocol = Protocol.Lookup(signedMessage.Version);
210 MessageDictionary dictionary = new MessageDictionary(signedMessage);
211 var parametersToSign = from name in signedMessage.SignedParameterOrder.Split(',')
212 let prefixedName = Protocol.V20.openid.Prefix + name
213 select new KeyValuePair<string, string>(prefixedName, dictionary[prefixedName]);
215 byte[] dataToSign = KeyValueFormEncoding.GetBytes(parametersToSign);
216 return Convert.ToBase64String(association.Sign(dataToSign));
219 /// <summary>
220 /// Gets the association to use to sign or verify a message.
221 /// </summary>
222 /// <param name="signedMessage">The message to sign or verify.</param>
223 /// <returns>The association to use to sign or verify the message.</returns>
224 private Association GetAssociation(ITamperResistantOpenIdMessage signedMessage) {
225 if (this.IsOnProvider) {
226 // We're on a Provider to either sign (smart/dumb) or verify a dumb signature.
227 return this.GetSpecificAssociation(signedMessage) ?? this.GetDumbAssociationForSigning();
228 } else {
229 // We're on a Relying Party verifying a signature.
230 IDirectedProtocolMessage directedMessage = (IDirectedProtocolMessage)signedMessage;
231 return this.rpAssociations.GetAssociation(directedMessage.Recipient, signedMessage.AssociationHandle);
235 /// <summary>
236 /// Gets a specific association referenced in a given message's association handle.
237 /// </summary>
238 /// <param name="signedMessage">The signed message whose association handle should be used to lookup the association to return.</param>
239 /// <returns>The referenced association; or <c>null</c> if such an association cannot be found.</returns>
240 /// <remarks>
241 /// If the association handle set in the message does not match any valid association,
242 /// the association handle property is cleared, and the
243 /// <see cref="ITamperResistantOpenIdMessage.InvalidateHandle"/> property is set to the
244 /// handle that could not be found.
245 /// </remarks>
246 private Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage) {
247 Association association = null;
249 if (!string.IsNullOrEmpty(signedMessage.AssociationHandle)) {
250 if (this.IsOnProvider) {
251 // Since we have an association handle, we're either signing with a smart association,
252 // or verifying a dumb one.
253 bool signing = string.IsNullOrEmpty(signedMessage.Signature);
254 ErrorUtilities.VerifyInternal(signing == (signedMessage is PositiveAssertionResponse), "Ooops... somehow we think we're signing a message that isn't a positive assertion!");
255 AssociationRelyingPartyType type = signing ? AssociationRelyingPartyType.Smart : AssociationRelyingPartyType.Dumb;
256 association = this.opAssociations.GetAssociation(type, signedMessage.AssociationHandle);
257 if (association == null) {
258 // There was no valid association with the requested handle.
259 // Let's tell the RP to forget about that association.
260 signedMessage.InvalidateHandle = signedMessage.AssociationHandle;
261 signedMessage.AssociationHandle = null;
263 } else if (this.rpAssociations != null) { // if on a smart RP
264 Uri providerEndpoint = ((PositiveAssertionResponse)signedMessage).ProviderEndpoint;
265 association = this.rpAssociations.GetAssociation(providerEndpoint, signedMessage.AssociationHandle);
269 return association;
272 /// <summary>
273 /// Gets a private Provider association used for signing messages in "dumb" mode.
274 /// </summary>
275 /// <returns>An existing or newly created association.</returns>
276 private Association GetDumbAssociationForSigning() {
277 // If no assoc_handle was given or it was invalid, the only thing
278 // left to do is sign a message using a 'dumb' mode association.
279 Protocol protocol = Protocol.Default;
280 Association association = this.opAssociations.GetAssociation(AssociationRelyingPartyType.Dumb);
281 if (association == null) {
282 association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.HMAC_SHA256, AssociationRelyingPartyType.Dumb);
283 this.opAssociations.StoreAssociation(AssociationRelyingPartyType.Dumb, association);
286 return association;