SslServerStream.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. public event CertificateValidationCallback2 ClientCertValidation2;
  65. #region Constructors
  66. public SslServerStream(
  67. Stream stream,
  68. X509Certificate serverCertificate) : this(
  69. stream,
  70. serverCertificate,
  71. false,
  72. false,
  73. SecurityProtocolType.Default)
  74. {
  75. }
  76. public SslServerStream(
  77. Stream stream,
  78. X509Certificate serverCertificate,
  79. bool clientCertificateRequired,
  80. bool ownsStream): this(
  81. stream,
  82. serverCertificate,
  83. clientCertificateRequired,
  84. ownsStream,
  85. SecurityProtocolType.Default)
  86. {
  87. }
  88. public SslServerStream(
  89. Stream stream,
  90. X509Certificate serverCertificate,
  91. bool clientCertificateRequired,
  92. bool requestClientCertificate,
  93. bool ownsStream)
  94. : this (stream, serverCertificate, clientCertificateRequired, requestClientCertificate, ownsStream, SecurityProtocolType.Default)
  95. {
  96. }
  97. public SslServerStream(
  98. Stream stream,
  99. X509Certificate serverCertificate,
  100. bool clientCertificateRequired,
  101. bool ownsStream,
  102. SecurityProtocolType securityProtocolType)
  103. : this (stream, serverCertificate, clientCertificateRequired, false, ownsStream, securityProtocolType)
  104. {
  105. }
  106. public SslServerStream(
  107. Stream stream,
  108. X509Certificate serverCertificate,
  109. bool clientCertificateRequired,
  110. bool requestClientCertificate,
  111. bool ownsStream,
  112. SecurityProtocolType securityProtocolType)
  113. : base(stream, ownsStream)
  114. {
  115. this.context = new ServerContext(
  116. this,
  117. securityProtocolType,
  118. serverCertificate,
  119. clientCertificateRequired,
  120. requestClientCertificate);
  121. this.protocol = new ServerRecordProtocol(innerStream, (ServerContext)this.context);
  122. }
  123. #endregion
  124. #region Finalizer
  125. ~SslServerStream()
  126. {
  127. this.Dispose(false);
  128. }
  129. #endregion
  130. #region IDisposable Methods
  131. protected override void Dispose(bool disposing)
  132. {
  133. base.Dispose(disposing);
  134. if (disposing)
  135. {
  136. this.ClientCertValidation = null;
  137. this.PrivateKeySelection = null;
  138. }
  139. }
  140. #endregion
  141. #region Handsake Methods
  142. /*
  143. Client Server
  144. ClientHello -------->
  145. ServerHello
  146. Certificate*
  147. ServerKeyExchange*
  148. CertificateRequest*
  149. <-------- ServerHelloDone
  150. Certificate*
  151. ClientKeyExchange
  152. CertificateVerify*
  153. [ChangeCipherSpec]
  154. Finished -------->
  155. [ChangeCipherSpec]
  156. <-------- Finished
  157. Application Data <-------> Application Data
  158. Fig. 1 - Message flow for a full handshake
  159. */
  160. internal override IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state)
  161. {
  162. // Reset the context if needed
  163. if (this.context.HandshakeState != HandshakeState.None)
  164. {
  165. this.context.Clear();
  166. }
  167. // Obtain supported cipher suites
  168. this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
  169. // Set handshake state
  170. this.context.HandshakeState = HandshakeState.Started;
  171. // Receive Client Hello message
  172. return this.protocol.BeginReceiveRecord(this.innerStream, callback, state);
  173. }
  174. internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
  175. {
  176. // Receive Client Hello message and ignore it
  177. this.protocol.EndReceiveRecord(asyncResult);
  178. // If received message is not an ClientHello send a
  179. // Fatal Alert
  180. if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
  181. {
  182. this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
  183. }
  184. // Send ServerHello message
  185. this.protocol.SendRecord(HandshakeType.ServerHello);
  186. // Send ServerCertificate message
  187. this.protocol.SendRecord(HandshakeType.Certificate);
  188. // If the negotiated cipher is a KeyEx cipher send ServerKeyExchange
  189. if (this.context.Negotiating.Cipher.IsExportable)
  190. {
  191. this.protocol.SendRecord(HandshakeType.ServerKeyExchange);
  192. }
  193. bool certRequested = false;
  194. // If the negotiated cipher is a KeyEx cipher or
  195. // the client certificate is required send the CertificateRequest message
  196. if (this.context.Negotiating.Cipher.IsExportable ||
  197. ((ServerContext)this.context).ClientCertificateRequired ||
  198. ((ServerContext)this.context).RequestClientCertificate)
  199. {
  200. this.protocol.SendRecord(HandshakeType.CertificateRequest);
  201. certRequested = true;
  202. }
  203. // Send ServerHelloDone message
  204. this.protocol.SendRecord(HandshakeType.ServerHelloDone);
  205. // Receive client response, until the Client Finished message
  206. // is received. IE can be interrupted at this stage and never
  207. // complete the handshake
  208. while (this.context.LastHandshakeMsg != HandshakeType.Finished)
  209. {
  210. byte[] record = this.protocol.ReceiveRecord(this.innerStream);
  211. if ((record == null) || (record.Length == 0))
  212. {
  213. throw new TlsException(
  214. AlertDescription.HandshakeFailiure,
  215. "The client stopped the handshake.");
  216. }
  217. }
  218. if (certRequested) {
  219. X509Certificate client_cert = this.context.ClientSettings.ClientCertificate;
  220. if (client_cert == null && ((ServerContext)this.context).ClientCertificateRequired)
  221. throw new TlsException (AlertDescription.BadCertificate, "No certificate received from client.");
  222. if (!RaiseClientCertificateValidation (client_cert, new int[0]))
  223. throw new TlsException (AlertDescription.BadCertificate, "Client certificate not accepted.");
  224. }
  225. // Send ChangeCipherSpec and ServerFinished messages
  226. this.protocol.SendChangeCipherSpec();
  227. this.protocol.SendRecord (HandshakeType.Finished);
  228. // The handshake is finished
  229. this.context.HandshakeState = HandshakeState.Finished;
  230. // Reset Handshake messages information
  231. this.context.HandshakeMessages.Reset ();
  232. // Clear Key Info
  233. this.context.ClearKeyInfo();
  234. }
  235. #endregion
  236. #region Event Methods
  237. internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
  238. {
  239. throw new NotSupportedException();
  240. }
  241. internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
  242. {
  243. if (this.ClientCertValidation != null)
  244. {
  245. return this.ClientCertValidation(certificate, errors);
  246. }
  247. return (errors != null && errors.Length == 0);
  248. }
  249. internal override bool HaveRemoteValidation2Callback {
  250. get { return ClientCertValidation2 != null; }
  251. }
  252. internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
  253. {
  254. CertificateValidationCallback2 cb = ClientCertValidation2;
  255. if (cb != null)
  256. return cb (collection);
  257. return null;
  258. }
  259. internal bool RaiseClientCertificateValidation(
  260. X509Certificate certificate,
  261. int[] certificateErrors)
  262. {
  263. return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
  264. }
  265. internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
  266. {
  267. if (this.PrivateKeySelection != null)
  268. {
  269. return this.PrivateKeySelection(certificate, targetHost);
  270. }
  271. return null;
  272. }
  273. internal AsymmetricAlgorithm RaisePrivateKeySelection(
  274. X509Certificate certificate,
  275. string targetHost)
  276. {
  277. return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
  278. }
  279. #endregion
  280. }
  281. }