Author: spouliot
Date: 2005-04-13 15:06:13 -0400 (Wed, 13 Apr 2005)
New Revision: 42956
Modified:
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ChangeLog
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
Log:
2005-04-13 Sebastien Pouliot <[EMAIL PROTECTED]>
* CipherSuite.cs: In sync with HEAD.
* RecordProtocol.cs: Some API changes so a record can be decoded from
any supplied stream (not just the inner network stream).
* SslClientStream.cs: BeginRead is now truly async if the Negotiate is
called from BeginWrite (where it should be in most case).
* SslServerStream.cs: Adapted to API changes in RecordProtocol.cs.
Modified:
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ChangeLog
===================================================================
---
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ChangeLog
2005-04-13 19:03:17 UTC (rev 42955)
+++
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ChangeLog
2005-04-13 19:06:13 UTC (rev 42956)
@@ -1,3 +1,12 @@
+2005-04-13 Sebastien Pouliot <[EMAIL PROTECTED]>
+
+ * CipherSuite.cs: In sync with HEAD.
+ * RecordProtocol.cs: Some API changes so a record can be decoded from
+ any supplied stream (not just the inner network stream).
+ * SslClientStream.cs: BeginRead is now truly async if the Negotiate is
+ called from BeginWrite (where it should be in most case).
+ * SslServerStream.cs: Adapted to API changes in RecordProtocol.cs.
+
2005-04-12 Sebastien Pouliot <[EMAIL PROTECTED]>
* SslHandshakeHash.cs: Changed "SslHash" to "MD5SHA1". Fix #71696.
Modified:
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
===================================================================
---
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
2005-04-13 19:03:17 UTC (rev 42955)
+++
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
2005-04-13 19:06:13 UTC (rev 42956)
@@ -370,9 +370,6 @@
public byte[] PRF(byte[] secret, string label, byte[] data, int
length)
{
- HashAlgorithm md5 = MD5.Create();
- HashAlgorithm sha1 = SHA1.Create();
-
/* Secret Length calc exmplain from the RFC2246.
Section 5
*
* S1 and S2 are the two halves of the secret and each
is the same
@@ -593,4 +590,4 @@
#endregion
}
-}
\ No newline at end of file
+}
Modified:
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
===================================================================
---
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
2005-04-13 19:03:17 UTC (rev 42955)
+++
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
2005-04-13 19:06:13 UTC (rev 42956)
@@ -72,7 +72,7 @@
#region Reveive Record Methods
- public byte[] ReceiveRecord()
+ public byte[] ReceiveRecord(Stream record)
{
if (this.context.ConnectionEnd)
{
@@ -80,9 +80,9 @@
AlertDescription.InternalError,
"The session is finished and it's no
longer valid.");
}
-
- // Try to read the Record Content Type
- int type = this.innerStream.ReadByte();
+
+ // Try to read the Record Content Type
+ int type = record.ReadByte ();
if (type == -1)
{
return null;
@@ -92,10 +92,13 @@
this.context.LastHandshakeMsg =
HandshakeType.ClientHello;
ContentType contentType = (ContentType)type;
- byte[] buffer = this.ReadRecordBuffer(type);
+ byte[] buffer = this.ReadRecordBuffer(type, record);
+ if (buffer == null)
+ {
+ // record incomplete (at the moment)
+ return null;
+ }
- TlsStream message = new TlsStream(buffer);
-
// Decrypt message contents if needed
if (contentType == ContentType.Alert && buffer.Length
== 2)
{
@@ -104,20 +107,22 @@
{
if (this.context.IsActual && contentType !=
ContentType.ChangeCipherSpec)
{
- message =
this.decryptRecordFragment(contentType, message.ToArray());
-
- DebugHelper.WriteLine("Decrypted record
data", message.ToArray());
+ buffer =
this.decryptRecordFragment(contentType, buffer);
+ DebugHelper.WriteLine("Decrypted record
data", buffer);
}
}
// Process record
- byte[] result = message.ToArray();
-
switch (contentType)
{
case ContentType.Alert:
-
this.ProcessAlert((AlertLevel)message.ReadByte(),
(AlertDescription)message.ReadByte());
- result = null;
+ this.ProcessAlert((AlertLevel)buffer
[0], (AlertDescription)buffer [1]);
+ if (record.CanSeek)
+ {
+ // don't reprocess that memory
block
+ record.SetLength (0);
+ }
+ buffer = null;
break;
case ContentType.ChangeCipherSpec:
@@ -127,14 +132,15 @@
case ContentType.ApplicationData:
break;
- case ContentType.Handshake:
+ case ContentType.Handshake:
+ TlsStream message = new TlsStream
(buffer);
while (!message.EOF)
{
this.ProcessHandshakeMessage(message);
}
// Update handshakes of current messages
-
this.context.HandshakeMessages.Write(message.ToArray());
+
this.context.HandshakeMessages.Write(buffer);
break;
// FIXME / MCS bug - http://bugzilla.ximian.com/show_bug.cgi?id=67711
@@ -149,35 +155,41 @@
AlertDescription.UnexpectedMessage,
"Unknown record
received from server.");
}
- this.context.HandshakeMessages.Write
(result);
+ this.context.HandshakeMessages.Write
(buffer);
break;
}
- return result;
- }
-
- private byte[] ReadRecordBuffer(int contentType)
+ return buffer;
+ }
+
+ private byte[] ReadRecordBuffer (int contentType, Stream record)
{
switch (contentType)
{
case 0x80:
- return this.ReadClientHelloV2();
+ return this.ReadClientHelloV2(record);
default:
if
(!Enum.IsDefined(typeof(ContentType), (ContentType)contentType))
{
throw new
TlsException(AlertDescription.DecodeError);
}
- return this.ReadStandardRecordBuffer();
+ return
this.ReadStandardRecordBuffer(record);
}
- }
+ }
+
+ private byte[] ReadClientHelloV2 (Stream record)
+ {
+ int msgLength = record.ReadByte ();
+ // process further only if the whole record is available
+ if (record.CanSeek && (msgLength + 1 > record.Length))
+ {
+ return null;
+ }
+
+ byte[] message = new byte[msgLength];
+ record.Read (message, 0, msgLength);
- private byte[] ReadClientHelloV2()
- {
- int msgLength =
this.innerStream.ReadByte();
- byte[] message = new byte [msgLength];
- this.innerStream.Read (message, 0, msgLength);
-
int msgType = message [0];
if (msgType != 1)
{
@@ -229,19 +241,26 @@
this.context.ProtocolNegotiated = true;
return message;
- }
+ }
+
+ private byte[] ReadStandardRecordBuffer (Stream record)
+ {
+ short protocol = this.ReadShort(record);
+ short length = this.ReadShort(record);
- private byte[] ReadStandardRecordBuffer()
- {
- short protocol = this.ReadShort();
- short length = this.ReadShort();
+ // process further only if the whole record is available
+ // note: the first 5 bytes aren't part of the length
+ if (record.CanSeek && (length + 5 > record.Length))
+ {
+ return null;
+ }
// Read Record data
int received = 0;
byte[] buffer = new byte[length];
while (received != length)
{
- received += this.innerStream.Read(buffer,
received, buffer.Length - received);
+ received += record.Read(buffer, received,
buffer.Length - received);
}
// Check that the message has a valid protocol version
@@ -256,10 +275,10 @@
return buffer;
}
- private short ReadShort()
+ private short ReadShort(Stream record)
{
byte[] b = new byte[2];
- this.innerStream.Read(b, 0, b.Length);
+ record.Read(b, 0, b.Length);
short val = BitConverter.ToInt16(b, 0);
@@ -459,7 +478,7 @@
return ecr;
}
- private TlsStream decryptRecordFragment(
+ private byte[] decryptRecordFragment(
ContentType contentType,
byte[] fragment)
{
@@ -520,7 +539,7 @@
// Update sequence number
this.context.ReadSequenceNumber++;
- return new TlsStream(dcrFragment);
+ return dcrFragment;
}
#endregion
Modified:
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
===================================================================
---
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
2005-04-13 19:03:17 UTC (rev 42955)
+++
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
2005-04-13 19:06:13 UTC (rev 42956)
@@ -29,6 +29,7 @@
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
+using System.Threading;
using Mono.Security.Protocol.Tls.Handshake;
@@ -65,12 +66,13 @@
#region Fields
private Stream
innerStream;
- private BufferedStream
inputBuffer;
+ private MemoryStream
inputBuffer;
private ClientContext context;
private ClientRecordProtocol protocol;
private bool
ownsStream;
private bool
disposed;
private bool
checkCertRevocationStatus;
+ private object
negotiate;
private object
read;
private object
write;
@@ -236,6 +238,11 @@
}
}
+ // this is used by Mono's certmgr tool to download certificates
+ internal Mono.Security.X509.X509CertificateCollection
ServerCertificates {
+ get { return context.ServerSettings.Certificates; }
+ }
+
#endregion
#region Callback Properties
@@ -329,9 +336,10 @@
targetHost,
clientCertificates);
- this.inputBuffer = new BufferedStream(new
MemoryStream());
+ this.inputBuffer = new MemoryStream();
this.innerStream = stream;
this.ownsStream = ownsStream;
+ this.negotiate = new object ();
this.read = new object ();
this.write = new object ();
this.protocol = new
ClientRecordProtocol(innerStream, context);
@@ -398,8 +406,8 @@
int count,
AsyncCallback callback,
object state)
- {
- this.checkDisposed();
+ {
+ this.checkDisposed ();
if (buffer == null)
{
@@ -422,15 +430,21 @@
throw new ArgumentOutOfRangeException("count is
less than the length of buffer minus the value of the offset parameter.");
}
- lock (this)
+ if (this.context.HandshakeState == HandshakeState.None)
{
- if (this.context.HandshakeState ==
HandshakeState.None)
+ // Note: Async code may have problem if they
can't ensure that
+ // the Negotiate phase isn't done during a read
operation.
+ // System.Net.HttpWebRequest protects itself
from that problem
+ lock (this.negotiate)
{
- this.NegotiateHandshake();
+ if (this.context.HandshakeState ==
HandshakeState.None)
+ {
+ this.NegotiateHandshake();
+ }
}
}
- IAsyncResult asyncResult;
+ IAsyncResult asyncResult = null;
lock (this.read)
{
@@ -445,43 +459,28 @@
if (!this.context.ConnectionEnd)
{
- // Check if we have space in
the middle buffer
- // if not Read next TLS record
and update the inputBuffer
- while ((this.inputBuffer.Length
- this.inputBuffer.Position) < count)
+ if ((this.inputBuffer.Length ==
this.inputBuffer.Position) && (count > 0))
{
- // Read next record and
write it into the inputBuffer
- long position
= this.inputBuffer.Position;
- byte[] record
= this.protocol.ReceiveRecord();
-
- if (record != null &&
record.Length > 0)
- {
- // Write new
data to the inputBuffer
-
this.inputBuffer.Seek(0, SeekOrigin.End);
-
this.inputBuffer.Write(record, 0, record.Length);
+ // bigger than max
record length for SSL/TLS
+ byte[] recbuf = new
byte[16384];
- // Restore
buffer position
-
this.inputBuffer.Seek(position, SeekOrigin.Begin);
- }
- else
+ // this will read data
from the network until we have (at least) one
+ // record to send back
to the caller
+
this.innerStream.BeginRead (recbuf, 0, recbuf.Length,
+ new
AsyncCallback (NetworkReadCallback), recbuf);
+
+ if
(!recordEvent.WaitOne (300000, false)) // 5 minutes
{
- if (record ==
null)
- {
- break;
- }
+ // FAILSAFE
+
DebugHelper.WriteLine ("TIMEOUT length {0}, position {1}, count {2} -
{3}\n{4}",
+
this.inputBuffer.Length, this.inputBuffer.Position, count, GetHashCode (),
+
Environment.StackTrace);
+ throw new
TlsException (AlertDescription.InternalError);
}
-
- // TODO: Review if we
need to check the Length
- // property of the
innerStream for other types
- // of streams, to check
that there are data available
- // for read
- if (this.innerStream is
NetworkStream &&
-
!((NetworkStream)this.innerStream).DataAvailable)
- {
- break;
- }
- }
+ }
}
+ // return the record(s) to the caller
asyncResult =
this.inputBuffer.BeginRead(
buffer, offset, count,
callback, state);
}
@@ -496,9 +495,102 @@
{
throw new IOException("IO exception
during read.");
}
+
}
return asyncResult;
+ }
+
+ private ManualResetEvent recordEvent = new ManualResetEvent
(false);
+ private MemoryStream recordStream = new MemoryStream ();
+
+ // read encrypted data until we have enough to decrypt (at
least) one
+ // record and return are the records (may be more than one) we
have
+ private void NetworkReadCallback (IAsyncResult result)
+ {
+ byte[] recbuf = (byte[])result.AsyncState;
+ int n = innerStream.EndRead (result);
+ if (n > 0)
+ {
+ // add the just received data to the waiting
data
+ recordStream.Write (recbuf, 0, n);
+ }
+
+ bool dataToReturn = false;
+ long pos = recordStream.Position;
+
+ recordStream.Position = 0;
+ byte[] record = null;
+
+ // don't try to decode record unless we have at least 5
bytes
+ // i.e. type (1), protocol (2) and length (2)
+ if (recordStream.Length >= 5)
+ {
+ record = this.protocol.ReceiveRecord
(recordStream);
+ }
+
+ // a record of 0 length is valid (and there may be more
record after it)
+ while (record != null)
+ {
+ // we probably received more stuff after the
record, and we must keep it!
+ long remainder = recordStream.Length -
recordStream.Position;
+ byte[] outofrecord = null;
+ if (remainder > 0)
+ {
+ outofrecord = new byte[remainder];
+ recordStream.Read (outofrecord, 0,
outofrecord.Length);
+ }
+
+ long position = this.inputBuffer.Position;
+
+ if (record.Length > 0)
+ {
+ // Write new data to the inputBuffer
+ this.inputBuffer.Seek (0,
SeekOrigin.End);
+ this.inputBuffer.Write (record, 0,
record.Length);
+
+ // Restore buffer position
+ this.inputBuffer.Seek (position,
SeekOrigin.Begin);
+ dataToReturn = true;
+ }
+
+ recordStream.SetLength (0);
+ record = null;
+
+ if (remainder > 0)
+ {
+ recordStream.Write (outofrecord, 0,
outofrecord.Length);
+ // type (1), protocol (2) and length (2)
+ if (recordStream.Length >= 5)
+ {
+ // try to see if another record
is available
+ recordStream.Position = 0;
+ record =
this.protocol.ReceiveRecord (recordStream);
+ if (record == null)
+ pos =
recordStream.Length;
+ }
+ else
+ pos = remainder;
+ }
+ else
+ pos = 0;
+ }
+
+ if (!dataToReturn && (n > 0))
+ {
+ // there is no record to return to caller and
(possibly) more data waiting
+ // so continue reading from network (and
appending to stream)
+ recordStream.Position = recordStream.Length;
+ this.innerStream.BeginRead (recbuf, 0,
recbuf.Length,
+ new AsyncCallback
(NetworkReadCallback), recbuf);
+ }
+ else
+ {
+ // we have record(s) to return -or- no more
available to read from network
+ // reset position for further reading
+ recordStream.Position = pos;
+ recordEvent.Set ();
+ }
}
public override IAsyncResult BeginWrite(
@@ -531,11 +623,14 @@
throw new ArgumentOutOfRangeException("count is
less than the length of buffer minus the value of the offset parameter.");
}
- lock (this)
+ if (this.context.HandshakeState == HandshakeState.None)
{
- if (this.context.HandshakeState ==
HandshakeState.None)
+ lock (this.negotiate)
{
- this.NegotiateHandshake();
+ if (this.context.HandshakeState ==
HandshakeState.None)
+ {
+ this.NegotiateHandshake();
+ }
}
}
@@ -576,9 +671,10 @@
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult is
null or was not obtained by calling BeginRead.");
- }
+ }
- return this.inputBuffer.EndRead(asyncResult);
+ recordEvent.Reset ();
+ return this.inputBuffer.EndRead (asyncResult);
}
public override void EndWrite(IAsyncResult asyncResult)
@@ -684,76 +780,73 @@
internal void NegotiateHandshake()
{
- lock (this)
+ try
{
- try
+ if (this.context.HandshakeState !=
HandshakeState.None)
{
- if (this.context.HandshakeState !=
HandshakeState.None)
- {
- this.context.Clear();
- }
+ this.context.Clear();
+ }
- // Obtain supported cipher suites
- this.context.SupportedCiphers =
CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
+ // Obtain supported cipher suites
+ this.context.SupportedCiphers =
CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);
- // Send client hello
-
this.protocol.SendRecord(HandshakeType.ClientHello);
+ // Send client hello
+
this.protocol.SendRecord(HandshakeType.ClientHello);
- // Read server response
- while (this.context.LastHandshakeMsg !=
HandshakeType.ServerHelloDone)
- {
- // Read next record
- this.protocol.ReceiveRecord();
- }
+ // Read server response
+ while (this.context.LastHandshakeMsg !=
HandshakeType.ServerHelloDone)
+ {
+ // Read next record
+ this.protocol.ReceiveRecord
(this.innerStream);
+ }
- // Send client certificate if requested
- if
(this.context.ServerSettings.CertificateRequest)
- {
-
this.protocol.SendRecord(HandshakeType.Certificate);
- }
+ // Send client certificate if requested
+ if
(this.context.ServerSettings.CertificateRequest)
+ {
+
this.protocol.SendRecord(HandshakeType.Certificate);
+ }
- // Send Client Key Exchange
-
this.protocol.SendRecord(HandshakeType.ClientKeyExchange);
+ // Send Client Key Exchange
+
this.protocol.SendRecord(HandshakeType.ClientKeyExchange);
- // Now initialize session cipher with
the generated keys
- this.context.Cipher.InitializeCipher();
+ // Now initialize session cipher with the
generated keys
+ this.context.Cipher.InitializeCipher();
- // Send certificate verify if requested
- if
(this.context.ServerSettings.CertificateRequest)
- {
-
this.protocol.SendRecord(HandshakeType.CertificateVerify);
- }
+ // Send certificate verify if requested
+ if
(this.context.ServerSettings.CertificateRequest)
+ {
+
this.protocol.SendRecord(HandshakeType.CertificateVerify);
+ }
- // Send Cipher Spec protocol
- this.protocol.SendChangeCipherSpec();
+ // Send Cipher Spec protocol
+ this.protocol.SendChangeCipherSpec();
- // Read record until server finished is
received
- while (this.context.HandshakeState !=
HandshakeState.Finished)
- {
- // If all goes well this will
process messages:
- // Change Cipher
Spec
- // Server finished
- this.protocol.ReceiveRecord();
- }
-
- // Clear Key Info
- this.context.ClearKeyInfo();
- }
- catch (TlsException ex)
+ // Read record until server finished is received
+ while (this.context.HandshakeState !=
HandshakeState.Finished)
{
- this.protocol.SendAlert(ex.Alert);
- this.Close();
-
- throw new IOException("The
authentication or decryption has failed.");
+ // If all goes well this will process
messages:
+ // Change Cipher Spec
+ // Server finished
+ this.protocol.ReceiveRecord
(this.innerStream);
}
- catch (Exception)
- {
-
this.protocol.SendAlert(AlertDescription.InternalError);
- this.Close();
- throw new IOException("The
authentication or decryption has failed.");
- }
+ // Clear Key Info
+ this.context.ClearKeyInfo();
}
+ catch (TlsException ex)
+ {
+ this.protocol.SendAlert(ex.Alert);
+ this.Close();
+
+ throw new IOException("The authentication or
decryption has failed.");
+ }
+ catch (Exception)
+ {
+
this.protocol.SendAlert(AlertDescription.InternalError);
+ this.Close();
+
+ throw new IOException("The authentication or
decryption has failed.");
+ }
}
#endregion
Modified:
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
===================================================================
---
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
2005-04-13 19:03:17 UTC (rev 42955)
+++
branches/mono-1-0/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
2005-04-13 19:06:13 UTC (rev 42956)
@@ -402,7 +402,7 @@
{
// Read next record and
write it into the inputBuffer
long position
= this.inputBuffer.Position;
- byte[] record
= this.protocol.ReceiveRecord();
+ byte[] record
= this.protocol.ReceiveRecord(this.innerStream);
if (record != null &&
record.Length > 0)
{
@@ -649,8 +649,8 @@
// Set handshake state
this.context.HandshakeState =
HandshakeState.Started;
- // Receive Client Hello message
- this.protocol.ReceiveRecord();
+ // Receive Client Hello message
+ this.protocol.ReceiveRecord (this.innerStream);
// If received message is not an ClientHello
send a
// Fatal Alert
@@ -685,8 +685,8 @@
// Receive client response, until the Client
Finished message
// is received
while (this.context.LastHandshakeMsg !=
HandshakeType.Finished)
- {
- this.protocol.ReceiveRecord();
+ {
+ this.protocol.ReceiveRecord
(this.innerStream);
}
// Send ChangeCipherSpec and ServerFinished
messages
_______________________________________________
Mono-patches maillist - [email protected]
http://lists.ximian.com/mailman/listinfo/mono-patches