2
0

SslSecurityTokenAuthenticator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. //
  2. // SslSecurityTokenAuthenticator.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 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.IO;
  32. using System.Net.Security;
  33. using System.IdentityModel.Policy;
  34. using System.IdentityModel.Selectors;
  35. using System.IdentityModel.Tokens;
  36. using System.Security.Cryptography;
  37. using System.Security.Cryptography.X509Certificates;
  38. using System.Security.Cryptography.Xml;
  39. using System.ServiceModel.Channels;
  40. using System.ServiceModel.Description;
  41. using System.ServiceModel.Security;
  42. using System.ServiceModel.Security.Tokens;
  43. using System.Xml;
  44. using ReqType = System.ServiceModel.Security.Tokens.ServiceModelSecurityTokenRequirement;
  45. namespace System.ServiceModel.Security.Tokens
  46. {
  47. // FIXME: implement all
  48. class SslSecurityTokenAuthenticator : CommunicationSecurityTokenAuthenticator
  49. {
  50. ServiceCredentialsSecurityTokenManager manager;
  51. SslAuthenticatorCommunicationObject comm;
  52. bool mutual;
  53. public SslSecurityTokenAuthenticator (
  54. ServiceCredentialsSecurityTokenManager manager,
  55. SecurityTokenRequirement r)
  56. {
  57. this.manager = manager;
  58. mutual = (r.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego);
  59. comm = new SslAuthenticatorCommunicationObject (this);
  60. }
  61. public bool IsMutual {
  62. get { return mutual; }
  63. }
  64. public ServiceCredentialsSecurityTokenManager Manager {
  65. get { return manager; }
  66. }
  67. public override AuthenticatorCommunicationObject Communication {
  68. get { return comm; }
  69. }
  70. protected override bool CanValidateTokenCore (SecurityToken token)
  71. {
  72. throw new NotImplementedException ();
  73. }
  74. protected override ReadOnlyCollection<IAuthorizationPolicy>
  75. ValidateTokenCore (SecurityToken token)
  76. {
  77. throw new NotImplementedException ();
  78. }
  79. }
  80. class SslAuthenticatorCommunicationObject : AuthenticatorCommunicationObject
  81. {
  82. SslSecurityTokenAuthenticator owner;
  83. public SslAuthenticatorCommunicationObject (SslSecurityTokenAuthenticator owner)
  84. {
  85. this.owner = owner;
  86. }
  87. WSTrustSecurityTokenServiceProxy proxy;
  88. protected internal override TimeSpan DefaultCloseTimeout {
  89. get { throw new NotImplementedException (); }
  90. }
  91. protected internal override TimeSpan DefaultOpenTimeout {
  92. get { throw new NotImplementedException (); }
  93. }
  94. public override Message ProcessNegotiation (Message request)
  95. {
  96. if (request.Headers.Action == Constants.WstIssueAction)
  97. return ProcessClientHello (request);
  98. else
  99. return ProcessClientKeyExchange (request);
  100. }
  101. class TlsServerSessionInfo
  102. {
  103. public TlsServerSessionInfo (string context, TlsServerSession tls)
  104. {
  105. ContextId = context;
  106. Tls = tls;
  107. }
  108. public string ContextId;
  109. public TlsServerSession Tls;
  110. public MemoryStream Messages = new MemoryStream ();
  111. }
  112. Dictionary<string,TlsServerSessionInfo> sessions =
  113. new Dictionary<string,TlsServerSessionInfo> ();
  114. void AppendNegotiationMessageXml (XmlReader reader, TlsServerSessionInfo tlsInfo)
  115. {
  116. XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform ();
  117. XmlDocument doc = new XmlDocument ();
  118. doc.PreserveWhitespace = true;
  119. reader.MoveToContent ();
  120. doc.AppendChild (doc.ReadNode (reader));
  121. t.LoadInput (doc);
  122. MemoryStream stream = (MemoryStream) t.GetOutput ();
  123. byte [] bytes = stream.ToArray ();
  124. tlsInfo.Messages.Write (bytes, 0, bytes.Length);
  125. }
  126. Message ProcessClientHello (Message request)
  127. {
  128. // FIXME: use correct buffer size
  129. MessageBuffer buffer = request.CreateBufferedCopy (0x10000);
  130. WSTrustRequestSecurityTokenReader reader =
  131. new WSTrustRequestSecurityTokenReader (buffer.CreateMessage ().GetReaderAtBodyContents (), SecurityTokenSerializer);
  132. reader.Read ();
  133. if (sessions.ContainsKey (reader.Value.Context))
  134. throw new SecurityNegotiationException (String.Format ("The context '{0}' already exists in this SSL negotiation manager", reader.Value.Context));
  135. TlsServerSession tls = new TlsServerSession (owner.Manager.ServiceCredentials.ServiceCertificate.Certificate, owner.IsMutual);
  136. TlsServerSessionInfo tlsInfo = new TlsServerSessionInfo (
  137. reader.Value.Context, tls);
  138. AppendNegotiationMessageXml (buffer.CreateMessage ().GetReaderAtBodyContents (), tlsInfo);
  139. tls.ProcessClientHello (reader.Value.BinaryExchange.Value);
  140. WstRequestSecurityTokenResponse rstr =
  141. new WstRequestSecurityTokenResponse (SecurityTokenSerializer);
  142. rstr.Context = reader.Value.Context;
  143. rstr.BinaryExchange = new WstBinaryExchange (Constants.WstBinaryExchangeValueTls);
  144. rstr.BinaryExchange.Value = tls.ProcessServerHello ();
  145. Message reply = Message.CreateMessage (request.Version, Constants.WstIssueReplyAction, rstr);
  146. reply.Headers.RelatesTo = request.Headers.MessageId;
  147. // FIXME: use correct buffer size
  148. buffer = reply.CreateBufferedCopy (0x10000);
  149. AppendNegotiationMessageXml (buffer.CreateMessage ().GetReaderAtBodyContents (), tlsInfo);
  150. sessions [reader.Value.Context] = tlsInfo;
  151. return buffer.CreateMessage ();
  152. }
  153. Message ProcessClientKeyExchange (Message request)
  154. {
  155. // FIXME: use correct buffer size
  156. MessageBuffer buffer = request.CreateBufferedCopy (0x10000);
  157. WSTrustRequestSecurityTokenResponseReader reader =
  158. new WSTrustRequestSecurityTokenResponseReader (Constants.WstTlsnegoProofTokenType, buffer.CreateMessage ().GetReaderAtBodyContents (), SecurityTokenSerializer, null);
  159. reader.Read ();
  160. TlsServerSessionInfo tlsInfo;
  161. if (!sessions.TryGetValue (reader.Value.Context, out tlsInfo))
  162. throw new SecurityNegotiationException (String.Format ("The context '{0}' does not exist in this SSL negotiation manager", reader.Value.Context));
  163. TlsServerSession tls = tlsInfo.Tls;
  164. AppendNegotiationMessageXml (buffer.CreateMessage ().GetReaderAtBodyContents (), tlsInfo);
  165. //Console.WriteLine (System.Text.Encoding.UTF8.GetString (tlsInfo.Messages.ToArray ()));
  166. tls.ProcessClientKeyExchange (reader.Value.BinaryExchange.Value);
  167. byte [] serverFinished = tls.ProcessServerFinished ();
  168. // The shared key is computed as recommended in WS-Trust:
  169. // P_SHA1(encrypted_key,SHA1(exc14n(RST..RSTRs))+"CK-HASH")
  170. byte [] hash = SHA1.Create ().ComputeHash (tlsInfo.Messages.ToArray ());
  171. byte [] key = tls.CreateHash (tls.MasterSecret, hash, "CK-HASH");
  172. byte [] keyTlsApplied = tls.ProcessApplicationData (key);
  173. foreach (byte b in hash) Console.Write ("{0:X02} ", b); Console.WriteLine ();
  174. foreach (byte b in key) Console.Write ("{0:X02} ", b); Console.WriteLine ();
  175. WstRequestSecurityTokenResponseCollection col =
  176. new WstRequestSecurityTokenResponseCollection ();
  177. WstRequestSecurityTokenResponse rstr =
  178. new WstRequestSecurityTokenResponse (SecurityTokenSerializer);
  179. rstr.Context = reader.Value.Context;
  180. rstr.TokenType = Constants.WsscContextToken;
  181. DateTime from = DateTime.Now;
  182. // FIXME: not sure if arbitrary key is used here.
  183. SecurityContextSecurityToken sct = SecurityContextSecurityToken.CreateCookieSecurityContextToken (
  184. // Create a new context.
  185. // (do not use sslnego context here.)
  186. new UniqueId (),
  187. "uuid-" + Guid.NewGuid (),
  188. key,
  189. from,
  190. // FIXME: use LocalServiceSecuritySettings.NegotiationTimeout
  191. from.AddHours (8),
  192. null,
  193. owner.Manager.ServiceCredentials.SecureConversationAuthentication.SecurityStateEncoder);
  194. rstr.RequestedSecurityToken = sct;
  195. // without this ProcessApplicationData(), .NET seems
  196. // to fail recovering the key.
  197. rstr.RequestedProofToken = keyTlsApplied;
  198. rstr.RequestedAttachedReference = new LocalIdKeyIdentifierClause (sct.Id);
  199. rstr.RequestedUnattachedReference = new SecurityContextKeyIdentifierClause (sct.ContextId, null);
  200. WstLifetime lt = new WstLifetime ();
  201. lt.Created = from;
  202. lt.Expires = from.Add (SecurityBindingElement.LocalServiceSettings.IssuedCookieLifetime);
  203. rstr.Lifetime = lt;
  204. rstr.BinaryExchange = new WstBinaryExchange (Constants.WstBinaryExchangeValueTls);
  205. rstr.BinaryExchange.Value = serverFinished;
  206. col.Responses.Add (rstr);
  207. // Authenticator is mandatory for MS sslnego.
  208. rstr = new WstRequestSecurityTokenResponse (SecurityTokenSerializer);
  209. rstr.Context = reader.Value.Context;
  210. rstr.Authenticator = tls.CreateHash (key, hash, "AUTH-HASH");
  211. col.Responses.Add (rstr);
  212. sessions.Remove (reader.Value.Context);
  213. // FIXME: get correct tokenRequestor address (probably identity authorized?)
  214. if (owner.IssuedSecurityTokenHandler != null)
  215. owner.IssuedSecurityTokenHandler (sct, request.Headers.ReplyTo);
  216. return Message.CreateMessage (request.Version, Constants.WstIssueReplyAction, col);
  217. }
  218. protected override void OnAbort ()
  219. {
  220. throw new NotImplementedException ();
  221. }
  222. protected override void OnOpen (TimeSpan timeout)
  223. {
  224. if (State == CommunicationState.Opened)
  225. throw new InvalidOperationException ("Already opened.");
  226. EnsureProperties ();
  227. proxy = new WSTrustSecurityTokenServiceProxy (
  228. IssuerBinding, IssuerAddress);
  229. }
  230. protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
  231. {
  232. throw new NotImplementedException ();
  233. }
  234. protected override void OnEndOpen (IAsyncResult result)
  235. {
  236. throw new NotImplementedException ();
  237. }
  238. protected override void OnClose (TimeSpan timeout)
  239. {
  240. if (proxy != null)
  241. proxy.Close ();
  242. }
  243. protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
  244. {
  245. throw new NotImplementedException ();
  246. }
  247. protected override void OnEndClose (IAsyncResult result)
  248. {
  249. throw new NotImplementedException ();
  250. }
  251. }
  252. }