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;
35 using Mono.Security.Interface;
37 namespace Mono.Security.Protocol.Tls
46 delegate bool CertificateValidationCallback(
47 X509Certificate certificate,
48 int[] certificateErrors);
55 delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
62 delegate X509Certificate CertificateSelectionCallback(
63 X509CertificateCollection clientCertificates,
64 X509Certificate serverCertificate,
66 X509CertificateCollection serverRequestedCertificates);
73 delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
74 X509Certificate certificate,
84 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 private void SafeEndReceiveRecord (IAsyncResult ar, bool ignoreEmpty = false)
256 byte[] record = this.protocol.EndReceiveRecord (ar);
257 if (!ignoreEmpty && ((record == null) || (record.Length == 0))) {
258 throw new TlsException (
259 AlertDescription.HandshakeFailiure,
260 "The server stopped the handshake.");
264 private enum NegotiateState
267 ReceiveClientHelloResponse,
269 ReceiveCipherSpecResponse,
271 ReceiveFinishResponse,
275 private class NegotiateAsyncResult : IAsyncResult
277 private object locker = new object ();
278 private AsyncCallback _userCallback;
279 private object _userState;
280 private Exception _asyncException;
281 private ManualResetEvent handle;
282 private NegotiateState _state;
283 private bool completed;
285 public NegotiateAsyncResult(AsyncCallback userCallback, object userState, NegotiateState state)
287 _userCallback = userCallback;
288 _userState = userState;
292 public NegotiateState State
294 get { return _state; }
295 set { _state = value; }
298 public object AsyncState
300 get { return _userState; }
303 public Exception AsyncException
305 get { return _asyncException; }
308 public bool CompletedWithError
312 return false; // Perhaps throw InvalidOperationExcetion?
314 return null != _asyncException;
318 public WaitHandle AsyncWaitHandle
323 handle = new ManualResetEvent (completed);
330 public bool CompletedSynchronously
332 get { return false; }
335 public bool IsCompleted
344 public void SetComplete(Exception ex)
354 if (_userCallback != null)
355 _userCallback.BeginInvoke (this, null, null);
357 _asyncException = ex;
361 public void SetComplete()
367 internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
369 if (this.context.HandshakeState != HandshakeState.None) {
370 this.context.Clear ();
373 // Obtain supported cipher suites
374 this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (false, context.SecurityProtocol);
376 // Set handshake state
377 this.context.HandshakeState = HandshakeState.Started;
379 NegotiateAsyncResult result = new NegotiateAsyncResult (callback, state, NegotiateState.SentClientHello);
381 // Begin sending the client hello
382 this.protocol.BeginSendRecord (HandshakeType.ClientHello, NegotiateAsyncWorker, result);
387 internal override void EndNegotiateHandshake (IAsyncResult result)
389 NegotiateAsyncResult negotiate = result as NegotiateAsyncResult;
391 if (negotiate == null)
392 throw new ArgumentNullException ();
393 if (!negotiate.IsCompleted)
394 negotiate.AsyncWaitHandle.WaitOne();
395 if (negotiate.CompletedWithError)
396 throw negotiate.AsyncException;
399 private void NegotiateAsyncWorker (IAsyncResult result)
401 NegotiateAsyncResult negotiate = result.AsyncState as NegotiateAsyncResult;
405 switch (negotiate.State)
407 case NegotiateState.SentClientHello:
408 this.protocol.EndSendRecord (result);
410 // we are now ready to ready the receive the hello response.
411 negotiate.State = NegotiateState.ReceiveClientHelloResponse;
413 // Start reading the client hello response
414 this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
417 case NegotiateState.ReceiveClientHelloResponse:
418 this.SafeEndReceiveRecord (result, true);
420 if (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone &&
421 (!this.context.AbbreviatedHandshake || this.context.LastHandshakeMsg != HandshakeType.ServerHello)) {
422 // Read next record (skip empty, e.g. warnings alerts)
423 this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
427 // special case for abbreviated handshake where no ServerHelloDone is sent from the server
428 if (this.context.AbbreviatedHandshake) {
429 ClientSessionCache.SetContextFromCache (this.context);
430 this.context.Negotiating.Cipher.ComputeKeys ();
431 this.context.Negotiating.Cipher.InitializeCipher ();
433 negotiate.State = NegotiateState.SentCipherSpec;
435 // Send Change Cipher Spec message with the current cipher
436 // or as plain text if this is the initial negotiation
437 this.protocol.BeginSendChangeCipherSpec(NegotiateAsyncWorker, negotiate);
439 // Send client certificate if requested
440 // even if the server ask for it it _may_ still be optional
441 bool clientCertificate = this.context.ServerSettings.CertificateRequest;
443 using (var memstream = new MemoryStream())
445 // NOTE: sadly SSL3 and TLS1 differs in how they handle this and
446 // the current design doesn't allow a very cute way to handle
447 // SSL3 alert warning for NoCertificate (41).
448 if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
450 clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
451 (this.context.ClientSettings.Certificates.Count > 0));
452 // this works well with OpenSSL (but only for SSL3)
455 byte[] record = null;
457 if (clientCertificate)
459 record = this.protocol.EncodeHandshakeRecord(HandshakeType.Certificate);
460 memstream.Write(record, 0, record.Length);
463 // Send Client Key Exchange
464 record = this.protocol.EncodeHandshakeRecord(HandshakeType.ClientKeyExchange);
465 memstream.Write(record, 0, record.Length);
467 // Now initialize session cipher with the generated keys
468 this.context.Negotiating.Cipher.InitializeCipher();
470 // Send certificate verify if requested (optional)
471 if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
473 record = this.protocol.EncodeHandshakeRecord(HandshakeType.CertificateVerify);
474 memstream.Write(record, 0, record.Length);
477 // send the chnage cipher spec.
478 this.protocol.SendChangeCipherSpec(memstream);
480 // Send Finished message
481 record = this.protocol.EncodeHandshakeRecord(HandshakeType.Finished);
482 memstream.Write(record, 0, record.Length);
484 negotiate.State = NegotiateState.SentKeyExchange;
486 // send all the records.
487 this.innerStream.BeginWrite (memstream.GetBuffer (), 0, (int)memstream.Length, NegotiateAsyncWorker, negotiate);
492 case NegotiateState.SentKeyExchange:
493 this.innerStream.EndWrite (result);
495 negotiate.State = NegotiateState.ReceiveFinishResponse;
497 this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
501 case NegotiateState.ReceiveFinishResponse:
502 this.SafeEndReceiveRecord (result);
504 // Read record until server finished is received
505 if (this.context.HandshakeState != HandshakeState.Finished) {
506 // If all goes well this will process messages:
507 // Change Cipher Spec
509 this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
512 // Reset Handshake messages information
513 this.context.HandshakeMessages.Reset ();
516 this.context.ClearKeyInfo();
518 negotiate.SetComplete ();
523 case NegotiateState.SentCipherSpec:
524 this.protocol.EndSendChangeCipherSpec (result);
526 negotiate.State = NegotiateState.ReceiveCipherSpecResponse;
528 // Start reading the cipher spec response
529 this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
532 case NegotiateState.ReceiveCipherSpecResponse:
533 this.SafeEndReceiveRecord (result, true);
535 if (this.context.HandshakeState != HandshakeState.Finished)
537 this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
541 negotiate.State = NegotiateState.SentFinished;
542 this.protocol.BeginSendRecord(HandshakeType.Finished, NegotiateAsyncWorker, negotiate);
546 case NegotiateState.SentFinished:
547 this.protocol.EndSendRecord (result);
549 // Reset Handshake messages information
550 this.context.HandshakeMessages.Reset ();
553 this.context.ClearKeyInfo();
555 negotiate.SetComplete ();
560 catch (TlsException ex)
564 this.protocol.SendAlert(ref e);
567 negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex));
572 this.protocol.SendAlert(AlertDescription.InternalError);
575 negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex));
581 #region Event Methods
583 internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
585 if (this.ClientCertSelection != null)
587 return this.ClientCertSelection(
591 serverRequestedCertificates);
597 internal override bool HaveRemoteValidation2Callback {
598 get { return ServerCertValidation2 != null; }
601 internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
603 CertificateValidationCallback2 cb = ServerCertValidation2;
605 return cb (collection);
609 internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
611 if (this.ServerCertValidation != null)
613 return this.ServerCertValidation(certificate, errors);
616 return (errors != null && errors.Length == 0);
619 internal virtual bool RaiseServerCertificateValidation(
620 X509Certificate certificate,
621 int[] certificateErrors)
623 return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
626 internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
628 return base.RaiseRemoteCertificateValidation2 (collection);
631 internal X509Certificate RaiseClientCertificateSelection(
632 X509CertificateCollection clientCertificates,
633 X509Certificate serverCertificate,
635 X509CertificateCollection serverRequestedCertificates)
637 return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
640 internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
642 if (this.PrivateKeySelection != null)
644 return this.PrivateKeySelection(certificate, targetHost);
650 internal AsymmetricAlgorithm RaisePrivateKeySelection(
651 X509Certificate certificate,
654 return base.RaiseLocalPrivateKeySelection(certificate, targetHost);