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 namespace Mono.Security.Protocol.Tls
36 public abstract class SslStreamBase: Stream, IDisposable
38 private delegate void AsyncHandshakeDelegate(InternalAsyncResult asyncResult, bool fromWrite);
42 internal Stream innerStream;
43 internal MemoryStream inputBuffer;
44 internal Context context;
45 internal RecordProtocol protocol;
46 internal bool ownsStream;
47 private volatile bool disposed;
48 private bool checkCertRevocationStatus;
49 private object negotiate;
52 private ManualResetEvent negotiationComplete;
59 protected SslStreamBase(
65 throw new ArgumentNullException("stream is null.");
67 if (!stream.CanRead || !stream.CanWrite)
69 throw new ArgumentNullException("stream is not both readable and writable.");
72 this.inputBuffer = new MemoryStream();
73 this.innerStream = stream;
74 this.ownsStream = ownsStream;
75 this.negotiate = new object();
76 this.read = new object();
77 this.write = new object();
78 this.negotiationComplete = new ManualResetEvent(false);
84 private void AsyncHandshakeCallback(IAsyncResult asyncResult)
86 InternalAsyncResult internalResult = asyncResult.AsyncState as InternalAsyncResult;
92 this.OnNegotiateHandshakeCallback(asyncResult);
94 catch (TlsException ex)
96 this.protocol.SendAlert(ex.Alert);
98 throw new IOException("The authentication or decryption has failed.", ex);
102 this.protocol.SendAlert(AlertDescription.InternalError);
104 throw new IOException("The authentication or decryption has failed.", ex);
107 negotiationComplete.Set();
109 if (internalResult.ProceedAfterHandshake)
111 //kick off the read or write process (whichever called us) after the handshake is complete
112 if (internalResult.FromWrite)
114 InternalBeginWrite(internalResult);
118 InternalBeginRead(internalResult);
123 negotiationComplete.Set();
124 internalResult.SetComplete();
130 negotiationComplete.Set();
131 internalResult.SetComplete(ex);
135 internal bool MightNeedHandshake
139 if (this.context.HandshakeState == HandshakeState.Finished)
145 lock (this.negotiate)
147 return (this.context.HandshakeState != HandshakeState.Finished);
153 internal void NegotiateHandshake()
155 if (this.MightNeedHandshake)
157 InternalAsyncResult ar = new InternalAsyncResult(null, null, null, 0, 0, false, false);
159 //if something already started negotiation, wait for it.
160 //otherwise end it ourselves.
161 if (!BeginNegotiateHandshake(ar))
163 this.negotiationComplete.WaitOne();
167 this.EndNegotiateHandshake(ar);
174 #region Abstracts/Virtuals
176 internal abstract IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state);
177 internal abstract void OnNegotiateHandshakeCallback(IAsyncResult asyncResult);
179 internal abstract X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates,
180 X509Certificate serverCertificate,
182 X509CertificateCollection serverRequestedCertificates);
184 internal abstract bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors);
186 internal abstract AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost);
190 #region Event Methods
192 internal X509Certificate RaiseLocalCertificateSelection(X509CertificateCollection certificates,
193 X509Certificate remoteCertificate,
195 X509CertificateCollection requestedCertificates)
197 return OnLocalCertificateSelection(certificates, remoteCertificate, targetHost, requestedCertificates);
200 internal bool RaiseRemoteCertificateValidation(X509Certificate certificate, int[] errors)
202 return OnRemoteCertificateValidation(certificate, errors);
205 internal AsymmetricAlgorithm RaiseLocalPrivateKeySelection(
206 X509Certificate certificate,
209 return OnLocalPrivateKeySelection(certificate, targetHost);
213 #region Security Properties
215 public bool CheckCertRevocationStatus
217 get { return this.checkCertRevocationStatus; }
218 set { this.checkCertRevocationStatus = value; }
221 public CipherAlgorithmType CipherAlgorithm
225 if (this.context.HandshakeState == HandshakeState.Finished)
227 return this.context.Cipher.CipherAlgorithmType;
230 return CipherAlgorithmType.None;
234 public int CipherStrength
238 if (this.context.HandshakeState == HandshakeState.Finished)
240 return this.context.Cipher.EffectiveKeyBits;
247 public HashAlgorithmType HashAlgorithm
251 if (this.context.HandshakeState == HandshakeState.Finished)
253 return this.context.Cipher.HashAlgorithmType;
256 return HashAlgorithmType.None;
260 public int HashStrength
264 if (this.context.HandshakeState == HandshakeState.Finished)
266 return this.context.Cipher.HashSize * 8;
273 public int KeyExchangeStrength
277 if (this.context.HandshakeState == HandshakeState.Finished)
279 return this.context.ServerSettings.Certificates[0].RSA.KeySize;
286 public ExchangeAlgorithmType KeyExchangeAlgorithm
290 if (this.context.HandshakeState == HandshakeState.Finished)
292 return this.context.Cipher.ExchangeAlgorithmType;
295 return ExchangeAlgorithmType.None;
299 public SecurityProtocolType SecurityProtocol
303 if (this.context.HandshakeState == HandshakeState.Finished)
305 return this.context.SecurityProtocol;
312 public X509Certificate ServerCertificate
316 if (this.context.HandshakeState == HandshakeState.Finished)
318 if (this.context.ServerSettings.Certificates != null &&
319 this.context.ServerSettings.Certificates.Count > 0)
321 return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData);
329 // this is used by Mono's certmgr tool to download certificates
330 internal Mono.Security.X509.X509CertificateCollection ServerCertificates
332 get { return context.ServerSettings.Certificates; }
337 #region Internal Async Result/State Class
339 private class InternalAsyncResult : IAsyncResult
341 private AsyncCallback _userCallback;
342 private object _userState;
343 private Exception _asyncException;
344 private ManualResetEvent _complete;
345 private int _bytesRead;
346 private bool _fromWrite;
347 private bool _proceedAfterHandshake;
349 private byte[] _buffer;
353 public InternalAsyncResult(AsyncCallback userCallback, object userState, byte[] buffer, int offset, int count, bool fromWrite, bool proceedAfterHandshake)
355 _userCallback = userCallback;
356 _userState = userState;
357 _complete = new ManualResetEvent(false);
361 _fromWrite = fromWrite;
362 _proceedAfterHandshake = proceedAfterHandshake;
365 public bool ProceedAfterHandshake
367 get { return _proceedAfterHandshake; }
370 public bool FromWrite
372 get { return _fromWrite; }
377 get { return _buffer; }
382 get { return _offset; }
387 get { return _count; }
392 get { return _bytesRead; }
395 public object AsyncState
397 get { return _userState; }
400 public Exception AsyncException
402 get { return _asyncException; }
405 public bool CompletedWithError
407 get { return null != _asyncException; }
410 public WaitHandle AsyncWaitHandle
412 get { return _complete; }
415 public bool CompletedSynchronously
417 get { return false; }
420 public bool IsCompleted
422 get { return _complete.WaitOne(0, false); }
425 private void SetComplete(Exception ex, int bytesRead)
427 if (this.IsCompleted)
432 if (this.IsCompleted)
435 _asyncException = ex;
436 _bytesRead = bytesRead;
440 if (null != _userCallback)
441 _userCallback (this);
445 public void SetComplete(Exception ex)
450 public void SetComplete(int bytesRead)
452 SetComplete(null, bytesRead);
455 public void SetComplete()
457 SetComplete(null, 0);
462 #region Stream Overrides and Async Stream Operations
464 private bool BeginNegotiateHandshake(InternalAsyncResult asyncResult)
468 lock (this.negotiate)
470 if (this.context.HandshakeState == HandshakeState.None)
472 this.OnBeginNegotiateHandshake(new AsyncCallback(AsyncHandshakeCallback), asyncResult);
482 catch (TlsException ex)
484 this.negotiationComplete.Set();
485 this.protocol.SendAlert(ex.Alert);
487 throw new IOException("The authentication or decryption has failed.", ex);
491 this.negotiationComplete.Set();
492 this.protocol.SendAlert(AlertDescription.InternalError);
494 throw new IOException("The authentication or decryption has failed.", ex);
498 private void EndNegotiateHandshake(InternalAsyncResult asyncResult)
500 asyncResult.AsyncWaitHandle.WaitOne();
502 if (asyncResult.CompletedWithError)
504 throw asyncResult.AsyncException;
508 public override IAsyncResult BeginRead(
512 AsyncCallback callback,
515 this.checkDisposed();
519 throw new ArgumentNullException("buffer is a null reference.");
523 throw new ArgumentOutOfRangeException("offset is less than 0.");
525 if (offset > buffer.Length)
527 throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
531 throw new ArgumentOutOfRangeException("count is less than 0.");
533 if (count > (buffer.Length - offset))
535 throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
538 InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, false, true);
540 if (this.MightNeedHandshake)
542 if (! BeginNegotiateHandshake(asyncResult))
544 //we made it down here so the handshake was not started.
545 //another thread must have started it in the mean time.
546 //wait for it to complete and then perform our original operation
547 this.negotiationComplete.WaitOne();
549 InternalBeginRead(asyncResult);
554 InternalBeginRead(asyncResult);
560 private void InternalBeginRead(InternalAsyncResult asyncResult)
568 // If actual buffer is fully read, reset it
569 bool shouldReset = this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0;
571 // If the buffer isn't fully read, but does have data, we need to immediately
572 // read the info from the buffer and let the user know that they have more data.
573 bool shouldReadImmediately = (this.inputBuffer.Length > 0) && (asyncResult.Count > 0);
579 else if (shouldReadImmediately)
581 preReadSize = this.inputBuffer.Read(asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
585 // This is explicitly done outside the synclock to avoid
586 // any potential deadlocks in the delegate call.
589 asyncResult.SetComplete(preReadSize);
591 else if (!this.context.ConnectionEnd)
593 // bigger than max record length for SSL/TLS
594 byte[] recbuf = new byte[16384];
596 // this will read data from the network until we have (at least) one
597 // record to send back to the caller
598 this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
599 new AsyncCallback(InternalReadCallback), new object[] { recbuf, asyncResult });
603 // We're done with the connection so we need to let the caller know with 0 bytes read
604 asyncResult.SetComplete(0);
607 catch (TlsException ex)
609 this.protocol.SendAlert(ex.Alert);
611 throw new IOException("The authentication or decryption has failed.", ex);
615 throw new IOException("IO exception during read.", ex);
620 private MemoryStream recordStream = new MemoryStream();
622 // read encrypted data until we have enough to decrypt (at least) one
623 // record and return are the records (may be more than one) we have
624 private void InternalReadCallback(IAsyncResult result)
629 object[] state = (object[])result.AsyncState;
630 byte[] recbuf = (byte[])state[0];
631 InternalAsyncResult internalResult = (InternalAsyncResult)state[1];
635 int n = innerStream.EndRead(result);
638 // Add the just received data to the waiting data
639 recordStream.Write(recbuf, 0, n);
643 // 0 length data means this read operation is done (lost connection in the case of a network stream).
644 internalResult.SetComplete(0);
648 bool dataToReturn = false;
649 long pos = recordStream.Position;
651 recordStream.Position = 0;
652 byte[] record = null;
654 // don't try to decode record unless we have at least 5 bytes
655 // i.e. type (1), protocol (2) and length (2)
656 if (recordStream.Length >= 5)
658 record = this.protocol.ReceiveRecord(recordStream);
661 // a record of 0 length is valid (and there may be more record after it)
662 while (record != null)
664 // we probably received more stuff after the record, and we must keep it!
665 long remainder = recordStream.Length - recordStream.Position;
666 byte[] outofrecord = null;
669 outofrecord = new byte[remainder];
670 recordStream.Read(outofrecord, 0, outofrecord.Length);
675 long position = this.inputBuffer.Position;
677 if (record.Length > 0)
679 // Write new data to the inputBuffer
680 this.inputBuffer.Seek(0, SeekOrigin.End);
681 this.inputBuffer.Write(record, 0, record.Length);
683 // Restore buffer position
684 this.inputBuffer.Seek(position, SeekOrigin.Begin);
689 recordStream.SetLength(0);
694 recordStream.Write(outofrecord, 0, outofrecord.Length);
695 // type (1), protocol (2) and length (2)
696 if (recordStream.Length >= 5)
698 // try to see if another record is available
699 recordStream.Position = 0;
700 record = this.protocol.ReceiveRecord(recordStream);
702 pos = recordStream.Length;
711 if (!dataToReturn && (n > 0))
713 // there is no record to return to caller and (possibly) more data waiting
714 // so continue reading from network (and appending to stream)
715 recordStream.Position = recordStream.Length;
716 this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
717 new AsyncCallback(InternalReadCallback), state);
721 // we have record(s) to return -or- no more available to read from network
722 // reset position for further reading
723 recordStream.Position = pos;
728 bytesRead = this.inputBuffer.Read(internalResult.Buffer, internalResult.Offset, internalResult.Count);
731 internalResult.SetComplete(bytesRead);
736 internalResult.SetComplete(ex);
741 private void InternalBeginWrite(InternalAsyncResult asyncResult)
745 // Send the buffer as a TLS record
749 byte[] record = this.protocol.EncodeRecord(
750 ContentType.ApplicationData, asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
752 this.innerStream.BeginWrite(
753 record, 0, record.Length, new AsyncCallback(InternalWriteCallback), asyncResult);
756 catch (TlsException ex)
758 this.protocol.SendAlert(ex.Alert);
761 throw new IOException("The authentication or decryption has failed.", ex);
765 throw new IOException("IO exception during Write.", ex);
769 private void InternalWriteCallback(IAsyncResult ar)
774 InternalAsyncResult internalResult = (InternalAsyncResult)ar.AsyncState;
778 this.innerStream.EndWrite(ar);
779 internalResult.SetComplete(0);
783 internalResult.SetComplete(ex);
787 public override IAsyncResult BeginWrite(
791 AsyncCallback callback,
794 this.checkDisposed();
798 throw new ArgumentNullException("buffer is a null reference.");
802 throw new ArgumentOutOfRangeException("offset is less than 0.");
804 if (offset > buffer.Length)
806 throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
810 throw new ArgumentOutOfRangeException("count is less than 0.");
812 if (count > (buffer.Length - offset))
814 throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
818 InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, true, true);
820 if (this.MightNeedHandshake)
822 if (! BeginNegotiateHandshake(asyncResult))
824 //we made it down here so the handshake was not started.
825 //another thread must have started it in the mean time.
826 //wait for it to complete and then perform our original operation
827 this.negotiationComplete.WaitOne();
829 InternalBeginWrite(asyncResult);
834 InternalBeginWrite(asyncResult);
840 public override int EndRead(IAsyncResult asyncResult)
842 this.checkDisposed();
844 InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
846 // Always wait until the read is complete
847 internalResult.AsyncWaitHandle.WaitOne();
849 if (internalResult == null)
851 throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
854 if (internalResult.CompletedWithError)
856 throw internalResult.AsyncException;
859 return internalResult.BytesRead;
862 public override void EndWrite(IAsyncResult asyncResult)
864 this.checkDisposed();
866 InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
868 internalResult.AsyncWaitHandle.WaitOne();
870 if (asyncResult == null)
872 throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginWrite.");
875 if (internalResult.CompletedWithError)
877 throw internalResult.AsyncException;
881 public override void Close()
883 ((IDisposable)this).Dispose();
886 public override void Flush()
888 this.checkDisposed();
890 this.innerStream.Flush();
893 public int Read(byte[] buffer)
895 return this.Read(buffer, 0, buffer.Length);
898 public override int Read(byte[] buffer, int offset, int count)
900 IAsyncResult res = this.BeginRead(buffer, offset, count, null, null);
902 return this.EndRead(res);
905 public override long Seek(long offset, SeekOrigin origin)
907 throw new NotSupportedException();
910 public override void SetLength(long value)
912 throw new NotSupportedException();
915 public void Write(byte[] buffer)
917 this.Write(buffer, 0, buffer.Length);
920 public override void Write(byte[] buffer, int offset, int count)
922 IAsyncResult res = this.BeginWrite(buffer, offset, count, null, null);
927 public override bool CanRead
929 get { return this.innerStream.CanRead; }
932 public override bool CanSeek
934 get { return false; }
937 public override bool CanWrite
939 get { return this.innerStream.CanWrite; }
942 public override long Length
944 get { throw new NotSupportedException(); }
947 public override long Position
951 throw new NotSupportedException();
955 throw new NotSupportedException();
960 #region IDisposable Members and Finalizer
967 public void Dispose()
970 GC.SuppressFinalize(this);
973 protected virtual void Dispose(bool disposing)
979 if (this.innerStream != null)
981 if (this.context.HandshakeState == HandshakeState.Finished &&
982 !this.context.ConnectionEnd)
984 // Write close notify
985 this.protocol.SendAlert(AlertDescription.CloseNotify);
990 // Close inner stream
991 this.innerStream.Close();
994 this.ownsStream = false;
995 this.innerStream = null;
998 this.disposed = true;
1004 #region Misc Methods
1006 private void resetBuffer()
1008 this.inputBuffer.SetLength(0);
1009 this.inputBuffer.Position = 0;
1012 internal void checkDisposed()
1016 throw new ObjectDisposedException("The Stream is closed.");