SpnegoSecurityTokenAuthenticator.cs 11 KB

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