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; }
70 delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
72 public delegate X509Certificate CertificateSelectionCallback(
73 X509CertificateCollection clientCertificates,
74 X509Certificate serverCertificate,
76 X509CertificateCollection serverRequestedCertificates);
78 public delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
79 X509Certificate certificate,
84 public class SslClientStream : SslStreamBase
86 #region Internal Events
88 internal event CertificateValidationCallback ServerCertValidation;
89 internal event CertificateSelectionCallback ClientCertSelection;
90 internal event PrivateKeySelectionCallback PrivateKeySelection;
96 // required by HttpsClientStream for proxy support
97 internal Stream InputBuffer
99 get { return base.inputBuffer; }
102 public X509CertificateCollection ClientCertificates
104 get { return this.context.ClientSettings.Certificates; }
107 public X509Certificate SelectedClientCertificate
109 get { return this.context.ClientSettings.ClientCertificate; }
114 #region Callback Properties
116 public CertificateValidationCallback ServerCertValidationDelegate
118 get { return this.ServerCertValidation; }
119 set { this.ServerCertValidation = value; }
122 public CertificateSelectionCallback ClientCertSelectionDelegate
124 get { return this.ClientCertSelection; }
125 set { this.ClientCertSelection = value; }
128 public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
130 get { return this.PrivateKeySelection; }
131 set { this.PrivateKeySelection = value; }
136 public event CertificateValidationCallback2 ServerCertValidation2;
140 public SslClientStream(
145 stream, targetHost, ownsStream,
146 SecurityProtocolType.Default, null)
150 public SslClientStream(
153 X509Certificate clientCertificate)
155 stream, targetHost, false, SecurityProtocolType.Default,
156 new X509CertificateCollection(new X509Certificate[]{clientCertificate}))
160 public SslClientStream(
163 X509CertificateCollection clientCertificates) :
165 stream, targetHost, false, SecurityProtocolType.Default,
170 public SslClientStream(
174 SecurityProtocolType securityProtocolType)
176 stream, targetHost, ownsStream, securityProtocolType,
177 new X509CertificateCollection())
181 public SslClientStream(
185 SecurityProtocolType securityProtocolType,
186 X509CertificateCollection clientCertificates):
187 base(stream, ownsStream)
189 if (targetHost == null || targetHost.Length == 0)
191 throw new ArgumentNullException("targetHost is null or an empty string.");
194 this.context = new ClientContext(
196 securityProtocolType,
200 this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context);
214 #region IDisposable Methods
216 protected override void Dispose(bool disposing)
218 base.Dispose(disposing);
222 this.ServerCertValidation = null;
223 this.ClientCertSelection = null;
224 this.PrivateKeySelection = null;
225 this.ServerCertValidation2 = null;
231 #region Handshake Methods
236 ClientHello -------->
241 <-------- ServerHelloDone
249 Application Data <-------> Application Data
251 Fig. 1 - Message flow for a full handshake
254 internal override IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state)
258 if (this.context.HandshakeState != HandshakeState.None)
260 this.context.Clear();
263 // Obtain supported cipher suites
264 this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
266 // Set handshake state
267 this.context.HandshakeState = HandshakeState.Started;
270 return this.protocol.BeginSendRecord(HandshakeType.ClientHello, callback, state);
272 catch (TlsException ex)
274 this.protocol.SendAlert(ex.Alert);
276 throw new IOException("The authentication or decryption has failed.", ex);
280 this.protocol.SendAlert(AlertDescription.InternalError);
282 throw new IOException("The authentication or decryption has failed.", ex);
286 private void SafeReceiveRecord (Stream s, bool ignoreEmpty = false)
288 byte[] record = this.protocol.ReceiveRecord (s);
289 if (!ignoreEmpty && ((record == null) || (record.Length == 0))) {
290 throw new TlsException (
291 AlertDescription.HandshakeFailiure,
292 "The server stopped the handshake.");
296 internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
298 this.protocol.EndSendRecord(asyncResult);
300 // Read server response
301 while (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone)
303 // Read next record (skip empty, e.g. warnings alerts)
304 SafeReceiveRecord (this.innerStream, true);
306 // special case for abbreviated handshake where no ServerHelloDone is sent from the server
307 if (this.context.AbbreviatedHandshake && (this.context.LastHandshakeMsg == HandshakeType.ServerHello))
311 // the handshake is much easier if we can reuse a previous session settings
312 if (this.context.AbbreviatedHandshake)
314 ClientSessionCache.SetContextFromCache (this.context);
315 this.context.Negotiating.Cipher.ComputeKeys ();
316 this.context.Negotiating.Cipher.InitializeCipher ();
318 // Send Cipher Spec protocol
319 this.protocol.SendChangeCipherSpec ();
321 // Read record until server finished is received
322 while (this.context.HandshakeState != HandshakeState.Finished)
324 // If all goes well this will process messages:
325 // Change Cipher Spec
327 SafeReceiveRecord (this.innerStream);
330 // Send Finished message
331 this.protocol.SendRecord (HandshakeType.Finished);
335 // Send client certificate if requested
336 // even if the server ask for it it _may_ still be optional
337 bool clientCertificate = this.context.ServerSettings.CertificateRequest;
339 // NOTE: sadly SSL3 and TLS1 differs in how they handle this and
340 // the current design doesn't allow a very cute way to handle
341 // SSL3 alert warning for NoCertificate (41).
342 if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
344 clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
345 (this.context.ClientSettings.Certificates.Count > 0));
346 // this works well with OpenSSL (but only for SSL3)
349 if (clientCertificate)
351 this.protocol.SendRecord(HandshakeType.Certificate);
354 // Send Client Key Exchange
355 this.protocol.SendRecord(HandshakeType.ClientKeyExchange);
357 // Now initialize session cipher with the generated keys
358 this.context.Negotiating.Cipher.InitializeCipher();
360 // Send certificate verify if requested (optional)
361 if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
363 this.protocol.SendRecord(HandshakeType.CertificateVerify);
366 // Send Cipher Spec protocol
367 this.protocol.SendChangeCipherSpec ();
369 // Send Finished message
370 this.protocol.SendRecord (HandshakeType.Finished);
372 // Read record until server finished is received
373 while (this.context.HandshakeState != HandshakeState.Finished) {
374 // If all goes well this will process messages:
375 // Change Cipher Spec
377 SafeReceiveRecord (this.innerStream);
381 // Reset Handshake messages information
382 this.context.HandshakeMessages.Reset ();
385 this.context.ClearKeyInfo();
391 #region Event Methods
393 internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
395 if (this.ClientCertSelection != null)
397 return this.ClientCertSelection(
401 serverRequestedCertificates);
407 internal override bool HaveRemoteValidation2Callback {
408 get { return ServerCertValidation2 != null; }
411 internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
413 CertificateValidationCallback2 cb = ServerCertValidation2;
415 return cb (collection);
419 internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
421 if (this.ServerCertValidation != null)
423 return this.ServerCertValidation(certificate, errors);
426 return (errors != null && errors.Length == 0);
429 internal virtual bool RaiseServerCertificateValidation(
430 X509Certificate certificate,
431 int[] certificateErrors)
433 return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
436 internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
438 return base.RaiseRemoteCertificateValidation2 (collection);
441 internal X509Certificate RaiseClientCertificateSelection(
442 X509CertificateCollection clientCertificates,
443 X509Certificate serverCertificate,
445 X509CertificateCollection serverRequestedCertificates)
447 return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
450 internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
452 if (this.PrivateKeySelection != null)
454 return this.PrivateKeySelection(certificate, targetHost);
460 internal AsymmetricAlgorithm RaisePrivateKeySelection(
461 X509Certificate certificate,
464 return base.RaiseLocalPrivateKeySelection(certificate, targetHost);