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);
43 public delegate bool CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
45 public delegate X509Certificate CertificateSelectionCallback(
46 X509CertificateCollection clientCertificates,
47 X509Certificate serverCertificate,
49 X509CertificateCollection serverRequestedCertificates);
51 public delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
52 X509Certificate certificate,
57 public class SslClientStream : SslStreamBase
59 #region Internal Events
61 internal event CertificateValidationCallback ServerCertValidation;
62 internal event CertificateSelectionCallback ClientCertSelection;
63 internal event PrivateKeySelectionCallback PrivateKeySelection;
69 // required by HttpsClientStream for proxy support
70 internal Stream InputBuffer
72 get { return base.inputBuffer; }
75 public X509CertificateCollection ClientCertificates
77 get { return this.context.ClientSettings.Certificates; }
80 public X509Certificate SelectedClientCertificate
82 get { return this.context.ClientSettings.ClientCertificate; }
87 #region Callback Properties
89 public CertificateValidationCallback ServerCertValidationDelegate
91 get { return this.ServerCertValidation; }
92 set { this.ServerCertValidation = value; }
95 public CertificateSelectionCallback ClientCertSelectionDelegate
97 get { return this.ClientCertSelection; }
98 set { this.ClientCertSelection = value; }
101 public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
103 get { return this.PrivateKeySelection; }
104 set { this.PrivateKeySelection = value; }
109 public event CertificateValidationCallback2 ServerCertValidation2;
112 public SslClientStream(
117 stream, targetHost, ownsStream,
118 SecurityProtocolType.Default, null)
122 public SslClientStream(
125 X509Certificate clientCertificate)
127 stream, targetHost, false, SecurityProtocolType.Default,
128 new X509CertificateCollection(new X509Certificate[]{clientCertificate}))
132 public SslClientStream(
135 X509CertificateCollection clientCertificates) :
137 stream, targetHost, false, SecurityProtocolType.Default,
142 public SslClientStream(
146 SecurityProtocolType securityProtocolType)
148 stream, targetHost, ownsStream, securityProtocolType,
149 new X509CertificateCollection())
153 public SslClientStream(
157 SecurityProtocolType securityProtocolType,
158 X509CertificateCollection clientCertificates):
159 base(stream, ownsStream)
161 if (targetHost == null || targetHost.Length == 0)
163 throw new ArgumentNullException("targetHost is null or an empty string.");
166 this.context = new ClientContext(
168 securityProtocolType,
172 this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context);
186 #region IDisposable Methods
188 protected override void Dispose(bool disposing)
190 base.Dispose(disposing);
194 this.ServerCertValidation = null;
195 this.ClientCertSelection = null;
196 this.PrivateKeySelection = null;
197 this.ServerCertValidation2 = null;
203 #region Handshake Methods
208 ClientHello -------->
213 <-------- ServerHelloDone
221 Application Data <-------> Application Data
223 Fig. 1 - Message flow for a full handshake
226 internal override IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state)
230 if (this.context.HandshakeState != HandshakeState.None)
232 this.context.Clear();
235 // Obtain supported cipher suites
236 this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
238 // Set handshake state
239 this.context.HandshakeState = HandshakeState.Started;
242 return this.protocol.BeginSendRecord(HandshakeType.ClientHello, callback, state);
244 catch (TlsException ex)
246 this.protocol.SendAlert(ex.Alert);
248 throw new IOException("The authentication or decryption has failed.", ex);
252 this.protocol.SendAlert(AlertDescription.InternalError);
254 throw new IOException("The authentication or decryption has failed.", ex);
258 private void SafeReceiveRecord (Stream s)
260 byte[] record = this.protocol.ReceiveRecord (s);
261 if ((record == null) || (record.Length == 0)) {
262 throw new TlsException (
263 AlertDescription.HandshakeFailiure,
264 "The server stopped the handshake.");
268 internal override void OnNegotiateHandshakeCallback(IAsyncResult asyncResult)
270 this.protocol.EndSendRecord(asyncResult);
272 // Read server response
273 while (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone)
276 SafeReceiveRecord (this.innerStream);
278 // special case for abbreviated handshake where no ServerHelloDone is sent from the server
279 if (this.context.AbbreviatedHandshake && (this.context.LastHandshakeMsg == HandshakeType.ServerHello))
283 // the handshake is much easier if we can reuse a previous session settings
284 if (this.context.AbbreviatedHandshake)
286 ClientSessionCache.SetContextFromCache (this.context);
287 this.context.Negotiating.Cipher.ComputeKeys ();
288 this.context.Negotiating.Cipher.InitializeCipher ();
290 // Send Cipher Spec protocol
291 this.protocol.SendChangeCipherSpec ();
293 // Read record until server finished is received
294 while (this.context.HandshakeState != HandshakeState.Finished)
296 // If all goes well this will process messages:
297 // Change Cipher Spec
299 SafeReceiveRecord (this.innerStream);
302 // Send Finished message
303 this.protocol.SendRecord (HandshakeType.Finished);
307 // Send client certificate if requested
308 // even if the server ask for it it _may_ still be optional
309 bool clientCertificate = this.context.ServerSettings.CertificateRequest;
311 // NOTE: sadly SSL3 and TLS1 differs in how they handle this and
312 // the current design doesn't allow a very cute way to handle
313 // SSL3 alert warning for NoCertificate (41).
314 if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
316 clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
317 (this.context.ClientSettings.Certificates.Count > 0));
318 // this works well with OpenSSL (but only for SSL3)
321 if (clientCertificate)
323 this.protocol.SendRecord(HandshakeType.Certificate);
326 // Send Client Key Exchange
327 this.protocol.SendRecord(HandshakeType.ClientKeyExchange);
329 // Now initialize session cipher with the generated keys
330 this.context.Negotiating.Cipher.InitializeCipher();
332 // Send certificate verify if requested (optional)
333 if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
335 this.protocol.SendRecord(HandshakeType.CertificateVerify);
338 // Send Cipher Spec protocol
339 this.protocol.SendChangeCipherSpec ();
341 // Send Finished message
342 this.protocol.SendRecord (HandshakeType.Finished);
344 // Read record until server finished is received
345 while (this.context.HandshakeState != HandshakeState.Finished) {
346 // If all goes well this will process messages:
347 // Change Cipher Spec
349 SafeReceiveRecord (this.innerStream);
353 // Reset Handshake messages information
354 this.context.HandshakeMessages.Reset ();
357 this.context.ClearKeyInfo();
363 #region Event Methods
365 internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
367 if (this.ClientCertSelection != null)
369 return this.ClientCertSelection(
373 serverRequestedCertificates);
379 internal override bool HaveRemoteValidation2Callback {
380 get { return ServerCertValidation2 != null; }
383 internal override bool OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
385 CertificateValidationCallback2 cb = ServerCertValidation2;
387 return cb (collection);
391 internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
393 if (this.ServerCertValidation != null)
395 return this.ServerCertValidation(certificate, errors);
398 return (errors != null && errors.Length == 0);
401 internal virtual bool RaiseServerCertificateValidation(
402 X509Certificate certificate,
403 int[] certificateErrors)
405 return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
408 internal virtual bool RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
410 return base.RaiseRemoteCertificateValidation2 (collection);
413 internal X509Certificate RaiseClientCertificateSelection(
414 X509CertificateCollection clientCertificates,
415 X509Certificate serverCertificate,
417 X509CertificateCollection serverRequestedCertificates)
419 return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
422 internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
424 if (this.PrivateKeySelection != null)
426 return this.PrivateKeySelection(certificate, targetHost);
432 internal AsymmetricAlgorithm RaisePrivateKeySelection(
433 X509Certificate certificate,
436 return base.RaiseLocalPrivateKeySelection(certificate, targetHost);