SecureMessageDecryptor.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //
  2. // SecureMessageDecryptor.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.ObjectModel;
  31. using System.Globalization;
  32. using System.IdentityModel.Selectors;
  33. using System.IdentityModel.Tokens;
  34. using System.Runtime.Serialization;
  35. using System.Security.Cryptography;
  36. using System.Security.Cryptography.X509Certificates;
  37. using System.Security.Cryptography.Xml;
  38. using System.ServiceModel;
  39. using System.ServiceModel.Channels;
  40. using System.ServiceModel.Description;
  41. using System.ServiceModel.Security;
  42. using System.ServiceModel.Security.Tokens;
  43. using System.Text;
  44. using System.Xml;
  45. using System.Xml.XPath;
  46. using ReqType = System.ServiceModel.Security.Tokens.ServiceModelSecurityTokenRequirement;
  47. namespace System.ServiceModel.Channels
  48. {
  49. internal class RecipientSecureMessageDecryptor : SecureMessageDecryptor
  50. {
  51. RecipientMessageSecurityBindingSupport security;
  52. public RecipientSecureMessageDecryptor (
  53. Message source, RecipientMessageSecurityBindingSupport security)
  54. : base (source, security)
  55. {
  56. this.security = security;
  57. }
  58. public override MessageDirection Direction {
  59. get { return MessageDirection.Input; }
  60. }
  61. public override SecurityMessageProperty RequestSecurity {
  62. get { return null; }
  63. }
  64. public override SecurityTokenParameters Parameters {
  65. get { return security.RecipientParameters; }
  66. }
  67. public override SecurityTokenParameters CounterParameters {
  68. get { return security.InitiatorParameters; }
  69. }
  70. }
  71. internal class InitiatorSecureMessageDecryptor : SecureMessageDecryptor
  72. {
  73. InitiatorMessageSecurityBindingSupport security;
  74. SecurityMessageProperty request_security;
  75. public InitiatorSecureMessageDecryptor (
  76. Message source, SecurityMessageProperty secprop, InitiatorMessageSecurityBindingSupport security)
  77. : base (source, security)
  78. {
  79. this.security = security;
  80. request_security = secprop;
  81. }
  82. public override SecurityMessageProperty RequestSecurity {
  83. get { return request_security; }
  84. }
  85. public override MessageDirection Direction {
  86. get { return MessageDirection.Output; }
  87. }
  88. public override SecurityTokenParameters Parameters {
  89. get { return security.InitiatorParameters; }
  90. }
  91. public override SecurityTokenParameters CounterParameters {
  92. get { return security.RecipientParameters; }
  93. }
  94. }
  95. internal abstract class SecureMessageDecryptor
  96. {
  97. Message source_message;
  98. MessageBuffer buf;
  99. MessageSecurityBindingSupport security;
  100. XmlDocument doc;
  101. XmlNamespaceManager nsmgr; // for XPath query
  102. SecurityMessageProperty sec_prop =
  103. new SecurityMessageProperty ();
  104. WSSecurityMessageHeader wss_header = null;
  105. WSSecurityMessageHeaderReader wss_header_reader;
  106. List<MessageHeaderInfo> headers = new List<MessageHeaderInfo> ();
  107. SecurityTokenResolver token_resolver;
  108. List<SecurityToken> tokens;
  109. protected SecureMessageDecryptor (
  110. Message source, MessageSecurityBindingSupport security)
  111. {
  112. source_message = source;
  113. this.security = security;
  114. // FIXME: use proper max buffer
  115. buf = source.CreateBufferedCopy (int.MaxValue);
  116. doc = new XmlDocument ();
  117. doc.PreserveWhitespace = true;
  118. nsmgr = new XmlNamespaceManager (doc.NameTable);
  119. nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
  120. nsmgr.AddNamespace ("c", Constants.WsscNamespace);
  121. nsmgr.AddNamespace ("o", Constants.WssNamespace);
  122. nsmgr.AddNamespace ("e", EncryptedXml.XmlEncNamespaceUrl);
  123. nsmgr.AddNamespace ("u", Constants.WsuNamespace);
  124. nsmgr.AddNamespace ("dsig", SignedXml.XmlDsigNamespaceUrl);
  125. }
  126. public abstract MessageDirection Direction { get; }
  127. public abstract SecurityTokenParameters Parameters { get; }
  128. public abstract SecurityTokenParameters CounterParameters { get; }
  129. public abstract SecurityMessageProperty RequestSecurity { get; }
  130. public SecurityTokenResolver TokenResolver {
  131. get { return token_resolver; }
  132. }
  133. public Message DecryptMessage ()
  134. {
  135. Message srcmsg = buf.CreateMessage ();
  136. if (srcmsg.Version.Envelope == EnvelopeVersion.None)
  137. throw new ArgumentException ("The message to decrypt is not an expected SOAP envelope.");
  138. string action = GetAction ();
  139. if (action == null)
  140. throw new ArgumentException ("SOAP action could not be retrieved from the message to decrypt.");
  141. XPathNavigator nav = doc.CreateNavigator ();
  142. using (XmlWriter writer = nav.AppendChild ()) {
  143. buf.CreateMessage ().WriteMessage (writer);
  144. }
  145. /*
  146. doc.PreserveWhitespace = false;
  147. doc.Save (Console.Out);
  148. doc.PreserveWhitespace = true;
  149. */
  150. // read and store headers, wsse:Security and setup in-band resolver.
  151. ReadHeaders (srcmsg);
  152. ExtractSecurity ();
  153. Message msg = Message.CreateMessage (new XmlNodeReader (doc), srcmsg.Headers.Count, srcmsg.Version);
  154. for (int i = 0; i < srcmsg.Headers.Count; i++) {
  155. MessageHeaderInfo header = srcmsg.Headers [i];
  156. if (header == wss_header)
  157. msg.Headers.Add (wss_header);
  158. else
  159. msg.Headers.CopyHeaderFrom (srcmsg, i);
  160. }
  161. // FIXME: when Local[Client|Service]SecuritySettings.DetectReplays
  162. // is true, reject such messages which don't have <wsu:Timestamp>
  163. msg.Properties.Add ("Security", sec_prop);
  164. return msg;
  165. }
  166. void ReadHeaders (Message srcmsg)
  167. {
  168. SecurityTokenSerializer serializer =
  169. security.TokenSerializer;
  170. tokens = new List<SecurityToken> ();
  171. token_resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver (
  172. new ReadOnlyCollection <SecurityToken> (tokens),
  173. true);
  174. token_resolver = new UnionSecurityTokenResolver (token_resolver, security.OutOfBandTokenResolver);
  175. // Add relevant protection token and supporting tokens.
  176. tokens.Add (security.EncryptionToken);
  177. // FIXME: this is just a workaround for symmetric binding to not require extra client certificate.
  178. if (security.Element is AsymmetricSecurityBindingElement)
  179. tokens.Add (security.SigningToken);
  180. if (RequestSecurity != null && RequestSecurity.ProtectionToken != null)
  181. tokens.Add (RequestSecurity.ProtectionToken.SecurityToken);
  182. // FIXME: handle supporting tokens
  183. for (int i = 0; i < srcmsg.Headers.Count; i++) {
  184. MessageHeaderInfo header = srcmsg.Headers [i];
  185. // FIXME: check SOAP Actor.
  186. // MessageHeaderDescription.Actor needs to be accessible from here.
  187. if (header.Namespace == Constants.WssNamespace &&
  188. header.Name == "Security") {
  189. wss_header = new WSSecurityMessageHeader (null);
  190. wss_header_reader = new WSSecurityMessageHeaderReader (wss_header, serializer, token_resolver, doc, nsmgr, tokens);
  191. wss_header_reader.ReadContents (srcmsg.Headers.GetReaderAtHeader (i));
  192. headers.Add (wss_header);
  193. }
  194. else
  195. headers.Add (header);
  196. }
  197. if (wss_header == null)
  198. throw new InvalidOperationException ("In this service contract, a WS-Security header is required in the Message, but was not found.");
  199. }
  200. void ExtractSecurity ()
  201. {
  202. if (security.MessageProtectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature &&
  203. wss_header.Find<SignedXml> () != null)
  204. throw new MessageSecurityException ("The security binding element expects that the message signature is encrypted, while it isn't.");
  205. WrappedKeySecurityToken wk = wss_header.Find<WrappedKeySecurityToken> ();
  206. DerivedKeySecurityToken dk = wss_header.Find<DerivedKeySecurityToken> ();
  207. if (wk != null) {
  208. if (Parameters.RequireDerivedKeys && dk == null)
  209. throw new MessageSecurityException ("DerivedKeyToken is required in this contract, but was not found in the message");
  210. }
  211. else
  212. // FIXME: this is kind of hack for symmetric reply processing.
  213. wk = RequestSecurity.ProtectionToken != null ? RequestSecurity.ProtectionToken.SecurityToken as WrappedKeySecurityToken : null;
  214. SymmetricSecurityKey wkkey = wk != null ? wk.SecurityKeys [0] as SymmetricSecurityKey : null;
  215. wss_header_reader.DecryptSecurity (this, wkkey, RequestSecurity != null ? RequestSecurity.EncryptionKey : null);
  216. // signature confirmation
  217. WSSignedXml sxml = wss_header.Find<WSSignedXml> ();
  218. if (sxml == null)
  219. throw new MessageSecurityException ("The the message signature is expected but not found.");
  220. bool confirmed = false;
  221. SecurityKeyIdentifierClause sigClause = null;
  222. foreach (KeyInfoClause kic in sxml.KeyInfo) {
  223. SecurityTokenReferenceKeyInfo r = kic as SecurityTokenReferenceKeyInfo;
  224. if (r != null)
  225. sigClause = r.Clause;
  226. }
  227. if (sigClause == null)
  228. throw new MessageSecurityException ("SecurityTokenReference was not found in dsig:Signature KeyInfo.");
  229. SecurityToken signToken;
  230. SecurityKey signKey;
  231. signToken = TokenResolver.ResolveToken (sigClause);
  232. signKey = signToken.ResolveKeyIdentifierClause (sigClause);
  233. SymmetricSecurityKey symkey = signKey as SymmetricSecurityKey;
  234. if (symkey != null) {
  235. confirmed = sxml.CheckSignature (new HMACSHA1 (symkey.GetSymmetricKey ()));
  236. if (wk != null)
  237. // FIXME: authenticate token
  238. sec_prop.ProtectionToken = new SecurityTokenSpecification (wk, null);
  239. } else {
  240. AsymmetricAlgorithm alg = ((AsymmetricSecurityKey) signKey).GetAsymmetricAlgorithm (security.DefaultSignatureAlgorithm, false);
  241. confirmed = sxml.CheckSignature (alg);
  242. sec_prop.InitiatorToken = new SecurityTokenSpecification (
  243. signToken,
  244. security.TokenAuthenticator.ValidateToken (signToken));
  245. }
  246. if (!confirmed)
  247. throw new MessageSecurityException ("Message signature is invalid.");
  248. // token authentication
  249. // FIXME: it might not be limited to recipient
  250. if (Direction == MessageDirection.Input)
  251. ProcessSupportingTokens (sxml);
  252. sec_prop.EncryptionKey = ((SymmetricSecurityKey) wk.SecurityKeys [0]).GetSymmetricKey ();
  253. sec_prop.ConfirmedSignatures.Add (Convert.ToBase64String (sxml.SignatureValue));
  254. }
  255. #region supporting token processing
  256. // authenticate and map supporting tokens to proper SupportingTokenSpecification list.
  257. void ProcessSupportingTokens (SignedXml sxml)
  258. {
  259. List<SupportingTokenInfo> tokens = new List<SupportingTokenInfo> ();
  260. // First, categorize those tokens in the Security
  261. // header:
  262. // - Endorsing signing
  263. // - Signed signed
  264. // - SignedEncrypted signed encrypted
  265. // - SignedEndorsing signing signed
  266. foreach (object obj in wss_header.Contents) {
  267. SecurityToken token = obj as SecurityToken;
  268. if (token == null)
  269. continue;
  270. bool signed = false, endorsing = false, encrypted = false;
  271. // signed
  272. foreach (Reference r in sxml.SignedInfo.References)
  273. if (r.Uri.Substring (1) == token.Id) {
  274. signed = true;
  275. break;
  276. }
  277. // FIXME: how to get 'encrypted' state?
  278. // FIXME: endorsing
  279. SecurityTokenAttachmentMode mode =
  280. signed ? encrypted ? SecurityTokenAttachmentMode.SignedEncrypted :
  281. endorsing ? SecurityTokenAttachmentMode.SignedEndorsing :
  282. SecurityTokenAttachmentMode.Signed :
  283. SecurityTokenAttachmentMode.Endorsing;
  284. tokens.Add (new SupportingTokenInfo (token, mode, false));
  285. }
  286. // then,
  287. // 1. validate every mandatory supporting token
  288. // parameters (Endpoint-, Operation-). To do that,
  289. // iterate all tokens in the header against every
  290. // parameter in the mandatory list.
  291. // 2. validate every token that is not validated.
  292. // To do that, iterate all supporting token parameters
  293. // and check if any of them can validate it.
  294. SupportingTokenParameters supp;
  295. string action = GetAction ();
  296. ValidateTokensByParameters (security.Element.EndpointSupportingTokenParameters, tokens, false);
  297. if (security.Element.OperationSupportingTokenParameters.TryGetValue (action, out supp))
  298. ValidateTokensByParameters (supp, tokens, false);
  299. ValidateTokensByParameters (security.Element.OptionalEndpointSupportingTokenParameters, tokens, true);
  300. if (security.Element.OptionalOperationSupportingTokenParameters.TryGetValue (action, out supp))
  301. ValidateTokensByParameters (supp, tokens, true);
  302. }
  303. void ValidateTokensByParameters (SupportingTokenParameters supp, List<SupportingTokenInfo> tokens, bool optional)
  304. {
  305. ValidateTokensByParameters (supp.Endorsing, tokens, optional, SecurityTokenAttachmentMode.Endorsing);
  306. ValidateTokensByParameters (supp.Signed, tokens, optional, SecurityTokenAttachmentMode.Signed);
  307. ValidateTokensByParameters (supp.SignedEndorsing, tokens, optional, SecurityTokenAttachmentMode.SignedEndorsing);
  308. ValidateTokensByParameters (supp.SignedEncrypted, tokens, optional, SecurityTokenAttachmentMode.SignedEncrypted);
  309. }
  310. void ValidateTokensByParameters (IEnumerable<SecurityTokenParameters> plist, List<SupportingTokenInfo> tokens, bool optional, SecurityTokenAttachmentMode attachMode)
  311. {
  312. foreach (SecurityTokenParameters p in plist) {
  313. SecurityTokenResolver r;
  314. SecurityTokenAuthenticator a =
  315. security.CreateTokenAuthenticator (p, out r);
  316. SupportingTokenSpecification spec = ValidateTokensByParameters (a, r, tokens);
  317. if (spec == null) {
  318. if (optional)
  319. continue;
  320. else
  321. throw new MessageSecurityException (String.Format ("No security token could be validated for authenticator '{0}' which is indicated by the '{1}' supporting token parameters", a, attachMode));
  322. } else {
  323. // For endorsing tokens, verify corresponding signatures.
  324. switch (attachMode) {
  325. case SecurityTokenAttachmentMode.Endorsing:
  326. case SecurityTokenAttachmentMode.SignedEndorsing:
  327. WSSignedXml esxml = GetSignatureForToken (spec.SecurityToken);
  328. if (esxml == null)
  329. throw new MessageSecurityException (String.Format ("The '{1}' token '{0}' is expected to endorse the primary signature but no corresponding signature is found.", spec.SecurityToken, attachMode));
  330. bool confirmed;
  331. SecurityAlgorithmSuite suite = security.Element.DefaultAlgorithmSuite;
  332. foreach (SecurityTokenReferenceKeyInfo kic in esxml.KeyInfo) {
  333. SecurityKey signKey = spec.SecurityToken.ResolveKeyIdentifierClause (kic.Clause);
  334. SymmetricSecurityKey symkey = signKey as SymmetricSecurityKey;
  335. if (symkey != null) {
  336. confirmed = esxml.CheckSignature (symkey.GetKeyedHashAlgorithm (suite.DefaultSymmetricSignatureAlgorithm));
  337. } else {
  338. AsymmetricAlgorithm alg = ((AsymmetricSecurityKey) signKey).GetAsymmetricAlgorithm (suite.DefaultAsymmetricSignatureAlgorithm, false);
  339. confirmed = esxml.CheckSignature (alg);
  340. }
  341. if (!confirmed)
  342. throw new MessageSecurityException (String.Format ("Signature for '{1}' token '{0}' is invalid.", spec.SecurityToken, attachMode));
  343. break;
  344. }
  345. sec_prop.ConfirmedSignatures.Insert (0, Convert.ToBase64String (esxml.SignatureValue));
  346. break;
  347. }
  348. }
  349. sec_prop.IncomingSupportingTokens.Add (spec);
  350. }
  351. }
  352. WSSignedXml GetSignatureForToken (SecurityToken token)
  353. {
  354. int count = 0;
  355. foreach (WSSignedXml sxml in wss_header.FindAll<WSSignedXml> ()) {
  356. if (count++ == 0)
  357. continue; // primary signature
  358. foreach (SecurityTokenReferenceKeyInfo r in sxml.KeyInfo)
  359. if (token.MatchesKeyIdentifierClause (r.Clause))
  360. return sxml;
  361. }
  362. return null;
  363. }
  364. SupportingTokenSpecification ValidateTokensByParameters (SecurityTokenAuthenticator a, SecurityTokenResolver r, List<SupportingTokenInfo> tokens)
  365. {
  366. foreach (SupportingTokenInfo info in tokens)
  367. if (a.CanValidateToken (info.Token))
  368. return new SupportingTokenSpecification (
  369. info.Token,
  370. a.ValidateToken (info.Token),
  371. info.Mode);
  372. return null;
  373. }
  374. #endregion
  375. string GetAction ()
  376. {
  377. string ret = source_message.Headers.Action;
  378. if (ret == null) {
  379. HttpRequestMessageProperty reqprop =
  380. source_message.Properties ["Action"] as HttpRequestMessageProperty;
  381. if (reqprop != null)
  382. ret = reqprop.Headers ["Action"];
  383. }
  384. return ret;
  385. }
  386. }
  387. }