SslServerStream.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Transport Security Layer (TLS)
  2. // Copyright (c) 2003-2004 Carlos Guzman Alvarez
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining
  5. // a copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to
  9. // permit persons to whom the Software is furnished to do so, subject to
  10. // the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be
  13. // included in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. using System;
  24. using System.Collections;
  25. using System.IO;
  26. using System.Net;
  27. using System.Net.Sockets;
  28. using System.Security.Cryptography;
  29. using System.Security.Cryptography.X509Certificates;
  30. using Mono.Security.Protocol.Tls.Handshake;
  31. namespace Mono.Security.Protocol.Tls
  32. {
  33. public class SslServerStream : SslStreamBase
  34. {
  35. #region Internal Events
  36. internal event CertificateValidationCallback ClientCertValidation;
  37. internal event PrivateKeySelectionCallback PrivateKeySelection;
  38. #endregion
  39. #region Properties
  40. public X509Certificate ClientCertificate
  41. {
  42. get
  43. {
  44. if (this.context.HandshakeState == HandshakeState.Finished)
  45. {
  46. return this.context.ClientSettings.ClientCertificate;
  47. }
  48. return null;
  49. }
  50. }
  51. #endregion
  52. #region Callback Properties
  53. public CertificateValidationCallback ClientCertValidationDelegate
  54. {
  55. get { return this.ClientCertValidation; }
  56. set { this.ClientCertValidation = value; }
  57. }
  58. public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
  59. {
  60. get { return this.PrivateKeySelection; }
  61. set { this.PrivateKeySelection = value; }
  62. }
  63. #endregion
  64. #region Constructors
  65. public SslServerStream(
  66. Stream stream,
  67. X509Certificate serverCertificate) : this(
  68. stream,
  69. serverCertificate,
  70. false,
  71. false,
  72. SecurityProtocolType.Default)
  73. {
  74. }
  75. public SslServerStream(
  76. Stream stream,
  77. X509Certificate serverCertificate,
  78. bool clientCertificateRequired,
  79. bool ownsStream): this(
  80. stream,
  81. serverCertificate,
  82. clientCertificateRequired,
  83. ownsStream,
  84. SecurityProtocolType.Default)
  85. {
  86. }
  87. public SslServerStream(
  88. Stream stream,
  89. X509Certificate serverCertificate,
  90. bool clientCertificateRequired,
  91. bool ownsStream,
  92. SecurityProtocolType securityProtocolType)
  93. : base(stream, ownsStream)
  94. {
  95. this.context = new ServerContext(
  96. this,
  97. securityProtocolType,
  98. serverCertificate,
  99. clientCertificateRequired);
  100. this.protocol = new ServerRecordProtocol(innerStream, (ServerContext)this.context);
  101. }
  102. #endregion
  103. #region Finalizer
  104. ~SslServerStream()
  105. {
  106. this.Dispose(false);
  107. }
  108. #endregion
  109. #region IDisposable Methods
  110. protected override void Dispose(bool disposing)
  111. {
  112. base.Dispose(disposing);
  113. if (disposing)
  114. {
  115. this.ClientCertValidation = null;
  116. this.PrivateKeySelection = null;
  117. }
  118. }
  119. #endregion
  120. #region Handsake Methods
  121. /*
  122. Client Server
  123. ClientHello -------->
  124. ServerHello
  125. Certificate*
  126. ServerKeyExchange*
  127. CertificateRequest*
  128. <-------- ServerHelloDone
  129. Certificate*
  130. ClientKeyExchange
  131. CertificateVerify*
  132. [ChangeCipherSpec]
  133. Finished -------->
  134. [ChangeCipherSpec]
  135. <-------- Finished
  136. Application Data <-------> Application Data
  137. Fig. 1 - Message flow for a full handshake
  138. */
  139. internal override IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state)
  140. {
  141. // Reset the context if needed
  142. if (this.context.HandshakeState != HandshakeState.None)
  143. {
  144. this.context.Clear();
  145. }
  146. // Obtain supported cipher suites
  147. this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
  148. // Set handshake state
  149. this.context.HandshakeState = HandshakeState.Started;
  150. // Receive Client Hello message
  151. return this.protocol.BeginReceiveRecord(this.innerStream, callback, state);
  152. }
  153. internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
  154. {
  155. // Receive Client Hello message and ignore it
  156. this.protocol.EndReceiveRecord(asyncResult);
  157. // If received message is not an ClientHello send a
  158. // Fatal Alert
  159. if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
  160. {
  161. this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
  162. }
  163. // Send ServerHello message
  164. this.protocol.SendRecord(HandshakeType.ServerHello);
  165. // Send ServerCertificate message
  166. this.protocol.SendRecord(HandshakeType.Certificate);
  167. // If the negotiated cipher is a KeyEx cipher send ServerKeyExchange
  168. if (this.context.Negotiating.Cipher.IsExportable)
  169. {
  170. this.protocol.SendRecord(HandshakeType.ServerKeyExchange);
  171. }
  172. bool certRequested = false;
  173. // If the negotiated cipher is a KeyEx cipher or
  174. // the client certificate is required send the CertificateRequest message
  175. if (this.context.Negotiating.Cipher.IsExportable ||
  176. ((ServerContext)this.context).ClientCertificateRequired)
  177. {
  178. this.protocol.SendRecord(HandshakeType.CertificateRequest);
  179. certRequested = true;
  180. }
  181. // Send ServerHelloDone message
  182. this.protocol.SendRecord(HandshakeType.ServerHelloDone);
  183. // Receive client response, until the Client Finished message
  184. // is received. IE can be interrupted at this stage and never
  185. // complete the handshake
  186. while (this.context.LastHandshakeMsg != HandshakeType.Finished)
  187. {
  188. byte[] record = this.protocol.ReceiveRecord(this.innerStream);
  189. if ((record == null) || (record.Length == 0))
  190. {
  191. throw new TlsException(
  192. AlertDescription.HandshakeFailiure,
  193. "The client stopped the handshake.");
  194. }
  195. }
  196. if (certRequested && (this.context.ClientSettings.ClientCertificate == null))
  197. {
  198. // we asked for a certificate but didn't receive one
  199. // e.g. wget for SSL3
  200. if (!RaiseClientCertificateValidation(null, new int[0]))
  201. {
  202. throw new TlsException(
  203. AlertDescription.BadCertificate,
  204. "No certificate received from client.");
  205. }
  206. }
  207. // Send ChangeCipherSpec and ServerFinished messages
  208. this.protocol.SendChangeCipherSpec();
  209. this.protocol.SendRecord (HandshakeType.Finished);
  210. // The handshake is finished
  211. this.context.HandshakeState = HandshakeState.Finished;
  212. // Reset Handshake messages information
  213. this.context.HandshakeMessages.Reset ();
  214. // Clear Key Info
  215. this.context.ClearKeyInfo();
  216. }
  217. #endregion
  218. #region Event Methods
  219. internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
  220. {
  221. throw new NotSupportedException();
  222. }
  223. internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
  224. {
  225. if (this.ClientCertValidation != null)
  226. {
  227. return this.ClientCertValidation(certificate, errors);
  228. }
  229. return (errors != null && errors.Length == 0);
  230. }
  231. internal bool RaiseClientCertificateValidation(
  232. X509Certificate certificate,
  233. int[] certificateErrors)
  234. {
  235. return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
  236. }
  237. internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
  238. {
  239. if (this.PrivateKeySelection != null)
  240. {
  241. return this.PrivateKeySelection(certificate, targetHost);
  242. }
  243. return null;
  244. }
  245. internal AsymmetricAlgorithm RaisePrivateKeySelection(
  246. X509Certificate certificate,
  247. string targetHost)
  248. {
  249. return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
  250. }
  251. #endregion
  252. }
  253. }