TlsClientSession.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // TlsClientSession.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.IO;
  31. using System.Security.Cryptography;
  32. using System.Security.Cryptography.X509Certificates;
  33. using System.Text;
  34. using Mono.Security.Protocol.Tls;
  35. using Mono.Security.Protocol.Tls.Handshake;
  36. using Mono.Security.Protocol.Tls.Handshake.Client;
  37. namespace System.ServiceModel.Security.Tokens
  38. {
  39. internal abstract class TlsSession
  40. {
  41. protected abstract Context Context { get; }
  42. protected abstract RecordProtocol Protocol { get; }
  43. public byte [] MasterSecret {
  44. get { return Context.MasterSecret; }
  45. }
  46. public byte [] CreateHash (byte [] key, byte [] seedSrc, string label)
  47. {
  48. byte [] labelBytes = Encoding.UTF8.GetBytes (label);
  49. byte [] seed = new byte [seedSrc.Length + labelBytes.Length];
  50. Array.Copy (seedSrc, seed, seedSrc.Length);
  51. Array.Copy (labelBytes, 0, seed, seedSrc.Length, labelBytes.Length);
  52. return Context.Current.Cipher.Expand ("SHA1", key, seed, 256 / 8);
  53. }
  54. public byte [] CreateHashAlt (byte [] key, byte [] seed, string label)
  55. {
  56. return Context.Current.Cipher.PRF (key, label, seed, 256 / 8);
  57. }
  58. protected void WriteHandshake (MemoryStream ms)
  59. {
  60. Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (SecurityProtocolType.Tls);
  61. ms.WriteByte (0x16); // Handshake
  62. ms.WriteByte (3); // version-major
  63. ms.WriteByte (1); // version-minor
  64. }
  65. protected void WriteChangeCipherSpec (MemoryStream ms)
  66. {
  67. ms.WriteByte (0x14); // Handshake
  68. ms.WriteByte (3); // version-major
  69. ms.WriteByte (1); // version-minor
  70. ms.WriteByte (0); // size-upper
  71. ms.WriteByte (1); // size-lower
  72. ms.WriteByte (1); // ChangeCipherSpec content (1 byte)
  73. }
  74. protected void ReadHandshake (MemoryStream ms)
  75. {
  76. if (ms.ReadByte () != 0x16)
  77. throw new Exception ("INTERNAL ERROR: handshake is expected");
  78. Context.ChangeProtocol ((short) (ms.ReadByte () * 0x100 + ms.ReadByte ()));
  79. }
  80. protected void ReadChangeCipherSpec (MemoryStream ms)
  81. {
  82. if (ms.ReadByte () != 0x14)
  83. throw new Exception ("INTERNAL ERROR: ChangeCipherSpec is expected");
  84. Context.ChangeProtocol ((short) (ms.ReadByte () * 0x100 + ms.ReadByte ()));
  85. if (ms.ReadByte () * 0x100 + ms.ReadByte () != 1)
  86. throw new Exception ("INTERNAL ERROR: unexpected ChangeCipherSpec length");
  87. ms.ReadByte (); // ChangeCipherSpec content (1 byte) ... anything is OK?
  88. }
  89. protected byte [] ReadNextOperation (MemoryStream ms, HandshakeType expected)
  90. {
  91. if (ms.ReadByte () != (int) expected)
  92. throw new Exception ("INTERNAL ERROR: unexpected server response");
  93. int size = ms.ReadByte () * 0x10000 + ms.ReadByte () * 0x100 + ms.ReadByte ();
  94. // FIXME: use correct valid input range
  95. if (size > 0x100000)
  96. throw new Exception ("rejected massive input size.");
  97. byte [] bytes = new byte [size];
  98. ms.Read (bytes, 0, size);
  99. return bytes;
  100. }
  101. protected void WriteOperations (MemoryStream ms, params HandshakeMessage [] msgs)
  102. {
  103. List<byte []> rawbufs = new List<byte []> ();
  104. int total = 0;
  105. for (int i = 0; i < msgs.Length; i++) {
  106. HandshakeMessage msg = msgs [i];
  107. msg.Process ();
  108. rawbufs.Add (msg.EncodeMessage ());
  109. total += rawbufs [i].Length;
  110. msg.Update ();
  111. }
  112. // FIXME: split packets when the size exceeded 0x10000 (or so)
  113. ms.WriteByte ((byte) (total / 0x100));
  114. ms.WriteByte ((byte) (total % 0x100));
  115. foreach (byte [] bytes in rawbufs)
  116. ms.Write (bytes, 0, bytes.Length);
  117. }
  118. protected void VerifyEndOfTransmit (MemoryStream ms)
  119. {
  120. if (ms.Position == ms.Length)
  121. return;
  122. /*
  123. byte [] bytes = new byte [ms.Length - ms.Position];
  124. ms.Read (bytes, 0, bytes.Length);
  125. foreach (byte b in bytes)
  126. Console.Write ("{0:X02} ", b);
  127. Console.WriteLine (" - total {0} bytes remained.", bytes.Length);
  128. */
  129. throw new Exception ("INTERNAL ERROR: unexpected server response");
  130. }
  131. }
  132. internal class TlsClientSession : TlsSession
  133. {
  134. SslClientStream ssl;
  135. MemoryStream stream;
  136. bool mutual;
  137. public TlsClientSession (string host, X509Certificate2 clientCert)
  138. {
  139. stream = new MemoryStream ();
  140. if (clientCert == null)
  141. ssl = new SslClientStream (stream, host, true, SecurityProtocolType.Tls);
  142. else {
  143. ssl = new SslClientStream (stream, host, true, SecurityProtocolType.Tls, new X509CertificateCollection (new X509Certificate [] {clientCert}));
  144. mutual = true;
  145. ssl.ClientCertSelection += delegate (
  146. X509CertificateCollection clientCertificates,
  147. X509Certificate serverCertificate,
  148. string targetHost,
  149. X509CertificateCollection serverRequestedCertificates) {
  150. return clientCertificates [0];
  151. };
  152. }
  153. }
  154. protected override Context Context {
  155. get { return ssl.context; }
  156. }
  157. protected override RecordProtocol Protocol {
  158. get { return ssl.protocol; }
  159. }
  160. public byte [] ProcessClientHello ()
  161. {
  162. Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (Context.SecurityProtocol);
  163. Context.HandshakeState = HandshakeState.Started;
  164. Protocol.SendRecord (HandshakeType.ClientHello);
  165. stream.Flush ();
  166. return stream.ToArray ();
  167. }
  168. // ServerHello, ServerCertificate and ServerHelloDone
  169. public void ProcessServerHello (byte [] raw)
  170. {
  171. stream.SetLength (0);
  172. stream.Write (raw, 0, raw.Length);
  173. stream.Seek (0, SeekOrigin.Begin);
  174. Protocol.ReceiveRecord (stream); // ServerHello
  175. Protocol.ReceiveRecord (stream); // ServerCertificate
  176. if (mutual)
  177. Protocol.ReceiveRecord (stream); // CertificateRequest
  178. Protocol.ReceiveRecord (stream); // ServerHelloDone
  179. if (stream.Position != stream.Length)
  180. throw new SecurityNegotiationException (String.Format ("Unexpected SSL negotiation binary: {0} bytes of excess in {1} bytes of the octets", stream.Length - stream.Position, stream.Length));
  181. }
  182. public byte [] ProcessClientKeyExchange ()
  183. {
  184. stream.SetLength (0);
  185. if (mutual)
  186. Protocol.SendRecord (HandshakeType.Certificate);
  187. Protocol.SendRecord (HandshakeType.ClientKeyExchange);
  188. Context.Negotiating.Cipher.ComputeKeys ();
  189. Context.Negotiating.Cipher.InitializeCipher ();
  190. Protocol.SendChangeCipherSpec ();
  191. Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (SecurityProtocolType.Tls);
  192. Protocol.SendRecord (HandshakeType.Finished);
  193. stream.Flush ();
  194. return stream.ToArray ();
  195. }
  196. public void ProcessServerFinished (byte [] raw)
  197. {
  198. stream.SetLength (0);
  199. stream.Write (raw, 0, raw.Length);
  200. stream.Seek (0, SeekOrigin.Begin);
  201. Protocol.ReceiveRecord (stream); // ChangeCipherSpec
  202. Protocol.ReceiveRecord (stream); // ServerFinished
  203. }
  204. public byte [] ProcessApplicationData (byte [] raw)
  205. {
  206. stream.SetLength (0);
  207. stream.Write (raw, 0, raw.Length);
  208. stream.Seek (0, SeekOrigin.Begin);
  209. return Protocol.ReceiveRecord (stream); // ApplicationData
  210. }
  211. }
  212. }