SslSecurityTokenProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //
  2. // SslSecurityTokenProvider.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.IO;
  31. using System.Net.Security;
  32. using System.IdentityModel.Selectors;
  33. using System.IdentityModel.Tokens;
  34. using System.Security.Cryptography;
  35. using System.Security.Cryptography.X509Certificates;
  36. using System.Security.Cryptography.Xml;
  37. using System.ServiceModel;
  38. using System.ServiceModel.Channels;
  39. using System.ServiceModel.Description;
  40. using System.ServiceModel.Security;
  41. using System.ServiceModel.Security.Tokens;
  42. using System.Xml;
  43. using ReqType = System.ServiceModel.Security.Tokens.ServiceModelSecurityTokenRequirement;
  44. namespace System.ServiceModel.Security.Tokens
  45. {
  46. class SslSecurityTokenProvider : CommunicationSecurityTokenProvider
  47. {
  48. SslCommunicationObject comm;
  49. ClientCredentialsSecurityTokenManager manager;
  50. public SslSecurityTokenProvider (ClientCredentialsSecurityTokenManager manager, bool mutual)
  51. {
  52. this.manager = manager;
  53. comm = new SslCommunicationObject (this, mutual);
  54. }
  55. public override ProviderCommunicationObject Communication {
  56. get { return comm; }
  57. }
  58. public ClientCredentialsSecurityTokenManager Manager {
  59. get { return manager; }
  60. }
  61. public override SecurityToken GetOnlineToken (TimeSpan timeout)
  62. {
  63. return comm.GetToken (timeout);
  64. }
  65. }
  66. class SslCommunicationObject : ProviderCommunicationObject
  67. {
  68. SslSecurityTokenProvider owner;
  69. WSTrustSecurityTokenServiceProxy proxy;
  70. X509Certificate2 client_certificate;
  71. public SslCommunicationObject (SslSecurityTokenProvider owner, bool mutual)
  72. {
  73. if (mutual) {
  74. client_certificate = owner.Manager.ClientCredentials.ClientCertificate.Certificate;
  75. if (client_certificate == null)
  76. throw new InvalidOperationException ("ClientCertificate is required for mutual SSL negotiation.");
  77. }
  78. this.owner = owner;
  79. }
  80. class TlsnegoClientSessionContext
  81. {
  82. XmlDocument doc = new XmlDocument ();
  83. XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform ();
  84. MemoryStream stream = new MemoryStream ();
  85. public void StoreMessage (XmlReader reader)
  86. {
  87. doc.RemoveAll ();
  88. doc.AppendChild (doc.ReadNode (reader));
  89. t.LoadInput (doc);
  90. MemoryStream s = (MemoryStream) t.GetOutput ();
  91. byte [] bytes = s.ToArray ();
  92. stream.Write (bytes, 0, bytes.Length);
  93. }
  94. public byte [] GetC14NResults ()
  95. {
  96. return stream.ToArray ();
  97. }
  98. }
  99. public SecurityToken GetToken (TimeSpan timeout)
  100. {
  101. TlsnegoClientSessionContext tlsctx =
  102. new TlsnegoClientSessionContext ();
  103. TlsClientSession tls = new TlsClientSession (IssuerAddress.Uri.ToString (), client_certificate);
  104. WstRequestSecurityToken rst =
  105. new WstRequestSecurityToken ();
  106. string contextId = rst.Context;
  107. // send ClientHello
  108. rst.BinaryExchange = new WstBinaryExchange (Constants.WstBinaryExchangeValueTls);
  109. rst.BinaryExchange.Value = tls.ProcessClientHello ();
  110. Message request = Message.CreateMessage (IssuerBinding.MessageVersion, Constants.WstIssueAction, rst);
  111. request.Headers.MessageId = new UniqueId ();
  112. request.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
  113. request.Headers.To = TargetAddress.Uri;
  114. MessageBuffer buffer = request.CreateBufferedCopy (0x10000);
  115. tlsctx.StoreMessage (buffer.CreateMessage ().GetReaderAtBodyContents ());
  116. Message response = proxy.Issue (buffer.CreateMessage ());
  117. // FIXME: use correct limitation
  118. buffer = response.CreateBufferedCopy (0x10000);
  119. tlsctx.StoreMessage (buffer.CreateMessage ().GetReaderAtBodyContents ());
  120. // receive ServerHello
  121. WSTrustRequestSecurityTokenResponseReader reader =
  122. new WSTrustRequestSecurityTokenResponseReader (Constants.WstTlsnegoProofTokenType, buffer.CreateMessage ().GetReaderAtBodyContents (), SecurityTokenSerializer, null);
  123. reader.Read ();
  124. if (reader.Value.RequestedSecurityToken != null)
  125. return reader.Value.RequestedSecurityToken;
  126. tls.ProcessServerHello (reader.Value.BinaryExchange.Value);
  127. // send ClientKeyExchange
  128. WstRequestSecurityTokenResponse rstr =
  129. new WstRequestSecurityTokenResponse (SecurityTokenSerializer);
  130. rstr.Context = reader.Value.Context;
  131. rstr.BinaryExchange = new WstBinaryExchange (Constants.WstBinaryExchangeValueTls);
  132. rstr.BinaryExchange.Value = tls.ProcessClientKeyExchange ();
  133. request = Message.CreateMessage (IssuerBinding.MessageVersion, Constants.WstIssueReplyAction, rstr);
  134. request.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
  135. request.Headers.To = TargetAddress.Uri;
  136. buffer = request.CreateBufferedCopy (0x10000);
  137. tlsctx.StoreMessage (buffer.CreateMessage ().GetReaderAtBodyContents ());
  138. //Console.WriteLine (System.Text.Encoding.UTF8.GetString (tlsctx.GetC14NResults ()));
  139. // FIXME: regeneration of this instance is somehow required, but should not be.
  140. proxy = new WSTrustSecurityTokenServiceProxy (
  141. IssuerBinding, IssuerAddress);
  142. response = proxy.IssueReply (buffer.CreateMessage ());
  143. // FIXME: use correct limitation
  144. buffer = response.CreateBufferedCopy (0x10000);
  145. WstRequestSecurityTokenResponseCollection coll =
  146. new WstRequestSecurityTokenResponseCollection ();
  147. coll.Read (Constants.WstTlsnegoProofTokenType, buffer.CreateMessage ().GetReaderAtBodyContents (), SecurityTokenSerializer, null);
  148. if (coll.Responses.Count != 2)
  149. throw new SecurityNegotiationException (String.Format ("Expected response is RequestSecurityTokenResponseCollection which contains two RequestSecurityTokenResponse items, but it actually contains {0} items", coll.Responses.Count));
  150. WstRequestSecurityTokenResponse r = coll.Responses [0];
  151. tls.ProcessServerFinished (r.BinaryExchange.Value);
  152. SecurityContextSecurityToken sctSrc =
  153. r.RequestedSecurityToken;
  154. #if false // FIXME: should this final RSTR included in RSTRC considered too?
  155. XmlDocument doc = new XmlDocument ();
  156. doc.PreserveWhitespace = true;
  157. using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateDictionaryWriter (doc.CreateNavigator ().AppendChild ())) {
  158. if (r == null) throw new Exception ("r");
  159. if (dw == null) throw new Exception ("dw");
  160. r.WriteBodyContents (dw);
  161. }
  162. tlsctx.StoreMessage (XmlDictionaryReader.CreateDictionaryReader (new XmlNodeReader (doc)));
  163. #endif
  164. // the RequestedProofToken is represented as 32 bytes
  165. // of TLS ApplicationData.
  166. // - According to WSE2 doc, it is *the* key, but not
  167. // sure it also applies to WCF.
  168. // - WSS4J also seems to store the encryped shared key.
  169. // - (Important) It seems that without tls decryption,
  170. // .NET fails to recover the key.
  171. byte [] proof = tls.ProcessApplicationData (
  172. (byte []) r.RequestedProofToken);
  173. byte [] key = proof;
  174. // Authenticate token.
  175. byte [] actual = coll.Responses [1].Authenticator;
  176. if (actual == null)
  177. throw new SecurityNegotiationException ("Token authenticator is expected in the RequestSecurityTokenResponse but not found.");
  178. if (coll.Responses [0].Context != contextId)
  179. throw new SecurityNegotiationException ("The context Id does not match with that of the corresponding token authenticator.");
  180. // H = sha1(exc14n(RST..RSTRs))
  181. byte [] hash = SHA1.Create ().ComputeHash (tlsctx.GetC14NResults ());
  182. byte [] referent = tls.CreateHash (key, hash, "AUTH-HASH");
  183. Console.WriteLine (System.Text.Encoding.ASCII.GetString (tlsctx.GetC14NResults ()));
  184. Console.Write ("Hash: ");
  185. foreach (byte b in hash) Console.Write ("{0:X02} ", b); Console.WriteLine ();
  186. Console.Write ("Referent: ");
  187. foreach (byte b in referent) Console.Write ("{0:X02} ", b); Console.WriteLine ();
  188. Console.Write ("Actual: ");
  189. foreach (byte b in actual) Console.Write ("{0:X02} ", b); Console.WriteLine ();
  190. Console.Write ("Proof: ");
  191. foreach (byte b in proof) Console.Write ("{0:X02} ", b); Console.WriteLine ();
  192. bool mismatch = referent.Length != actual.Length;
  193. if (!mismatch)
  194. for (int i = 0; i < referent.Length; i++)
  195. if (referent [i] != actual [i])
  196. mismatch = true;
  197. // FIXME: enable verification
  198. // if (mismatch)
  199. // throw new SecurityNegotiationException ("The CombinedHash does not match the expected value.");
  200. return sctSrc;
  201. }
  202. protected internal override TimeSpan DefaultCloseTimeout {
  203. get { throw new NotImplementedException (); }
  204. }
  205. protected internal override TimeSpan DefaultOpenTimeout {
  206. get { throw new NotImplementedException (); }
  207. }
  208. protected override void OnAbort ()
  209. {
  210. throw new NotImplementedException ();
  211. }
  212. protected override void OnOpen (TimeSpan timeout)
  213. {
  214. if (State == CommunicationState.Opened)
  215. throw new InvalidOperationException ("Already opened.");
  216. EnsureProperties ();
  217. proxy = new WSTrustSecurityTokenServiceProxy (
  218. IssuerBinding, IssuerAddress);
  219. }
  220. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  221. {
  222. throw new NotImplementedException ();
  223. }
  224. protected override void OnEndOpen (IAsyncResult result)
  225. {
  226. throw new NotImplementedException ();
  227. }
  228. protected override void OnClose (TimeSpan timeout)
  229. {
  230. if (proxy != null)
  231. proxy.Close ();
  232. }
  233. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  234. {
  235. throw new NotImplementedException ();
  236. }
  237. protected override void OnEndClose (IAsyncResult result)
  238. {
  239. throw new NotImplementedException ();
  240. }
  241. }
  242. }