1 // Transport Security Layer (TLS)
2 // Copyright (c) 2003-2004 Carlos Guzman Alvarez
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 using System.Collections;
29 using System.Net.Sockets;
30 using System.Security.Cryptography;
31 using System.Security.Cryptography.X509Certificates;
32 using System.Threading;
34 using Mono.Security.Protocol.Tls.Handshake;
36 namespace Mono.Security.Protocol.Tls
40 public delegate bool CertificateValidationCallback(
41 X509Certificate certificate,
42 int[] certificateErrors);
44 public class ValidationResult {
49 public ValidationResult (bool trusted, bool user_denied, int error_code)
51 this.trusted = trusted;
52 this.user_denied = user_denied;
53 this.error_code = error_code;
57 get { return trusted; }
60 public bool UserDenied {
61 get { return user_denied; }
64 public int ErrorCode {
65 get { return error_code; }
74 delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
76 public delegate X509Certificate CertificateSelectionCallback(
77 X509CertificateCollection clientCertificates,
78 X509Certificate serverCertificate,
80 X509CertificateCollection serverRequestedCertificates);
82 public delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
83 X509Certificate certificate,
88 public class SslClientStream : SslStreamBase
90 #region Internal Events
92 internal event CertificateValidationCallback ServerCertValidation;
93 internal event CertificateSelectionCallback ClientCertSelection;
94 internal event PrivateKeySelectionCallback PrivateKeySelection;
100 // required by HttpsClientStream for proxy support
101 internal Stream InputBuffer
103 get { return base.inputBuffer; }
106 public X509CertificateCollection ClientCertificates
108 get { return this.context.ClientSettings.Certificates; }
111 public X509Certificate SelectedClientCertificate
113 get { return this.context.ClientSettings.ClientCertificate; }
118 #region Callback Properties
120 public CertificateValidationCallback ServerCertValidationDelegate
122 get { return this.ServerCertValidation; }
123 set { this.ServerCertValidation = value; }
126 public CertificateSelectionCallback ClientCertSelectionDelegate
128 get { return this.ClientCertSelection; }
129 set { this.ClientCertSelection = value; }
132 public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
134 get { return this.PrivateKeySelection; }
135 set { this.PrivateKeySelection = value; }
141 internal event CertificateValidationCallback2 ServerCertValidation2;
143 public event CertificateValidationCallback2 ServerCertValidation2;
148 public SslClientStream(
153 stream, targetHost, ownsStream,
154 SecurityProtocolType.Default, null)
158 public SslClientStream(
161 X509Certificate clientCertificate)
163 stream, targetHost, false, SecurityProtocolType.Default,
164 new X509CertificateCollection(new X509Certificate[]{clientCertificate}))
168 public SslClientStream(
171 X509CertificateCollection clientCertificates) :
173 stream, targetHost, false, SecurityProtocolType.Default,
178 public SslClientStream(
182 SecurityProtocolType securityProtocolType)
184 stream, targetHost, ownsStream, securityProtocolType,
185 new X509CertificateCollection())
189 public SslClientStream(
193 SecurityProtocolType securityProtocolType,
194 X509CertificateCollection clientCertificates):
195 base(stream, ownsStream)
197 if (targetHost == null || targetHost.Length == 0)
199 throw new ArgumentNullException("targetHost is null or an empty string.");
202 this.context = new ClientContext(
204 securityProtocolType,
208 this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context);
222 #region IDisposable Methods
224 protected override void Dispose(bool disposing)
226 base.Dispose(disposing);
230 this.ServerCertValidation = null;
231 this.ClientCertSelection = null;
232 this.PrivateKeySelection = null;
233 this.ServerCertValidation2 = null;
239 #region Handshake Methods
244 ClientHello -------->
249 <-------- ServerHelloDone
257 Application Data <-------> Application Data
259 Fig. 1 - Message flow for a full handshake
262 internal override IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state)
266 if (this.context.HandshakeState != HandshakeState.None)
268 this.context.Clear();
271 // Obtain supported cipher suites
272 this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
274 // Set handshake state
275 this.context.HandshakeState = HandshakeState.Started;
278 return this.protocol.BeginSendRecord(HandshakeType.ClientHello, callback, state);
280 catch (TlsException ex)
282 this.protocol.SendAlert(ex.Alert);
284 throw new IOException("The authentication or decryption has failed.", ex);
288 this.protocol.SendAlert(AlertDescription.InternalError);
290 throw new IOException("The authentication or decryption has failed.", ex);
294 private void SafeReceiveRecord (Stream s)
296 byte[] record = this.protocol.ReceiveRecord (s);
297 if ((record == null) || (record.Length == 0)) {
298 throw new TlsException (
299 AlertDescription.HandshakeFailiure,
300 "The server stopped the handshake.");
304 internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
306 this.protocol.EndSendRecord(asyncResult);
308 // Read server response
309 while (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone)
312 SafeReceiveRecord (this.innerStream);
314 // special case for abbreviated handshake where no ServerHelloDone is sent from the server
315 if (this.context.AbbreviatedHandshake && (this.context.LastHandshakeMsg == HandshakeType.ServerHello))
319 // the handshake is much easier if we can reuse a previous session settings
320 if (this.context.AbbreviatedHandshake)
322 ClientSessionCache.SetContextFromCache (this.context);
323 this.context.Negotiating.Cipher.ComputeKeys ();
324 this.context.Negotiating.Cipher.InitializeCipher ();
326 // Send Cipher Spec protocol
327 this.protocol.SendChangeCipherSpec ();
329 // Read record until server finished is received
330 while (this.context.HandshakeState != HandshakeState.Finished)
332 // If all goes well this will process messages:
333 // Change Cipher Spec
335 SafeReceiveRecord (this.innerStream);
338 // Send Finished message
339 this.protocol.SendRecord (HandshakeType.Finished);
343 // Send client certificate if requested
344 // even if the server ask for it it _may_ still be optional
345 bool clientCertificate = this.context.ServerSettings.CertificateRequest;
347 // NOTE: sadly SSL3 and TLS1 differs in how they handle this and
348 // the current design doesn't allow a very cute way to handle
349 // SSL3 alert warning for NoCertificate (41).
350 if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
352 clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
353 (this.context.ClientSettings.Certificates.Count > 0));
354 // this works well with OpenSSL (but only for SSL3)
357 if (clientCertificate)
359 this.protocol.SendRecord(HandshakeType.Certificate);
362 // Send Client Key Exchange
363 this.protocol.SendRecord(HandshakeType.ClientKeyExchange);
365 // Now initialize session cipher with the generated keys
366 this.context.Negotiating.Cipher.InitializeCipher();
368 // Send certificate verify if requested (optional)
369 if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
371 this.protocol.SendRecord(HandshakeType.CertificateVerify);
374 // Send Cipher Spec protocol
375 this.protocol.SendChangeCipherSpec ();
377 // Send Finished message
378 this.protocol.SendRecord (HandshakeType.Finished);
380 // Read record until server finished is received
381 while (this.context.HandshakeState != HandshakeState.Finished) {
382 // If all goes well this will process messages:
383 // Change Cipher Spec
385 SafeReceiveRecord (this.innerStream);
389 // Reset Handshake messages information
390 this.context.HandshakeMessages.Reset ();
393 this.context.ClearKeyInfo();
399 #region Event Methods
401 internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
403 if (this.ClientCertSelection != null)
405 return this.ClientCertSelection(
409 serverRequestedCertificates);
415 internal override bool HaveRemoteValidation2Callback {
416 get { return ServerCertValidation2 != null; }
419 internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
421 CertificateValidationCallback2 cb = ServerCertValidation2;
423 return cb (collection);
427 internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
429 if (this.ServerCertValidation != null)
431 return this.ServerCertValidation(certificate, errors);
434 return (errors != null && errors.Length == 0);
437 internal virtual bool RaiseServerCertificateValidation(
438 X509Certificate certificate,
439 int[] certificateErrors)
441 return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
444 internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
446 return base.RaiseRemoteCertificateValidation2 (collection);
449 internal X509Certificate RaiseClientCertificateSelection(
450 X509CertificateCollection clientCertificates,
451 X509Certificate serverCertificate,
453 X509CertificateCollection serverRequestedCertificates)
455 return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
458 internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
460 if (this.PrivateKeySelection != null)
462 return this.PrivateKeySelection(certificate, targetHost);
468 internal AsymmetricAlgorithm RaisePrivateKeySelection(
469 X509Certificate certificate,
472 return base.RaiseLocalPrivateKeySelection(certificate, targetHost);