SecureMessageDecryptor.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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.Security
  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. //Console.WriteLine ("####### " + buf.CreateMessage ());
  117. doc = new XmlDocument ();
  118. doc.PreserveWhitespace = true;
  119. nsmgr = new XmlNamespaceManager (doc.NameTable);
  120. nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
  121. nsmgr.AddNamespace ("c", Constants.WsscNamespace);
  122. nsmgr.AddNamespace ("o", Constants.WssNamespace);
  123. nsmgr.AddNamespace ("e", EncryptedXml.XmlEncNamespaceUrl);
  124. nsmgr.AddNamespace ("u", Constants.WsuNamespace);
  125. nsmgr.AddNamespace ("dsig", SignedXml.XmlDsigNamespaceUrl);
  126. }
  127. public abstract MessageDirection Direction { get; }
  128. public abstract SecurityTokenParameters Parameters { get; }
  129. public abstract SecurityTokenParameters CounterParameters { get; }
  130. public abstract SecurityMessageProperty RequestSecurity { get; }
  131. public SecurityTokenResolver TokenResolver {
  132. get { return token_resolver; }
  133. }
  134. public Message DecryptMessage ()
  135. {
  136. Message srcmsg = buf.CreateMessage ();
  137. if (srcmsg.Version.Envelope == EnvelopeVersion.None)
  138. throw new ArgumentException ("The message to decrypt is not an expected SOAP envelope.");
  139. XPathNavigator nav = doc.CreateNavigator ();
  140. using (XmlWriter writer = nav.AppendChild ()) {
  141. buf.CreateMessage ().WriteMessage (writer);
  142. }
  143. /*
  144. doc.PreserveWhitespace = false;
  145. doc.Save (Console.Out);
  146. doc.PreserveWhitespace = true;
  147. */
  148. // read and store headers, wsse:Security and setup in-band resolver.
  149. ReadHeaders (srcmsg);
  150. ExtractSecurity ();
  151. Message msg = Message.CreateMessage (new XmlNodeReader (doc), srcmsg.Headers.Count, srcmsg.Version);
  152. for (int i = 0; i < srcmsg.Headers.Count; i++) {
  153. MessageHeaderInfo header = srcmsg.Headers [i];
  154. if (header == wss_header) {
  155. msg.Headers.RemoveAt (i);
  156. msg.Headers.Add (wss_header);
  157. }
  158. }
  159. // FIXME: when Local[Client|Service]SecuritySettings.DetectReplays
  160. // is true, reject such messages which don't have <wsu:Timestamp>
  161. msg.Properties.Add ("Security", sec_prop);
  162. return msg;
  163. }
  164. void ReadHeaders (Message srcmsg)
  165. {
  166. SecurityTokenSerializer serializer =
  167. security.TokenSerializer;
  168. tokens = new List<SecurityToken> ();
  169. token_resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver (
  170. new ReadOnlyCollection <SecurityToken> (tokens),
  171. true);
  172. token_resolver = new UnionSecurityTokenResolver (token_resolver, security.OutOfBandTokenResolver);
  173. // Add relevant protection token and supporting tokens.
  174. tokens.Add (security.EncryptionToken);
  175. // FIXME: this is just a workaround for symmetric binding to not require extra client certificate.
  176. if (security.Element is AsymmetricSecurityBindingElement)
  177. tokens.Add (security.SigningToken);
  178. if (RequestSecurity != null && RequestSecurity.ProtectionToken != null)
  179. tokens.Add (RequestSecurity.ProtectionToken.SecurityToken);
  180. // FIXME: handle supporting tokens
  181. for (int i = 0; i < srcmsg.Headers.Count; i++) {
  182. MessageHeaderInfo header = srcmsg.Headers [i];
  183. // FIXME: check SOAP Actor.
  184. // MessageHeaderDescription.Actor needs to be accessible from here.
  185. if (header.Namespace == Constants.WssNamespace &&
  186. header.Name == "Security") {
  187. wss_header = new WSSecurityMessageHeader (null);
  188. wss_header_reader = new WSSecurityMessageHeaderReader (wss_header, serializer, token_resolver, doc, nsmgr, tokens);
  189. wss_header_reader.ReadContents (srcmsg.Headers.GetReaderAtHeader (i));
  190. headers.Add (wss_header);
  191. }
  192. else
  193. headers.Add (header);
  194. }
  195. if (wss_header == null)
  196. throw new InvalidOperationException ("In this service contract, a WS-Security header is required in the Message, but was not found.");
  197. }
  198. void ExtractSecurity ()
  199. {
  200. if (security.MessageProtectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature &&
  201. wss_header.Find<SignedXml> () != null)
  202. throw new MessageSecurityException ("The security binding element expects that the message signature is encrypted, while it isn't.");
  203. WrappedKeySecurityToken wk = wss_header.Find<WrappedKeySecurityToken> ();
  204. DerivedKeySecurityToken dk = wss_header.Find<DerivedKeySecurityToken> ();
  205. if (wk != null) {
  206. if (Parameters.RequireDerivedKeys && dk == null)
  207. throw new MessageSecurityException ("DerivedKeyToken is required in this contract, but was not found in the message");
  208. }
  209. else
  210. // FIXME: this is kind of hack for symmetric reply processing.
  211. wk = RequestSecurity.ProtectionToken != null ? RequestSecurity.ProtectionToken.SecurityToken as WrappedKeySecurityToken : null;
  212. SymmetricSecurityKey wkkey = wk != null ? wk.SecurityKeys [0] as SymmetricSecurityKey : null;
  213. wss_header_reader.DecryptSecurity (this, wkkey, RequestSecurity != null ? RequestSecurity.EncryptionKey : null);
  214. // signature confirmation
  215. WSSignedXml sxml = wss_header.Find<WSSignedXml> ();
  216. if (sxml == null)
  217. throw new MessageSecurityException ("The the message signature is expected but not found.");
  218. bool confirmed = false;
  219. SecurityKeyIdentifierClause sigClause = null;
  220. foreach (KeyInfoClause kic in sxml.KeyInfo) {
  221. SecurityTokenReferenceKeyInfo r = kic as SecurityTokenReferenceKeyInfo;
  222. if (r != null)
  223. sigClause = r.Clause;
  224. }
  225. if (sigClause == null)
  226. throw new MessageSecurityException ("SecurityTokenReference was not found in dsig:Signature KeyInfo.");
  227. SecurityToken signToken;
  228. SecurityKey signKey;
  229. signToken = TokenResolver.ResolveToken (sigClause);
  230. signKey = signToken.ResolveKeyIdentifierClause (sigClause);
  231. SymmetricSecurityKey symkey = signKey as SymmetricSecurityKey;
  232. if (symkey != null) {
  233. confirmed = sxml.CheckSignature (new HMACSHA1 (symkey.GetSymmetricKey ()));
  234. if (wk != null)
  235. // FIXME: authenticate token
  236. sec_prop.ProtectionToken = new SecurityTokenSpecification (wk, null);
  237. } else {
  238. AsymmetricAlgorithm alg = ((AsymmetricSecurityKey) signKey).GetAsymmetricAlgorithm (security.DefaultSignatureAlgorithm, false);
  239. confirmed = sxml.CheckSignature (alg);
  240. sec_prop.InitiatorToken = new SecurityTokenSpecification (
  241. signToken,
  242. security.TokenAuthenticator.ValidateToken (signToken));
  243. }
  244. if (!confirmed)
  245. throw new MessageSecurityException ("Message signature is invalid.");
  246. // token authentication
  247. // FIXME: it might not be limited to recipient
  248. if (Direction == MessageDirection.Input)
  249. ProcessSupportingTokens (sxml);
  250. sec_prop.EncryptionKey = ((SymmetricSecurityKey) wk.SecurityKeys [0]).GetSymmetricKey ();
  251. sec_prop.ConfirmedSignatures.Add (Convert.ToBase64String (sxml.SignatureValue));
  252. }
  253. #region supporting token processing
  254. // authenticate and map supporting tokens to proper SupportingTokenSpecification list.
  255. void ProcessSupportingTokens (SignedXml sxml)
  256. {
  257. List<SupportingTokenInfo> tokens = new List<SupportingTokenInfo> ();
  258. // First, categorize those tokens in the Security
  259. // header:
  260. // - Endorsing signing
  261. // - Signed signed
  262. // - SignedEncrypted signed encrypted
  263. // - SignedEndorsing signing signed
  264. foreach (object obj in wss_header.Contents) {
  265. SecurityToken token = obj as SecurityToken;
  266. if (token == null)
  267. continue;
  268. bool signed = false, endorsing = false, encrypted = false;
  269. // signed
  270. foreach (Reference r in sxml.SignedInfo.References)
  271. if (r.Uri.Substring (1) == token.Id) {
  272. signed = true;
  273. break;
  274. }
  275. // FIXME: how to get 'encrypted' state?
  276. // FIXME: endorsing
  277. SecurityTokenAttachmentMode mode =
  278. signed ? encrypted ? SecurityTokenAttachmentMode.SignedEncrypted :
  279. endorsing ? SecurityTokenAttachmentMode.SignedEndorsing :
  280. SecurityTokenAttachmentMode.Signed :
  281. SecurityTokenAttachmentMode.Endorsing;
  282. tokens.Add (new SupportingTokenInfo (token, mode, false));
  283. }
  284. // then,
  285. // 1. validate every mandatory supporting token
  286. // parameters (Endpoint-, Operation-). To do that,
  287. // iterate all tokens in the header against every
  288. // parameter in the mandatory list.
  289. // 2. validate every token that is not validated.
  290. // To do that, iterate all supporting token parameters
  291. // and check if any of them can validate it.
  292. SupportingTokenParameters supp;
  293. string action = GetAction ();
  294. if (action == null)
  295. throw new ArgumentException ("SOAP action could not be retrieved from the message to decrypt.");
  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[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
  381. if (reqprop != null)
  382. ret = reqprop.Headers ["Action"];
  383. }
  384. return ret;
  385. }
  386. }
  387. }