Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMartin Baulig <mabaul@microsoft.com>2019-10-19 01:02:48 +0300
committerAlexander Köplinger <alex.koeplinger@outlook.com>2019-10-19 01:02:48 +0300
commitfffad7e3a8f57a7eaff67d43a3a29b7f64e94646 (patch)
treee9b222b63c2a16a6a6b22cb4b6b8a08c06c2c896 /mcs/class/Mono.Security
parent8836231459121e0144ae03169554c1d0636ec5ba (diff)
Remove the Legacy TLS Provider. (#17391)
* `MonoTlsProviderFactory` now treats "legacy" as an alias for "default". * `Mono.Net.Security/LegacySslStream`: Removed. This class also wasn't using the `MobileAuthenticatedStream` base class, thus preventing cleanups simplifications in that area. * `Mono.Net.Security/LegacyTlsProvider`: Removed. * `Mono.Security/Mono.Security.Protocol.Tls*`: Removed all the old legacy code. * `Mono.Security.Interface.MonoTlsProviderFactory`: Bump internal version to 4.
Diffstat (limited to 'mcs/class/Mono.Security')
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs3
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs149
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs220
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs87
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs139
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs98
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs450
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs111
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs102
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs150
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs52
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs121
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs276
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs86
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs88
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs152
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs116
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs74
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs107
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs75
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs122
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs52
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs110
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs38
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs170
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs44
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Alert.cs265
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherAlgorithmType.cs45
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs594
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteCollection.cs130
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteFactory.cs199
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientContext.cs82
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientRecordProtocol.cs195
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientSessionCache.cs254
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ContentType.cs37
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Context.cs519
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/DebugHelper.cs95
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs43
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HandshakeState.cs36
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HashAlgorithmType.cs41
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HttpsClientStream.cs122
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/MD5SHA1.cs146
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs108
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs105
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs965
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityCompressionType.cs42
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityParameters.cs60
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityProtocolType.cs46
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerContext.cs118
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs173
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslCipherSuite.cs251
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs659
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslHandshakeHash.cs185
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs332
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs1224
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsCipherSuite.cs152
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsClientSettings.cs124
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsException.cs93
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsServerSettings.cs129
-rw-r--r--mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsStream.cs274
-rw-r--r--mcs/class/Mono.Security/Mono.Security.csproj59
-rw-r--r--mcs/class/Mono.Security/Mono.Security.dll.sources60
62 files changed, 3 insertions, 11151 deletions
diff --git a/mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs b/mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs
index 5df54ac6eeb..5776e399745 100644
--- a/mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs
+++ b/mcs/class/Mono.Security/Mono.Security.Interface/MonoTlsProviderFactory.cs
@@ -183,9 +183,10 @@ namespace Mono.Security.Interface
* - 1: everything up until May 2018
* - 2: the new ServicePointScheduler changes have landed
* - 3: full support for Client Certificates
+ * - 4: Legacy TLS Removal
*
*/
- internal const int InternalVersion = 3;
+ internal const int InternalVersion = 4;
#endregion
}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs
deleted file mode 100644
index 49e2d85f4c3..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs
+++ /dev/null
@@ -1,149 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.Protocol.Tls;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsClientCertificate : HandshakeMessage
- {
- private bool clientCertSelected;
- private X509Certificate clientCert;
-
- #region Constructors
-
- public TlsClientCertificate(Context context)
- : base(context, HandshakeType.Certificate)
- {
- }
-
- #endregion
-
- #region Properties
-
- public X509Certificate ClientCertificate {
- get {
- if (!clientCertSelected)
- {
- GetClientCertificate ();
- clientCertSelected = true;
- }
- return clientCert;
- }
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
- this.Reset();
- }
-
- #endregion
-
- #region Protected Methods
-
- private void GetClientCertificate ()
- {
-// TODO: Client certificate selection is unfinished
- ClientContext context = (ClientContext)this.Context;
-
- // note: the server may ask for mutual authentication
- // but may not require it (i.e. it can be optional).
- if (context.ClientSettings.Certificates != null &&
- context.ClientSettings.Certificates.Count > 0)
- {
- clientCert = context.SslStream.RaiseClientCertificateSelection(
- this.Context.ClientSettings.Certificates,
- new X509Certificate(this.Context.ServerSettings.Certificates[0].RawData),
- this.Context.ClientSettings.TargetHost,
- null);
- // Note: the application code can raise it's
- // own exception to stop the connection too.
- }
-
- // Update the selected client certificate
- context.ClientSettings.ClientCertificate = clientCert;
- }
-
- private void SendCertificates ()
- {
- TlsStream chain = new TlsStream ();
-
- X509Certificate currentCert = this.ClientCertificate;
- while (currentCert != null) {
- byte[] rawCert = currentCert.GetRawCertData ();
- chain.WriteInt24 (rawCert.Length);
- chain.Write(rawCert);
- currentCert = FindParentCertificate (currentCert);
- }
- this.WriteInt24 ((int)chain.Length);
- this.Write (chain.ToArray ());
- }
-
- protected override void ProcessAsSsl3()
- {
- if (this.ClientCertificate != null) {
- SendCertificates ();
- } else {
- // an Alert warning for NoCertificate (41)
- // should be sent from here - but that would
- // break the current message handling
- }
- }
-
- protected override void ProcessAsTls1()
- {
- if (this.ClientCertificate != null) {
- SendCertificates ();
- } else {
- // return message with empty certificate (see 7.4.6 in RFC2246)
- this.WriteInt24 (0);
- }
- }
-
- private X509Certificate FindParentCertificate (X509Certificate cert)
- {
- #pragma warning disable 618
- // This certificate is the root certificate
- if (cert.GetName () == cert.GetIssuerName ())
- return null;
-
- foreach (X509Certificate certificate in this.Context.ClientSettings.Certificates) {
- if (certificate.GetName () == cert.GetIssuerName ())
- return certificate;
- }
- return null;
- #pragma warning restore 618
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs
deleted file mode 100644
index bfa689d2ea4..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs
+++ /dev/null
@@ -1,220 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography.X509Certificates;
-
-using System.Security.Cryptography;
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsClientCertificateVerify : HandshakeMessage
- {
- #region Constructors
-
- public TlsClientCertificateVerify(Context context)
- : base(context, HandshakeType.CertificateVerify)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
- this.Reset();
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- AsymmetricAlgorithm privKey = null;
- ClientContext context = (ClientContext)this.Context;
-
- privKey = context.SslStream.RaisePrivateKeySelection(
- context.ClientSettings.ClientCertificate,
- context.ClientSettings.TargetHost);
-
- if (privKey == null)
- {
- throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable.");
- }
- else
- {
- SslHandshakeHash hash = new SslHandshakeHash(context.MasterSecret);
- hash.TransformFinalBlock(
- context.HandshakeMessages.ToArray(),
- 0,
- (int)context.HandshakeMessages.Length);
-
- // CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented
- // in RSACryptoServiceProvider. Other implementations likely implement DecryptValue
- // so we will try the CreateSignature method.
- byte[] signature = null;
- if (!(privKey is RSACryptoServiceProvider))
- {
- try
- {
- signature = hash.CreateSignature((RSA)privKey);
- }
- catch (NotImplementedException)
- { }
- }
- // If DecryptValue is not implemented, then try to export the private
- // key and let the RSAManaged class do the DecryptValue
- if (signature == null)
- {
- // RSAManaged of the selected ClientCertificate
- // (at this moment the first one)
- RSA rsa = this.getClientCertRSA((RSA)privKey);
-
- // Write message
- signature = hash.CreateSignature(rsa);
- }
- this.Write((short)signature.Length);
- this.Write(signature, 0, signature.Length);
- }
- }
-
- protected override void ProcessAsTls1()
- {
- AsymmetricAlgorithm privKey = null;
- ClientContext context = (ClientContext)this.Context;
-
- privKey = context.SslStream.RaisePrivateKeySelection(
- context.ClientSettings.ClientCertificate,
- context.ClientSettings.TargetHost);
-
- if (privKey == null)
- {
- throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable.");
- }
- else
- {
- // Compute handshake messages hash
- MD5SHA1 hash = new MD5SHA1();
- hash.ComputeHash(
- context.HandshakeMessages.ToArray(),
- 0,
- (int)context.HandshakeMessages.Length);
-
- // CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented
- // in RSACryptoServiceProvider. Other implementations likely implement DecryptValue
- // so we will try the CreateSignature method.
- byte[] signature = null;
- if (!(privKey is RSACryptoServiceProvider))
- {
- try
- {
- signature = hash.CreateSignature((RSA)privKey);
- }
- catch (NotImplementedException)
- { }
- }
- // If DecryptValue is not implemented, then try to export the private
- // key and let the RSAManaged class do the DecryptValue
- if (signature == null)
- {
- // RSAManaged of the selected ClientCertificate
- // (at this moment the first one)
- RSA rsa = this.getClientCertRSA((RSA)privKey);
-
- // Write message
- signature = hash.CreateSignature(rsa);
- }
- this.Write((short)signature.Length);
- this.Write(signature, 0, signature.Length);
- }
- }
-
- #endregion
-
- #region Private methods
-
- private RSA getClientCertRSA(RSA privKey)
- {
- RSAParameters rsaParams = new RSAParameters();
- RSAParameters privateParams = privKey.ExportParameters(true);
-
- // for RSA m_publickey contains 2 ASN.1 integers
- // the modulus and the public exponent
- ASN1 pubkey = new ASN1 (this.Context.ClientSettings.Certificates[0].GetPublicKey());
- ASN1 modulus = pubkey [0];
- if ((modulus == null) || (modulus.Tag != 0x02))
- {
- return null;
- }
- ASN1 exponent = pubkey [1];
- if (exponent.Tag != 0x02)
- {
- return null;
- }
-
- rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value);
- rsaParams.Exponent = exponent.Value;
-
- // Set private key parameters
- rsaParams.D = privateParams.D;
- rsaParams.DP = privateParams.DP;
- rsaParams.DQ = privateParams.DQ;
- rsaParams.InverseQ = privateParams.InverseQ;
- rsaParams.P = privateParams.P;
- rsaParams.Q = privateParams.Q;
-
- // BUG: MS BCL 1.0 can't import a key which
- // isn't the same size as the one present in
- // the container.
- int keySize = (rsaParams.Modulus.Length << 3);
- RSAManaged rsa = new RSAManaged(keySize);
- rsa.ImportParameters (rsaParams);
-
- return (RSA)rsa;
- }
-
- private byte[] getUnsignedBigInteger(byte[] integer)
- {
- if (integer [0] == 0x00)
- {
- // this first byte is added so we're sure it's an unsigned integer
- // however we can't feed it into RSAParameters or DSAParameters
- int length = integer.Length - 1;
- byte[] uinteger = new byte [length];
- Buffer.BlockCopy (integer, 1, uinteger, 0, length);
- return uinteger;
- }
- else
- {
- return integer;
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs
deleted file mode 100644
index 9f2e1ae2fbf..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsClientFinished : HandshakeMessage
- {
- #region Constructors
-
- public TlsClientFinished(Context context)
- : base(context, HandshakeType.Finished)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
- this.Reset();
- }
-
- #endregion
-
- #region Protected Methods
-
- static private byte[] Ssl3Marker = new byte [4] { 0x43, 0x4c, 0x4e, 0x54 };
-
- protected override void ProcessAsSsl3()
- {
- // Compute handshake messages hashes
- HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
-
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- hash.TransformBlock (data, 0, data.Length, data, 0);
- hash.TransformBlock (Ssl3Marker, 0, Ssl3Marker.Length, Ssl3Marker, 0);
- // hack to avoid memory allocation
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- this.Write (hash.Hash);
- }
-
- protected override void ProcessAsTls1()
- {
- // Compute handshake messages hash
- HashAlgorithm hash = new MD5SHA1();
-
- // note: we could call HashAlgorithm.ComputeHash(Stream) but that would allocate (on Mono)
- // a 4096 bytes buffer to process the hash - which is bigger than HandshakeMessages
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- byte[] digest = hash.ComputeHash (data, 0, data.Length);
-
- // Write message
- Write(this.Context.Write.Cipher.PRF(this.Context.MasterSecret, "client finished", digest, 12));
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs
deleted file mode 100644
index 42ca34523a4..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Net;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsClientHello : HandshakeMessage
- {
- #region Fields
-
- private byte[] random;
-
- #endregion
-
- #region Constructors
-
- public TlsClientHello(Context context)
- : base(context, HandshakeType.ClientHello)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- ClientContext context = (ClientContext)this.Context;
-
- base.Update();
-
- context.ClientRandom = random;
- context.ClientHelloProtocol = this.Context.Protocol;
-
- random = null;
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- // Client Version
- this.Write(this.Context.Protocol);
-
- // Random bytes - Unix time + Radom bytes [28]
- TlsStream clientRandom = new TlsStream();
- clientRandom.Write(this.Context.GetUnixTime());
- clientRandom.Write(this.Context.GetSecureRandomBytes(28));
- this.random = clientRandom.ToArray();
- clientRandom.Reset();
-
- this.Write(this.random);
-
- // Session id
- // Check if we have a cache session we could reuse
- this.Context.SessionId = ClientSessionCache.FromHost (this.Context.ClientSettings.TargetHost);
- if (this.Context.SessionId != null)
- {
- this.Write((byte)this.Context.SessionId.Length);
- if (this.Context.SessionId.Length > 0)
- {
- this.Write(this.Context.SessionId);
- }
- }
- else
- {
- this.Write((byte)0);
- }
-
- // Write length of Cipher suites
- this.Write((short)(this.Context.SupportedCiphers.Count*2));
-
- // Write Supported Cipher suites
- for (int i = 0; i < this.Context.SupportedCiphers.Count; i++)
- {
- this.Write((short)this.Context.SupportedCiphers[i].Code);
- }
-
- // Compression methods length
- this.Write((byte)1);
-
- // Compression methods ( 0 = none )
- this.Write((byte)this.Context.CompressionMethod);
- }
-
- protected override void ProcessAsTls1()
- {
- ProcessAsSsl3 ();
-
- // If applicable add the "server_name" extension to the hello message
- // http://www.ietf.org/rfc/rfc3546.txt
- string host = Context.ClientSettings.TargetHost;
- // Our TargetHost might be an address (not a host *name*) - see bug #8553
- // RFC3546 -> Literal IPv4 and IPv6 addresses are not permitted in "HostName".
- IPAddress addr;
- if (IPAddress.TryParse (host, out addr))
- return;
-
- TlsStream extensions = new TlsStream ();
- byte[] server_name = System.Text.Encoding.UTF8.GetBytes (host);
- extensions.Write ((short) 0x0000); // ExtensionType: server_name (0)
- extensions.Write ((short) (server_name.Length + 5)); // ServerNameList (length)
- extensions.Write ((short) (server_name.Length + 3)); // ServerName (length)
- extensions.Write ((byte) 0x00); // NameType: host_name (0)
- extensions.Write ((short) server_name.Length); // HostName (length)
- extensions.Write (server_name); // HostName (UTF8)
- this.Write ((short) extensions.Length);
- this.Write (extensions.ToArray ());
- }
-
- #endregion
- }
-} \ No newline at end of file
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs
deleted file mode 100644
index 3534d833170..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs
+++ /dev/null
@@ -1,98 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsClientKeyExchange : HandshakeMessage
- {
- #region Constructors
-
- public TlsClientKeyExchange (Context context) :
- base(context, HandshakeType.ClientKeyExchange)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- // a large chunk of code is common to both SSL3 and TLS1
- // SSL3 doesn't send the length of the buffer
- ProcessCommon (false);
- }
-
- protected override void ProcessAsTls1()
- {
- // a large chunk of code is common to both SSL3 and TLS1
- // TLS1 does send the length of the buffer
- ProcessCommon (true);
- }
-
- public void ProcessCommon (bool sendLength)
- {
- // Compute pre master secret
- byte[] preMasterSecret = this.Context.Negotiating.Cipher.CreatePremasterSecret ();
-
- // Create a new RSA key
- RSA rsa = null;
- if (this.Context.ServerSettings.ServerKeyExchange)
- {
- // this is the case for "exportable" ciphers
- rsa = new RSAManaged ();
- rsa.ImportParameters (this.Context.ServerSettings.RsaParameters);
- }
- else
- {
- rsa = this.Context.ServerSettings.CertificateRSA;
- }
-
- // Encrypt premaster_sercret
- RSAPKCS1KeyExchangeFormatter formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
-
- // Write the preMasterSecret encrypted
- byte[] buffer = formatter.CreateKeyExchange (preMasterSecret);
- if (sendLength)
- this.Write ((short) buffer.Length);
- this.Write (buffer);
-
- // Create master secret
- this.Context.Negotiating.Cipher.ComputeMasterSecret (preMasterSecret);
-
- // Create keys
- this.Context.Negotiating.Cipher.ComputeKeys ();
-
- // Clear resources
- rsa.Clear ();
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
deleted file mode 100644
index a96b415ef0c..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
+++ /dev/null
@@ -1,450 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2004, 2006-2010 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Net;
-using System.Collections;
-using System.Globalization;
-using System.Text.RegularExpressions;
-using System.Security.Cryptography;
-using X509Cert = System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.X509;
-using Mono.Security.X509.Extensions;
-
-using Mono.Security.Interface;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsServerCertificate : HandshakeMessage
- {
- #region Fields
-
- private X509CertificateCollection certificates;
-
- #endregion
-
- #region Constructors
-
- public TlsServerCertificate(Context context, byte[] buffer)
- : base(context, HandshakeType.Certificate, buffer)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
- this.Context.ServerSettings.Certificates = this.certificates;
- this.Context.ServerSettings.UpdateCertificateRSA();
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- this.certificates = new X509CertificateCollection();
-
- int readed = 0;
- int length = this.ReadInt24();
-
- while (readed < length)
- {
- // Read certificate length
- int certLength = ReadInt24();
-
- // Increment readed
- readed += 3;
-
- if (certLength > 0)
- {
- // Read certificate data
- byte[] buffer = this.ReadBytes(certLength);
-
- // Create a new X509 Certificate
- X509Certificate certificate = new X509Certificate(buffer);
- certificates.Add(certificate);
-
- readed += certLength;
-
- DebugHelper.WriteLine(
- String.Format("Server Certificate {0}", certificates.Count),
- buffer);
- }
- }
-
- this.validateCertificates(certificates);
- }
-
- #endregion
-
- #region Private Methods
-
- // Note: this method only works for RSA certificates
- // DH certificates requires some changes - does anyone use one ?
- private bool checkCertificateUsage (X509Certificate cert)
- {
- ClientContext context = (ClientContext)this.Context;
-
- // certificate extensions are required for this
- // we "must" accept older certificates without proofs
- if (cert.Version < 3)
- return true;
-
- KeyUsages ku = KeyUsages.none;
- switch (context.Negotiating.Cipher.ExchangeAlgorithmType)
- {
- case ExchangeAlgorithmType.RsaSign:
- ku = KeyUsages.digitalSignature;
- break;
- case ExchangeAlgorithmType.RsaKeyX:
- ku = KeyUsages.keyEncipherment;
- break;
- case ExchangeAlgorithmType.DiffieHellman:
- ku = KeyUsages.keyAgreement;
- break;
- case ExchangeAlgorithmType.Fortezza:
- return false; // unsupported certificate type
- }
-
- KeyUsageExtension kux = null;
- ExtendedKeyUsageExtension eku = null;
-
- X509Extension xtn = cert.Extensions ["2.5.29.15"];
- if (xtn != null)
- kux = new KeyUsageExtension (xtn);
-
- xtn = cert.Extensions ["2.5.29.37"];
- if (xtn != null)
- eku = new ExtendedKeyUsageExtension (xtn);
-
- if ((kux != null) && (eku != null))
- {
- // RFC3280 states that when both KeyUsageExtension and
- // ExtendedKeyUsageExtension are present then BOTH should
- // be valid
- if (!kux.Support (ku))
- return false;
- return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") ||
- eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1"));
- }
- else if (kux != null)
- {
- return kux.Support (ku);
- }
- else if (eku != null)
- {
- // Server Authentication (1.3.6.1.5.5.7.3.1) or
- // Netscape Server Gated Crypto (2.16.840.1.113730.4)
- return (eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.1") ||
- eku.KeyPurpose.Contains ("2.16.840.1.113730.4.1"));
- }
-
- // last chance - try with older (deprecated) Netscape extensions
- xtn = cert.Extensions ["2.16.840.1.113730.1.1"];
- if (xtn != null)
- {
- NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn);
- return ct.Support (NetscapeCertTypeExtension.CertTypes.SslServer);
- }
-
- // if the CN=host (checked later) then we assume this is meant for SSL/TLS
- // e.g. the new smtp.gmail.com certificate
- return true;
- }
-
- private void validateCertificates(X509CertificateCollection certificates)
- {
- ClientContext context = (ClientContext)this.Context;
- AlertDescription description = AlertDescription.BadCertificate;
-
-#if INSIDE_SYSTEM
- // This helps the linker to remove a lot of validation code that will never be used since
- // System.dll will, for OSX and iOS, uses the operating system X.509 certificate validations
- RemoteValidation (context, description);
-#else
- if (context.SslStream.HaveRemoteValidation2Callback)
- RemoteValidation (context, description);
- else
- LocalValidation (context, description);
-#endif
- }
-
- void RemoteValidation (ClientContext context, AlertDescription description)
- {
- ValidationResult res = context.SslStream.RaiseServerCertificateValidation2 (certificates);
- if (res.Trusted)
- return;
-
- long error = res.ErrorCode;
- switch (error) {
- case 0x800B0101:
- description = AlertDescription.CertificateExpired;
- break;
- case 0x800B010A:
- description = AlertDescription.UnknownCA;
- break;
- case 0x800B0109:
- description = AlertDescription.UnknownCA;
- break;
- default:
- description = AlertDescription.CertificateUnknown;
- break;
- }
- string err = String.Format ("Invalid certificate received from server. Error code: 0x{0:x}", error);
- throw new TlsException (description, err);
- }
-
- void LocalValidation (ClientContext context, AlertDescription description)
- {
- // the leaf is the web server certificate
- X509Certificate leaf = certificates [0];
- X509Cert.X509Certificate cert = new X509Cert.X509Certificate (leaf.RawData);
-
- ArrayList errors = new ArrayList();
-
- // SSL specific check - not all certificates can be
- // used to server-side SSL some rules applies after
- // all ;-)
- if (!checkCertificateUsage (leaf))
- {
- // WinError.h CERT_E_PURPOSE 0x800B0106
- errors.Add ((int)-2146762490);
- }
-
- // SSL specific check - does the certificate match
- // the host ?
- if (!checkServerIdentity (leaf))
- {
- // WinError.h CERT_E_CN_NO_MATCH 0x800B010F
- errors.Add ((int)-2146762481);
- }
-
- // Note: building and verifying a chain can take much time
- // so we do it last (letting simple things fails first)
-
- // Note: In TLS the certificates MUST be in order (and
- // optionally include the root certificate) so we're not
- // building the chain using LoadCertificate (it's faster)
-
- // Note: IIS doesn't seem to send the whole certificate chain
- // but only the server certificate :-( it's assuming that you
- // already have this chain installed on your computer. duh!
- // http://groups.google.ca/groups?q=IIS+server+certificate+chain&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=85058s%24avd%241%40nnrp1.deja.com&rnum=3
-
- // we must remove the leaf certificate from the chain
- X509CertificateCollection chain = new X509CertificateCollection (certificates);
- chain.Remove (leaf);
- X509Chain verify = new X509Chain (chain);
-
- bool result = false;
-
- try
- {
- result = verify.Build (leaf);
- }
- catch (Exception)
- {
- result = false;
- }
-
- if (!result)
- {
- switch (verify.Status)
- {
- case X509ChainStatusFlags.InvalidBasicConstraints:
- // WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
- errors.Add ((int)-2146869223);
- break;
-
- case X509ChainStatusFlags.NotSignatureValid:
- // WinError.h TRUST_E_BAD_DIGEST 0x80096010
- errors.Add ((int)-2146869232);
- break;
-
- case X509ChainStatusFlags.NotTimeNested:
- // WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
- errors.Add ((int)-2146762494);
- break;
-
- case X509ChainStatusFlags.NotTimeValid:
- // WinError.h CERT_E_EXPIRED 0x800B0101
- description = AlertDescription.CertificateExpired;
- errors.Add ((int)-2146762495);
- break;
-
- case X509ChainStatusFlags.PartialChain:
- // WinError.h CERT_E_CHAINING 0x800B010A
- description = AlertDescription.UnknownCA;
- errors.Add ((int)-2146762486);
- break;
-
- case X509ChainStatusFlags.UntrustedRoot:
- // WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
- description = AlertDescription.UnknownCA;
- errors.Add ((int)-2146762487);
- break;
-
- default:
- // unknown error
- description = AlertDescription.CertificateUnknown;
- errors.Add ((int)verify.Status);
- break;
- }
- }
-
- int[] certificateErrors = (int[])errors.ToArray(typeof(int));
-
- if (!context.SslStream.RaiseServerCertificateValidation(
- cert,
- certificateErrors))
- {
- throw new TlsException(
- description,
- "Invalid certificate received from server.");
- }
- }
-
- // RFC2818 - HTTP Over TLS, Section 3.1
- // http://www.ietf.org/rfc/rfc2818.txt
- //
- // 1. if present MUST use subjectAltName dNSName as identity
- // 1.1. if multiples entries a match of any one is acceptable
- // 1.2. wildcard * is acceptable
- // 2. URI may be an IP address -> subjectAltName.iPAddress
- // 2.1. exact match is required
- // 3. Use of the most specific Common Name (CN=) in the Subject
- // 3.1 Existing practice but DEPRECATED
- private bool checkServerIdentity (X509Certificate cert)
- {
- ClientContext context = (ClientContext)this.Context;
-
- string targetHost = context.ClientSettings.TargetHost;
-
- X509Extension ext = cert.Extensions ["2.5.29.17"];
- // 1. subjectAltName
- if (ext != null)
- {
- SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
- // 1.1 - multiple dNSName
- foreach (string dns in subjectAltName.DNSNames)
- {
- // 1.2 TODO - wildcard support
- if (Match (targetHost, dns))
- return true;
- }
- // 2. ipAddress
- foreach (string ip in subjectAltName.IPAddresses)
- {
- // 2.1. Exact match required
- if (ip == targetHost)
- return true;
- }
- }
- // 3. Common Name (CN=)
- return checkDomainName (cert.SubjectName);
- }
-
- private bool checkDomainName(string subjectName)
- {
- ClientContext context = (ClientContext)this.Context;
-
- string domainName = String.Empty;
- Regex search = new Regex(@"CN\s*=\s*([^,]*)");
-
- MatchCollection elements = search.Matches(subjectName);
-
- if (elements.Count == 1)
- {
- if (elements[0].Success)
- {
- domainName = elements[0].Groups[1].Value.ToString();
- }
- }
-
- return Match (context.ClientSettings.TargetHost, domainName);
- }
-
- // ensure the pattern is valid wrt to RFC2595 and RFC2818
- // http://www.ietf.org/rfc/rfc2595.txt
- // http://www.ietf.org/rfc/rfc2818.txt
- static bool Match (string hostname, string pattern)
- {
- // check if this is a pattern
- int index = pattern.IndexOf ('*');
- if (index == -1) {
- // not a pattern, do a direct case-insensitive comparison
- return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
- }
-
- // check pattern validity
- // A "*" wildcard character MAY be used as the left-most name component in the certificate.
-
- // unless this is the last char (valid)
- if (index != pattern.Length - 1) {
- // then the next char must be a dot .'.
- if (pattern [index + 1] != '.')
- return false;
- }
-
- // only one (A) wildcard is supported
- int i2 = pattern.IndexOf ('*', index + 1);
- if (i2 != -1)
- return false;
-
- // match the end of the pattern
- string end = pattern.Substring (index + 1);
- int length = hostname.Length - end.Length;
- // no point to check a pattern that is longer than the hostname
- if (length <= 0)
- return false;
-
- if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
- return false;
-
- // special case, we start with the wildcard
- if (index == 0) {
- // ensure we hostname non-matched part (start) doesn't contain a dot
- int i3 = hostname.IndexOf ('.');
- return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
- }
-
- // match the start of the pattern
- string start = pattern.Substring (0, index);
- return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs
deleted file mode 100644
index cedb565c923..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Text;
-using Mono.Security;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsServerCertificateRequest : HandshakeMessage
- {
- #region Fields
-
- private ClientCertificateType[] certificateTypes;
- private string[] distinguisedNames;
-
- #endregion
-
- #region Constructors
-
- public TlsServerCertificateRequest(Context context, byte[] buffer)
- : base(context, HandshakeType.CertificateRequest, buffer)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
-
- this.Context.ServerSettings.CertificateTypes = this.certificateTypes;
- this.Context.ServerSettings.DistinguisedNames = this.distinguisedNames;
- this.Context.ServerSettings.CertificateRequest = true;
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- // Read requested certificate types
- int typesCount = this.ReadByte();
-
- this.certificateTypes = new ClientCertificateType[typesCount];
-
- for (int i = 0; i < typesCount; i++)
- {
- this.certificateTypes[i] = (ClientCertificateType)this.ReadByte();
- }
-
- /*
- * Read requested certificate authorities (Distinguised Names)
- *
- * Name ::= SEQUENCE OF RelativeDistinguishedName
- *
- * RelativeDistinguishedName ::= SET OF AttributeValueAssertion
- *
- * AttributeValueAssertion ::= SEQUENCE {
- * attributeType OBJECT IDENTIFIER
- * attributeValue ANY }
- */
- if (this.ReadInt16() != 0)
- {
- ASN1 rdn = new ASN1(this.ReadBytes(this.ReadInt16()));
-
- distinguisedNames = new string[rdn.Count];
-
- for (int i = 0; i < rdn.Count; i++)
- {
- // element[0] = attributeType
- // element[1] = attributeValue
- ASN1 element = new ASN1(rdn[i].Value);
-
- distinguisedNames[i] = Encoding.UTF8.GetString(element[1].Value);
- }
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs
deleted file mode 100644
index f741f95a7da..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsServerFinished : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerFinished(Context context, byte[] buffer)
- : base(context, HandshakeType.Finished, buffer)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
-
- // Hahdshake is finished
- this.Context.HandshakeState = HandshakeState.Finished;
- }
-
- #endregion
-
- #region Protected Methods
-
- static private byte[] Ssl3Marker = new byte [4] { 0x53, 0x52, 0x56, 0x52 };
-
- protected override void ProcessAsSsl3()
- {
- // Compute handshake messages hashes
- HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
-
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- hash.TransformBlock (data, 0, data.Length, data, 0);
- hash.TransformBlock (Ssl3Marker, 0, Ssl3Marker.Length, Ssl3Marker, 0);
- // hack to avoid memory allocation
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- byte[] serverHash = this.ReadBytes((int)Length);
- byte[] clientHash = hash.Hash;
-
- // Check server prf against client prf
- if (!Compare (clientHash, serverHash))
- {
-// TODO: Review that selected alert is correct
- throw new TlsException(AlertDescription.InsuficientSecurity, "Invalid ServerFinished message received.");
- }
- }
-
- protected override void ProcessAsTls1()
- {
- byte[] serverPRF = this.ReadBytes((int)Length);
- HashAlgorithm hash = new MD5SHA1();
-
- // note: we could call HashAlgorithm.ComputeHash(Stream) but that would allocate (on Mono)
- // a 4096 bytes buffer to process the hash - which is bigger than HandshakeMessages
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- byte[] digest = hash.ComputeHash (data, 0, data.Length);
-
- byte[] clientPRF = this.Context.Current.Cipher.PRF(this.Context.MasterSecret, "server finished", digest, 12);
-
- // Check server prf against client prf
- if (!Compare (clientPRF, serverPRF))
- {
- throw new TlsException("Invalid ServerFinished message received.");
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs
deleted file mode 100644
index 0cbecb5f261..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs
+++ /dev/null
@@ -1,150 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsServerHello : HandshakeMessage
- {
- #region Fields
-
- private SecurityCompressionType compressionMethod;
- private byte[] random;
- private byte[] sessionId;
- private CipherSuite cipherSuite;
-
- #endregion
-
- #region Constructors
-
- public TlsServerHello(Context context, byte[] buffer)
- : base(context, HandshakeType.ServerHello, buffer)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
-
- this.Context.SessionId = this.sessionId;
- this.Context.ServerRandom = this.random;
- this.Context.Negotiating.Cipher = this.cipherSuite;
- this.Context.CompressionMethod = this.compressionMethod;
- this.Context.ProtocolNegotiated = true;
-
- DebugHelper.WriteLine("Selected Cipher Suite {0}", this.cipherSuite.Name);
- DebugHelper.WriteLine("Client random", this.Context.ClientRandom);
- DebugHelper.WriteLine("Server random", this.Context.ServerRandom);
-
- // Compute ClientRandom + ServerRandom
- int clen = this.Context.ClientRandom.Length;
- int slen = this.Context.ServerRandom.Length;
- int rlen = clen + slen;
- byte[] cs = new byte[rlen];
- Buffer.BlockCopy (this.Context.ClientRandom, 0, cs, 0, clen);
- Buffer.BlockCopy (this.Context.ServerRandom, 0, cs, clen, slen);
- this.Context.RandomCS = cs;
-
- // Server Random + Client Random
- byte[] sc = new byte[rlen];
- Buffer.BlockCopy (this.Context.ServerRandom, 0, sc, 0, slen);
- Buffer.BlockCopy (this.Context.ClientRandom, 0, sc, slen, clen);
- this.Context.RandomSC = sc;
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- // Read protocol version
- this.processProtocol(this.ReadInt16());
-
- // Read random - Unix time + Random bytes
- this.random = this.ReadBytes(32);
-
- // Read Session id
- int length = (int) ReadByte ();
- if (length > 0)
- {
- this.sessionId = this.ReadBytes(length);
- ClientSessionCache.Add (this.Context.ClientSettings.TargetHost, this.sessionId);
- this.Context.AbbreviatedHandshake = Compare (this.sessionId, this.Context.SessionId);
- }
- else
- {
- this.Context.AbbreviatedHandshake = false;
- }
-
- // Read cipher suite
- short cipherCode = this.ReadInt16();
- if (this.Context.SupportedCiphers.IndexOf(cipherCode) == -1)
- {
- // The server has sent an invalid ciphersuite
- throw new TlsException(AlertDescription.InsuficientSecurity, "Invalid cipher suite received from server");
- }
- this.cipherSuite = this.Context.SupportedCiphers[cipherCode];
-
- // Read compression methods ( always 0 )
- this.compressionMethod = (SecurityCompressionType)this.ReadByte();
- }
-
- #endregion
-
- #region Private Methods
-
- private void processProtocol(short protocol)
- {
- SecurityProtocolType serverProtocol = this.Context.DecodeProtocolCode(protocol);
-
- if ((serverProtocol & this.Context.SecurityProtocolFlags) == serverProtocol ||
- (this.Context.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
- {
- this.Context.SecurityProtocol = serverProtocol;
- this.Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (false, serverProtocol);
-
- DebugHelper.WriteLine("Selected protocol {0}", serverProtocol);
- }
- else
- {
- throw new TlsException(
- AlertDescription.ProtocolVersion,
- "Incorrect protocol version received from server");
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs
deleted file mode 100644
index 7a0e61fb5da..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsServerHelloDone : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerHelloDone(Context context, byte[] buffer)
- : base(context, HandshakeType.ServerHelloDone, buffer)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- }
-
- protected override void ProcessAsTls1()
- {
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs
deleted file mode 100644
index d6c8e513029..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-using Mono.Security.X509;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Client
-{
- internal class TlsServerKeyExchange : HandshakeMessage
- {
- #region Fields
-
- private RSAParameters rsaParams;
- private byte[] signedParams;
-
- #endregion
-
- #region Constructors
-
- public TlsServerKeyExchange(Context context, byte[] buffer)
- : base(context, HandshakeType.ServerKeyExchange, buffer)
- {
- this.verifySignature();
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
-
- this.Context.ServerSettings.ServerKeyExchange = true;
- this.Context.ServerSettings.RsaParameters = this.rsaParams;
- this.Context.ServerSettings.SignedParams = this.signedParams;
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- this.rsaParams = new RSAParameters();
-
- // Read modulus
- this.rsaParams.Modulus = this.ReadBytes(this.ReadInt16());
-
- // Read exponent
- this.rsaParams.Exponent = this.ReadBytes(this.ReadInt16());
-
- // Read signed params
- this.signedParams = this.ReadBytes(this.ReadInt16());
- }
-
- #endregion
-
- #region Private Methods
-
- private void verifySignature()
- {
- MD5SHA1 hash = new MD5SHA1();
-
- // Calculate size of server params
- int size = rsaParams.Modulus.Length + rsaParams.Exponent.Length + 4;
-
- // Create server params array
- TlsStream stream = new TlsStream();
-
- stream.Write(this.Context.RandomCS);
- stream.Write(this.ToArray(), 0, size);
-
- hash.ComputeHash(stream.ToArray());
-
- stream.Reset();
-
- bool isValidSignature = hash.VerifySignature(
- this.Context.ServerSettings.CertificateRSA,
- this.signedParams);
-
- if (!isValidSignature)
- {
- throw new TlsException(
- AlertDescription.DecodeError,
- "Data was not signed with the server certificate.");
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs
deleted file mode 100644
index 6ef5db41018..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs
+++ /dev/null
@@ -1,276 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using SSCX = System.Security.Cryptography.X509Certificates;
-using Mono.Security.X509;
-using Mono.Security.X509.Extensions;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsClientCertificate : HandshakeMessage
- {
- #region Fields
-
- private X509CertificateCollection clientCertificates;
-
- #endregion
-
- #region Constructors
-
- public TlsClientCertificate(Context context, byte[] buffer)
- : base(context, HandshakeType.Certificate, buffer)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- foreach (X509Certificate certificate in clientCertificates) {
- this.Context.ClientSettings.Certificates.Add (new SSCX.X509Certificate (certificate.RawData));
- }
- }
-
- public bool HasCertificate {
- get { return clientCertificates.Count > 0; }
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- int bytesRead = 0;
- int length = this.ReadInt24 ();
- this.clientCertificates = new X509CertificateCollection ();
- while (length > bytesRead) {
- int certLength = this.ReadInt24 ();
- bytesRead += certLength + 3;
- byte[] cert = this.ReadBytes (certLength);
- this.clientCertificates.Add (new X509Certificate (cert));
- }
-
- if (this.clientCertificates.Count > 0)
- {
- this.validateCertificates (this.clientCertificates);
- }
- else if ((this.Context as ServerContext).ClientCertificateRequired)
- {
- throw new TlsException (AlertDescription.NoCertificate);
- }
- }
-
- #endregion
-
- #region Private Methods
-
- private bool checkCertificateUsage (X509Certificate cert)
- {
- ServerContext context = (ServerContext)this.Context;
-
- // certificate extensions are required for this
- // we "must" accept older certificates without proofs
- if (cert.Version < 3)
- return true;
-
- KeyUsages ku = KeyUsages.none;
- switch (context.Negotiating.Cipher.ExchangeAlgorithmType)
- {
- case ExchangeAlgorithmType.RsaSign:
- case ExchangeAlgorithmType.RsaKeyX:
- ku = KeyUsages.digitalSignature;
- break;
- case ExchangeAlgorithmType.DiffieHellman:
- ku = KeyUsages.keyAgreement;
- break;
- case ExchangeAlgorithmType.Fortezza:
- return false; // unsupported certificate type
- }
-
- KeyUsageExtension kux = null;
- ExtendedKeyUsageExtension eku = null;
-
- X509Extension xtn = cert.Extensions["2.5.29.15"];
- if (xtn != null)
- kux = new KeyUsageExtension (xtn);
-
- xtn = cert.Extensions["2.5.29.37"];
- if (xtn != null)
- eku = new ExtendedKeyUsageExtension (xtn);
-
- if ((kux != null) && (eku != null))
- {
- // RFC3280 states that when both KeyUsageExtension and
- // ExtendedKeyUsageExtension are present then BOTH should
- // be valid
- return (kux.Support (ku) &&
- eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.2"));
- }
- else if (kux != null)
- {
- return kux.Support (ku);
- }
- else if (eku != null)
- {
- // Client Authentication (1.3.6.1.5.5.7.3.2)
- return eku.KeyPurpose.Contains ("1.3.6.1.5.5.7.3.2");
- }
-
- // last chance - try with older (deprecated) Netscape extensions
- xtn = cert.Extensions["2.16.840.1.113730.1.1"];
- if (xtn != null)
- {
- NetscapeCertTypeExtension ct = new NetscapeCertTypeExtension (xtn);
- return ct.Support (NetscapeCertTypeExtension.CertTypes.SslClient);
- }
-
- // certificate isn't valid for SSL server usage
- return false;
- }
-
- private void validateCertificates (X509CertificateCollection certificates)
- {
- ServerContext context = (ServerContext)this.Context;
- AlertDescription description = AlertDescription.BadCertificate;
- SSCX.X509Certificate client = null;
- int[] certificateErrors = null;
-
- // note: certificate may be null is no certificate is sent
- // (e.g. optional mutual authentication)
- if (certificates.Count > 0) {
- X509Certificate leaf = certificates[0];
-
- ArrayList errors = new ArrayList ();
-
- // SSL specific check - not all certificates can be
- // used to server-side SSL some rules applies after
- // all ;-)
- if (!checkCertificateUsage (leaf))
- {
- // WinError.h CERT_E_PURPOSE 0x800B0106
- errors.Add ((int)-2146762490);
- }
-
- X509Chain verify;
- // was a chain supplied ? if so use it, if not
- if (certificates.Count > 1) {
- // if so use it (and don't build our own)
- X509CertificateCollection chain = new X509CertificateCollection (certificates);
- chain.Remove (leaf);
- verify = new X509Chain (chain);
- } else {
- // if not, then let's build our own (based on what's available in the stores)
- verify = new X509Chain ();
- }
-
- bool result = false;
-
- try
- {
- result = verify.Build (leaf);
- }
- catch (Exception)
- {
- result = false;
- }
-
- if (!result)
- {
- switch (verify.Status)
- {
- case X509ChainStatusFlags.InvalidBasicConstraints:
- // WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
- errors.Add ((int)-2146869223);
- break;
-
- case X509ChainStatusFlags.NotSignatureValid:
- // WinError.h TRUST_E_BAD_DIGEST 0x80096010
- errors.Add ((int)-2146869232);
- break;
-
- case X509ChainStatusFlags.NotTimeNested:
- // WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
- errors.Add ((int)-2146762494);
- break;
-
- case X509ChainStatusFlags.NotTimeValid:
- // WinError.h CERT_E_EXPIRED 0x800B0101
- description = AlertDescription.CertificateExpired;
- errors.Add ((int)-2146762495);
- break;
-
- case X509ChainStatusFlags.PartialChain:
- // WinError.h CERT_E_CHAINING 0x800B010A
- description = AlertDescription.UnknownCA;
- errors.Add ((int)-2146762486);
- break;
-
- case X509ChainStatusFlags.UntrustedRoot:
- // WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
- description = AlertDescription.UnknownCA;
- errors.Add ((int)-2146762487);
- break;
-
- default:
- // unknown error
- description = AlertDescription.CertificateUnknown;
- errors.Add ((int)verify.Status);
- break;
- }
- }
- client = new SSCX.X509Certificate (leaf.RawData);
- certificateErrors = (int[])errors.ToArray (typeof (int));
- }
- else
- {
- certificateErrors = new int[0];
- }
-
- SSCX.X509CertificateCollection certCollection = new SSCX.X509CertificateCollection ();
- foreach (X509Certificate certificate in certificates) {
- certCollection.Add (new SSCX.X509Certificate (certificate.RawData));
- }
- if (!context.SslStream.RaiseClientCertificateValidation(client, certificateErrors))
- {
- throw new TlsException (
- description,
- "Invalid certificate received from client.");
- }
-
- this.Context.ClientSettings.ClientCertificate = client;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs
deleted file mode 100644
index 20a69edbbda..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography.X509Certificates;
-
-using System.Security.Cryptography;
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsClientCertificateVerify : HandshakeMessage
- {
- #region Constructors
-
- public TlsClientCertificateVerify(Context context, byte[] buffer)
- : base(context, HandshakeType.CertificateVerify, buffer)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- ServerContext context = (ServerContext)this.Context;
- int length = this.ReadInt16 ();
- byte[] signature = this.ReadBytes (length);
-
- // Verify signature
- SslHandshakeHash hash = new SslHandshakeHash(context.MasterSecret);
- hash.TransformFinalBlock(
- context.HandshakeMessages.ToArray(),
- 0,
- (int)context.HandshakeMessages.Length);
-
- if (!hash.VerifySignature(context.ClientSettings.CertificateRSA, signature))
- {
- throw new TlsException(AlertDescription.HandshakeFailiure, "Handshake Failure.");
- }
- }
-
- protected override void ProcessAsTls1()
- {
- ServerContext context = (ServerContext)this.Context;
- int length = this.ReadInt16 ();
- byte[] signature = this.ReadBytes (length);
-
- // Verify signature
- MD5SHA1 hash = new MD5SHA1();
- hash.ComputeHash(
- context.HandshakeMessages.ToArray(),
- 0,
- (int)context.HandshakeMessages.Length);
-
- if (!hash.VerifySignature(context.ClientSettings.CertificateRSA, signature))
- {
- throw new TlsException (AlertDescription.HandshakeFailiure, "Handshake Failure.");
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs
deleted file mode 100644
index 26eaad9a311..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsClientFinished : HandshakeMessage
- {
- #region Constructors
-
- public TlsClientFinished(Context context, byte[] buffer)
- : base(context, HandshakeType.Finished, buffer)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- // Compute handshake messages hashes
- HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
-
- TlsStream data = new TlsStream();
- data.Write(this.Context.HandshakeMessages.ToArray());
- data.Write((int)0x434C4E54);
-
- hash.TransformFinalBlock(data.ToArray(), 0, (int)data.Length);
-
- data.Reset();
-
- byte[] clientHash = this.ReadBytes((int)Length);
- byte[] serverHash = hash.Hash;
-
- // Check client prf against server prf
- if (!Compare (clientHash, serverHash))
- {
- throw new TlsException(AlertDescription.DecryptError, "Decrypt error.");
- }
- }
-
- protected override void ProcessAsTls1()
- {
- byte[] clientPRF = this.ReadBytes((int)this.Length);
- HashAlgorithm hash = new MD5SHA1();
-
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- byte[] digest = hash.ComputeHash (data, 0, data.Length);
-
- byte[] serverPRF = this.Context.Current.Cipher.PRF(
- this.Context.MasterSecret, "client finished", digest, 12);
-
- // Check client prf against server prf
- if (!Compare (clientPRF, serverPRF))
- {
- throw new TlsException(AlertDescription.DecryptError, "Decrypt error.");
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs
deleted file mode 100644
index 1172626f3c1..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs
+++ /dev/null
@@ -1,152 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsClientHello : HandshakeMessage
- {
- #region Private Fields
-
- private byte[] random;
- private byte[] sessionId;
- private short[] cipherSuites;
- private byte[] compressionMethods;
-
- #endregion
-
- #region Constructors
-
- public TlsClientHello(Context context, byte[] buffer)
- : base(context, HandshakeType.ClientHello, buffer)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
-
- this.selectCipherSuite();
- this.selectCompressionMethod();
-
- this.Context.SessionId = this.sessionId;
- this.Context.ClientRandom = this.random;
- this.Context.ProtocolNegotiated = true;
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- // Client Version
- this.processProtocol(this.ReadInt16());
-
- // Random bytes - Unix time + Radom bytes [28]
- this.random = this.ReadBytes(32);
-
- // Session id
- // Send the session ID empty
- this.sessionId = this.ReadBytes(this.ReadByte());
-
- // Read Supported Cipher Suites count
- this.cipherSuites = new short[this.ReadInt16()/2];
-
- // Read Cipher Suites
- for (int i = 0; i < this.cipherSuites.Length; i++)
- {
- this.cipherSuites[i] = this.ReadInt16();
- }
-
- // Compression methods length
- this.compressionMethods = new byte[this.ReadByte()];
-
- for (int i = 0; i < this.compressionMethods.Length; i++)
- {
- this.compressionMethods[i] = this.ReadByte();
- }
- }
-
- #endregion
-
- #region Private Methods
-
- private void processProtocol(short protocol)
- {
- // a server MUST reply with the hight version supported (`true` for fallback)
- // so a TLS 1.2 client (like Google Chrome) will be returned that the server uses TLS 1.0
- // instead of an alert about the protocol
- SecurityProtocolType clientProtocol = Context.DecodeProtocolCode (protocol, true);
-
- if ((clientProtocol & this.Context.SecurityProtocolFlags) == clientProtocol ||
- (this.Context.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
- {
- this.Context.SecurityProtocol = clientProtocol;
- this.Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (true, clientProtocol);
- }
- else
- {
- throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server");
- }
- }
-
- private void selectCipherSuite()
- {
- int index = 0;
-
- for (int i = 0; i < this.cipherSuites.Length; i++)
- {
- if ((index = this.Context.SupportedCiphers.IndexOf(this.cipherSuites[i])) != -1)
- {
- this.Context.Negotiating.Cipher = this.Context.SupportedCiphers[index];
- break;
- }
- }
-
- if (this.Context.Negotiating.Cipher == null)
- {
- throw new TlsException(AlertDescription.InsuficientSecurity, "Insuficient Security");
- }
- }
-
- private void selectCompressionMethod()
- {
- this.Context.CompressionMethod = SecurityCompressionType.None;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs
deleted file mode 100644
index ceeb39ad468..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsClientKeyExchange : HandshakeMessage
- {
- #region Constructors
-
- public TlsClientKeyExchange(Context context, byte[] buffer) :
- base(context,
- HandshakeType.ClientKeyExchange,
- buffer)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- AsymmetricAlgorithm privKey = null;
- ServerContext context = (ServerContext)this.Context;
-
- // Select the private key information
- privKey = context.SslStream.RaisePrivateKeySelection(
- new X509Certificate(context.ServerSettings.Certificates[0].RawData),
- null);
-
- if (privKey == null)
- {
- throw new TlsException(AlertDescription.UserCancelled, "Server certificate Private Key unavailable.");
- }
-
- // Read client premaster secret
- byte[] clientSecret = this.ReadBytes((int)this.Length);
-
- // Decrypt premaster secret
- RSAPKCS1KeyExchangeDeformatter deformatter = new RSAPKCS1KeyExchangeDeformatter(privKey);
-
- byte[] preMasterSecret = deformatter.DecryptKeyExchange(clientSecret);
-
- // Create master secret
- this.Context.Negotiating.Cipher.ComputeMasterSecret(preMasterSecret);
-
- // Create keys
- this.Context.Negotiating.Cipher.ComputeKeys ();
-
- // Initialize Cipher Suite
- this.Context.Negotiating.Cipher.InitializeCipher ();
- }
-
- protected override void ProcessAsTls1()
- {
- AsymmetricAlgorithm privKey = null;
- ServerContext context = (ServerContext)this.Context;
-
- // Select the private key information
- // Select the private key information
- privKey = context.SslStream.RaisePrivateKeySelection(
- new X509Certificate(context.ServerSettings.Certificates[0].RawData),
- null);
-
- if (privKey == null)
- {
- throw new TlsException(AlertDescription.UserCancelled, "Server certificate Private Key unavailable.");
- }
-
- // Read client premaster secret
- byte[] clientSecret = this.ReadBytes(this.ReadInt16());
-
- // Decrypt premaster secret
- RSAPKCS1KeyExchangeDeformatter deformatter = new RSAPKCS1KeyExchangeDeformatter(privKey);
-
- byte[] preMasterSecret = deformatter.DecryptKeyExchange(clientSecret);
-
- // Create master secret
- this.Context.Negotiating.Cipher.ComputeMasterSecret(preMasterSecret);
-
- // Create keys
- this.Context.Negotiating.Cipher.ComputeKeys();
-
- // Initialize Cipher Suite
- this.Context.Negotiating.Cipher.InitializeCipher();
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs
deleted file mode 100644
index 7475d2d1e64..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using System.Text.RegularExpressions;
-using System.Security.Cryptography;
-using X509Cert = System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.X509;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsServerCertificate : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerCertificate(Context context)
- : base(context, HandshakeType.Certificate)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- TlsStream certs = new TlsStream();
-
- foreach (X509Certificate certificate in this.Context.ServerSettings.Certificates)
- {
- // Write certificate length
- certs.WriteInt24(certificate.RawData.Length);
-
- // Write certificate data
- certs.Write(certificate.RawData);
- }
-
- this.WriteInt24(Convert.ToInt32(certs.Length));
- this.Write(certs.ToArray());
-
- certs.Close();
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs
deleted file mode 100644
index 40274a6200c..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Text;
-using Mono.Security;
-using Mono.Security.X509;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsServerCertificateRequest : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerCertificateRequest(Context context)
- : base(context, HandshakeType.CertificateRequest)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- ServerContext context = (ServerContext)this.Context;
-
- int count = context.ServerSettings.CertificateTypes.Length;
-
- this.WriteByte(Convert.ToByte(count));
-
- // Write requested certificate types
- for (int i = 0; i < count; i++)
- {
- this.WriteByte((byte)context.ServerSettings.CertificateTypes[i]);
- }
-
- /*
- * Write requested certificate authorities (Distinguised Names)
- *
- * Name ::= SEQUENCE OF RelativeDistinguishedName
- *
- * RelativeDistinguishedName ::= SET OF AttributeValueAssertion
- *
- * AttributeValueAssertion ::= SEQUENCE {
- * attributeType OBJECT IDENTIFIER
- * attributeValue ANY }
- */
-
- /*
- * From RFC 5246:
- * If the certificate_authorities list is empty, then the client MAY
- * send any certificate of the appropriate ClientCertificateType,
- * unless there is some external arrangement to the contrary.
- *
- * Better let the client choose which certificate instead of sending down
- * a potentially large list of DNs.
-
- if (context.ServerSettings.DistinguisedNames.Length > 0)
- {
- TlsStream list = new TlsStream ();
- // this is the worst formating ever :-|
- foreach (string dn in context.ServerSettings.DistinguisedNames)
- {
- byte[] name = X501.FromString (dn).GetBytes ();
- list.Write ((short)name.Length);
- list.Write (name);
- }
- this.Write ((short)list.Length);
- this.Write (list.ToArray ());
- }
- else
- {
- */
- this.Write ((short)0);
- //}
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs
deleted file mode 100644
index 91311506cf2..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsServerFinished : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerFinished(Context context)
- : base(context, HandshakeType.Finished)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- static private byte[] Ssl3Marker = new byte [4] { 0x53, 0x52, 0x56, 0x52 };
-
- protected override void ProcessAsSsl3()
- {
- // Compute handshake messages hashes
- HashAlgorithm hash = new SslHandshakeHash(this.Context.MasterSecret);
-
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- hash.TransformBlock (data, 0, data.Length, data, 0);
- hash.TransformBlock (Ssl3Marker, 0, Ssl3Marker.Length, Ssl3Marker, 0);
- // hack to avoid memory allocation
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- this.Write(hash.Hash);
- }
-
- protected override void ProcessAsTls1()
- {
- // Compute handshake messages hash
- HashAlgorithm hash = new MD5SHA1();
- byte[] data = this.Context.HandshakeMessages.ToArray ();
- byte[] digest = hash.ComputeHash (data, 0, data.Length);
-
- // Write message
- this.Write(this.Context.Current.Cipher.PRF(
- this.Context.MasterSecret, "server finished", digest, 12));
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs
deleted file mode 100644
index c02c24c57a2..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsServerHello : HandshakeMessage
- {
- #region Private Fields
-
- private int unixTime;
- private byte[] random;
-
- #endregion
-
- #region Constructors
-
- public TlsServerHello(Context context)
- : base(context, HandshakeType.ServerHello)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- base.Update();
-
- TlsStream random = new TlsStream();
-
- // Compute Server Random
- random.Write(this.unixTime);
- random.Write(this.random);
-
- this.Context.ServerRandom = random.ToArray();
-
- // Compute ClientRandom + ServerRandom
- random.Reset();
- random.Write(this.Context.ClientRandom);
- random.Write(this.Context.ServerRandom);
-
- this.Context.RandomCS = random.ToArray();
-
- // Server Random + Client Random
- random.Reset();
- random.Write(this.Context.ServerRandom);
- random.Write(this.Context.ClientRandom);
-
- this.Context.RandomSC = random.ToArray();
-
- random.Reset();
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- // Write protocol version
- this.Write(this.Context.Protocol);
-
- // Write Unix time
- this.unixTime = this.Context.GetUnixTime();
- this.Write(this.unixTime);
-
- // Write Random bytes
- random = this.Context.GetSecureRandomBytes(28);
- this.Write(this.random);
-
- if (this.Context.SessionId == null)
- {
- this.WriteByte(0);
- }
- else
- {
- // Write Session ID length
- this.WriteByte((byte)this.Context.SessionId.Length);
-
- // Write Session ID
- this.Write(this.Context.SessionId);
- }
-
- // Write selected cipher suite
- this.Write(this.Context.Negotiating.Cipher.Code);
-
- // Write selected compression method
- this.WriteByte((byte)this.Context.CompressionMethod);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs
deleted file mode 100644
index 1ce467c0625..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsServerHelloDone : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerHelloDone(Context context)
- : base(context, HandshakeType.ServerHelloDone)
- {
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- }
-
- protected override void ProcessAsTls1()
- {
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs
deleted file mode 100644
index 8a2d03382a7..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using SX509 = System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.Cryptography;
-using Mono.Security.X509;
-
-namespace Mono.Security.Protocol.Tls.Handshake.Server
-{
- internal class TlsServerKeyExchange : HandshakeMessage
- {
- #region Constructors
-
- public TlsServerKeyExchange(Context context)
- : base(context, HandshakeType.ServerKeyExchange)
- {
- }
-
- #endregion
-
- #region Methods
-
- public override void Update()
- {
- throw new NotSupportedException();
- }
-
- #endregion
-
- #region Protected Methods
-
- protected override void ProcessAsSsl3()
- {
- this.ProcessAsTls1();
- }
-
- protected override void ProcessAsTls1()
- {
- ServerContext context = (ServerContext)this.Context;
-
- // Select the private key information
- RSA rsa = (RSA)context.SslStream.PrivateKeyCertSelectionDelegate(
- new SX509.X509Certificate(context.ServerSettings.Certificates[0].RawData),
- null);
-
- RSAParameters rsaParams = rsa.ExportParameters(false);
-
- // Write Modulus
- this.WriteInt24(rsaParams.Modulus.Length);
- this.Write(rsaParams.Modulus, 0, rsaParams.Modulus.Length);
-
- // Write exponent
- this.WriteInt24(rsaParams.Exponent.Length);
- this.Write(rsaParams.Exponent, 0, rsaParams.Exponent.Length);
-
- // Write signed params
- byte[] signature = this.createSignature(rsa, this.ToArray());
- this.WriteInt24(signature.Length);
- this.Write(signature);
- }
-
- #endregion
-
- #region Private Methods
-
- private byte[] createSignature(RSA rsa, byte[] buffer)
- {
- MD5SHA1 hash = new MD5SHA1();
-
- // Create server params array
- TlsStream stream = new TlsStream();
-
- stream.Write(this.Context.RandomCS);
- stream.Write(buffer, 0, buffer.Length);
-
- hash.ComputeHash(stream.ToArray());
-
- stream.Reset();
-
- return hash.CreateSignature(rsa);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs
deleted file mode 100644
index 8bff7127910..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake
-{
- [Serializable]
- internal enum ClientCertificateType
- {
- RSA = 1,
- DSS = 2,
- RSAFixed = 3,
- DSSFixed = 4,
- Unknown = 255
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs
deleted file mode 100644
index 54071274165..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs
+++ /dev/null
@@ -1,170 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake
-{
- internal abstract class HandshakeMessage : TlsStream
- {
- #region Fields
-
- private Context context;
- private HandshakeType handshakeType;
- private ContentType contentType;
- private byte[] cache;
-
- #endregion
-
- #region Properties
-
- public Context Context
- {
- get { return this.context; }
- }
-
- public HandshakeType HandshakeType
- {
- get { return this.handshakeType; }
- }
-
- public ContentType ContentType
- {
- get { return this.contentType; }
- }
-
- #endregion
-
- #region Constructors
-
- public HandshakeMessage(
- Context context,
- HandshakeType handshakeType)
- : this(context, handshakeType, ContentType.Handshake)
- {
- }
-
- public HandshakeMessage(
- Context context,
- HandshakeType handshakeType,
- ContentType contentType) : base()
- {
- this.context = context;
- this.handshakeType = handshakeType;
- this.contentType = contentType;
- }
-
- public HandshakeMessage(
- Context context,
- HandshakeType handshakeType,
- byte[] data) : base(data)
- {
- this.context = context;
- this.handshakeType = handshakeType;
- }
-
- #endregion
-
- #region Abstract Methods
-
- protected abstract void ProcessAsTls1();
-
- protected abstract void ProcessAsSsl3();
-
- #endregion
-
- #region Methods
-
- public void Process()
- {
- switch (this.Context.SecurityProtocol)
- {
- case SecurityProtocolType.Tls:
- case SecurityProtocolType.Default:
- this.ProcessAsTls1();
- break;
-
- case SecurityProtocolType.Ssl3:
- this.ProcessAsSsl3();
- break;
-
- case SecurityProtocolType.Ssl2:
- default:
- throw new NotSupportedException("Unsupported security protocol type");
- }
- }
-
- public virtual void Update()
- {
- if (this.CanWrite)
- {
- // result may (should) be available from a previous call to EncodeMessage
- if (cache == null)
- cache = this.EncodeMessage ();
- this.context.HandshakeMessages.Write (cache);
- this.Reset();
- cache = null;
- }
- }
-
- public virtual byte[] EncodeMessage()
- {
- cache = null;
-
- if (CanWrite)
- {
- byte[] hs = this.ToArray ();
- int len = hs.Length;
- cache = new byte[4 + len];
-
- cache[0] = (byte) HandshakeType;
- // Length as an Int24 in Network Order
- cache[1] = (byte) (len >> 16);
- cache[2] = (byte) (len >> 8);
- cache[3] = (byte) len;
- Buffer.BlockCopy (hs, 0, cache, 4, len);
- }
-
- return cache;
- }
-
- static public bool Compare (byte[] buffer1, byte[] buffer2)
- {
- // in our case both null can't exist (or be valid)
- if ((buffer1 == null) || (buffer2 == null))
- return false;
-
- if (buffer1.Length != buffer2.Length)
- return false;
-
- for (int i = 0; i < buffer1.Length; i++) {
- if (buffer1[i] != buffer2[i])
- return false;
- }
- return true;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs
deleted file mode 100644
index a0165a3c619..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls.Handshake
-{
- [Serializable]
- internal enum HandshakeType : byte
- {
- HelloRequest = 0,
- ClientHello = 1,
- ServerHello = 2,
- Certificate = 11,
- ServerKeyExchange = 12,
- CertificateRequest = 13,
- ServerHelloDone = 14,
- CertificateVerify = 15,
- ClientKeyExchange = 16,
- Finished = 20,
- None = 255
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Alert.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Alert.cs
deleted file mode 100644
index 62ac7b9f293..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Alert.cs
+++ /dev/null
@@ -1,265 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
- #region Enumerations
-
- [Serializable]
- internal enum AlertLevel : byte
- {
- Warning = 1,
- Fatal = 2
- }
-
- [Serializable]
- internal enum AlertDescription : byte
- {
- CloseNotify = 0,
- UnexpectedMessage = 10,
- BadRecordMAC = 20,
- DecryptionFailed = 21,
- RecordOverflow = 22,
- DecompressionFailiure = 30,
- HandshakeFailiure = 40,
- NoCertificate = 41, // should be used in SSL3
- BadCertificate = 42,
- UnsupportedCertificate = 43,
- CertificateRevoked = 44,
- CertificateExpired = 45,
- CertificateUnknown = 46,
- IlegalParameter = 47,
- UnknownCA = 48,
- AccessDenied = 49,
- DecodeError = 50,
- DecryptError = 51,
- ExportRestriction = 60,
- ProtocolVersion = 70,
- InsuficientSecurity = 71,
- InternalError = 80,
- UserCancelled = 90,
- NoRenegotiation = 100
- }
-
- #endregion
-
- internal class Alert
- {
- #region Fields
-
- private AlertLevel level;
- private AlertDescription description;
-
- #endregion
-
- #region Properties
-
- public AlertLevel Level
- {
- get { return this.level; }
- }
-
- public AlertDescription Description
- {
- get { return this.description; }
- }
-
- public string Message
- {
- get { return Alert.GetAlertMessage(this.description); }
- }
-
- public bool IsWarning
- {
- get { return this.level == AlertLevel.Warning ? true : false; }
- }
-
- /*
- public bool IsFatal
- {
- get { return this.level == AlertLevel.Fatal ? true : false; }
- }
- */
-
- public bool IsCloseNotify
- {
- get
- {
- if (this.IsWarning &&
- this.description == AlertDescription.CloseNotify)
- {
- return true;
- }
-
- return false;
- }
- }
-
- #endregion
-
- #region Constructors
-
- public Alert(AlertDescription description)
- {
- this.description = description;
- this.level = inferAlertLevel(description);
- }
-
- public Alert(
- AlertLevel level,
- AlertDescription description)
- {
- this.level = level;
- this.description = description;
- }
-
- #endregion
-
- #region Private Methods
-
- private static AlertLevel inferAlertLevel(AlertDescription description)
- {
- switch (description)
- {
- case AlertDescription.CloseNotify:
- case AlertDescription.NoRenegotiation:
- case AlertDescription.UserCancelled:
- return AlertLevel.Warning;
-
- case AlertDescription.AccessDenied:
- case AlertDescription.BadCertificate:
- case AlertDescription.BadRecordMAC:
- case AlertDescription.CertificateExpired:
- case AlertDescription.CertificateRevoked:
- case AlertDescription.CertificateUnknown:
- case AlertDescription.DecodeError:
- case AlertDescription.DecompressionFailiure:
- case AlertDescription.DecryptError:
- case AlertDescription.DecryptionFailed:
- case AlertDescription.ExportRestriction:
- case AlertDescription.HandshakeFailiure:
- case AlertDescription.IlegalParameter:
- case AlertDescription.InsuficientSecurity:
- case AlertDescription.InternalError:
- case AlertDescription.ProtocolVersion:
- case AlertDescription.RecordOverflow:
- case AlertDescription.UnexpectedMessage:
- case AlertDescription.UnknownCA:
- case AlertDescription.UnsupportedCertificate:
- default:
- return AlertLevel.Fatal;
- }
- }
-
- #endregion
-
- #region Static Methods
-
- public static string GetAlertMessage(AlertDescription description)
- {
- #if (DEBUG)
- switch (description)
- {
- case AlertDescription.AccessDenied:
- return "An inappropriate message was received.";
-
- case AlertDescription.BadCertificate:
- return "TLSCiphertext decrypted in an invalid way.";
-
- case AlertDescription.BadRecordMAC:
- return "Record with an incorrect MAC.";
-
- case AlertDescription.CertificateExpired:
- return "Certificate has expired or is not currently valid";
-
- case AlertDescription.CertificateRevoked:
- return "Certificate was revoked by its signer.";
-
- case AlertDescription.CertificateUnknown:
- return "Certificate Unknown.";
-
- case AlertDescription.CloseNotify:
- return "Connection closed";
-
- case AlertDescription.DecodeError:
- return "A message could not be decoded because some field was out of the specified range or the length of the message was incorrect.";
-
- case AlertDescription.DecompressionFailiure:
- return "The decompression function received improper input (e.g. data that would expand to excessive length).";
-
- case AlertDescription.DecryptError:
- return "TLSCiphertext decrypted in an invalid way: either it wasn`t an even multiple of the block length or its padding values, when checked, weren`t correct.";
-
- case AlertDescription.DecryptionFailed:
- return "Handshake cryptographic operation failed, including being unable to correctly verify a signature, decrypt a key exchange, or validate finished message.";
-
- case AlertDescription.ExportRestriction:
- return "Negotiation not in compliance with export restrictions was detected.";
-
- case AlertDescription.HandshakeFailiure:
- return "Unable to negotiate an acceptable set of security parameters given the options available.";
-
- case AlertDescription.IlegalParameter:
- return "A field in the handshake was out of range or inconsistent with other fields.";
-
- case AlertDescription.InsuficientSecurity:
- return "Negotiation has failed specifically because the server requires ciphers more secure than those supported by the client.";
-
- case AlertDescription.InternalError:
- return "Internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue.";
-
- case AlertDescription.NoRenegotiation:
- return "Invalid renegotiation.";
-
- case AlertDescription.ProtocolVersion:
- return "Unsupported protocol version.";
-
- case AlertDescription.RecordOverflow:
- return "Invalid length on TLSCiphertext record or TLSCompressed record.";
-
- case AlertDescription.UnexpectedMessage:
- return "Invalid message received.";
-
- case AlertDescription.UnknownCA:
- return "CA can't be identified as a trusted CA.";
-
- case AlertDescription.UnsupportedCertificate:
- return "Certificate was of an unsupported type.";
-
- case AlertDescription.UserCancelled:
- return "Handshake cancelled by user.";
-
- default:
- return "";
- }
- #else
- return "The authentication or decryption has failed.";
- #endif
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherAlgorithmType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherAlgorithmType.cs
deleted file mode 100644
index b58cc2c785e..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherAlgorithmType.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
-#if INSIDE_SYSTEM
- internal
-#else
- [Serializable]
- public
-#endif
- enum CipherAlgorithmType
- {
- Des,
- None,
- Rc2,
- Rc4,
- Rijndael,
- SkipJack,
- TripleDes
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
deleted file mode 100644
index 91d8034467b..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuite.cs
+++ /dev/null
@@ -1,594 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Text;
-using System.Security.Cryptography;
-
-using Mono.Security;
-using Mono.Security.Cryptography;
-using M = Mono.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal abstract class CipherSuite
- {
- #region Static Fields
-
- public static byte[] EmptyArray = new byte[0];
-
- #endregion
-
- #region Fields
-
- private short code;
- private string name;
- private CipherAlgorithmType cipherAlgorithmType;
- private HashAlgorithmType hashAlgorithmType;
- private ExchangeAlgorithmType exchangeAlgorithmType;
- private bool isExportable;
- private CipherMode cipherMode;
- private byte keyMaterialSize;
- private int keyBlockSize;
- private byte expandedKeyMaterialSize;
- private short effectiveKeyBits;
- private byte ivSize;
- private byte blockSize;
- private Context context;
- private SymmetricAlgorithm encryptionAlgorithm;
- private ICryptoTransform encryptionCipher;
- private SymmetricAlgorithm decryptionAlgorithm;
- private ICryptoTransform decryptionCipher;
- private KeyedHashAlgorithm clientHMAC;
- private KeyedHashAlgorithm serverHMAC;
-
- #endregion
-
- #region Protected Properties
-
- protected ICryptoTransform EncryptionCipher
- {
- get { return this.encryptionCipher; }
- }
-
- protected ICryptoTransform DecryptionCipher
- {
- get { return this.decryptionCipher; }
- }
-
- protected KeyedHashAlgorithm ClientHMAC
- {
- get { return this.clientHMAC; }
- }
-
- protected KeyedHashAlgorithm ServerHMAC
- {
- get { return this.serverHMAC; }
- }
-
- #endregion
-
- #region Properties
-
- public CipherAlgorithmType CipherAlgorithmType
- {
- get { return this.cipherAlgorithmType; }
- }
-
- public string HashAlgorithmName
- {
- get
- {
- switch (this.hashAlgorithmType)
- {
- case HashAlgorithmType.Md5:
- return "MD5";
-
- case HashAlgorithmType.Sha1:
- return "SHA1";
-
- default:
- return "None";
- }
- }
- }
-
- internal HashAlgorithm CreateHashAlgorithm ()
- {
- switch (hashAlgorithmType) {
- case HashAlgorithmType.Md5:
- return MD5.Create ();
- case HashAlgorithmType.Sha1:
- return SHA1.Create ();
- default:
- return null;
- }
- }
-
- public HashAlgorithmType HashAlgorithmType
- {
- get { return this.hashAlgorithmType; }
- }
-
- public int HashSize
- {
- get
- {
- switch (this.hashAlgorithmType)
- {
- case HashAlgorithmType.Md5:
- return 16;
-
- case HashAlgorithmType.Sha1:
- return 20;
-
- default:
- return 0;
- }
- }
- }
-
- public ExchangeAlgorithmType ExchangeAlgorithmType
- {
- get { return this.exchangeAlgorithmType; }
- }
-
- public CipherMode CipherMode
- {
- get { return this.cipherMode; }
- }
-
- public short Code
- {
- get { return this.code; }
- }
-
- public string Name
- {
- get { return this.name; }
- }
-
- public bool IsExportable
- {
- get { return this.isExportable; }
- }
-
- public byte KeyMaterialSize
- {
- get { return this.keyMaterialSize; }
- }
-
- public int KeyBlockSize
- {
- get { return this.keyBlockSize; }
- }
-
- public byte ExpandedKeyMaterialSize
- {
- get { return this.expandedKeyMaterialSize; }
- }
-
- public short EffectiveKeyBits
- {
- get { return this.effectiveKeyBits; }
- }
-
- public byte IvSize
- {
- get { return this.ivSize; }
- }
-
- /*
- public byte BlockSize
- {
- get { return this.blockSize; }
- }
- */
-
- public Context Context
- {
- get { return this.context; }
- set
- {
- this.context = value;
- }
- }
-
- #endregion
-
- #region Constructors
-
- public CipherSuite(
- short code, string name, CipherAlgorithmType cipherAlgorithmType,
- HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType,
- bool exportable, bool blockMode, byte keyMaterialSize,
- byte expandedKeyMaterialSize, short effectiveKeyBits,
- byte ivSize, byte blockSize)
- {
- this.code = code;
- this.name = name;
- this.cipherAlgorithmType = cipherAlgorithmType;
- this.hashAlgorithmType = hashAlgorithmType;
- this.exchangeAlgorithmType = exchangeAlgorithmType;
- this.isExportable = exportable;
- if (blockMode)
- {
- this.cipherMode = CipherMode.CBC;
- }
- this.keyMaterialSize = keyMaterialSize;
- this.expandedKeyMaterialSize= expandedKeyMaterialSize;
- this.effectiveKeyBits = effectiveKeyBits;
- this.ivSize = ivSize;
- this.blockSize = blockSize;
- this.keyBlockSize = (this.keyMaterialSize + this.HashSize + this.ivSize) << 1;
- }
-
- #endregion
-
- #region Methods
-
- internal void Write (byte[] array, int offset, short value)
- {
- if (offset > array.Length - 2)
- throw new ArgumentException ("offset");
-
- array [offset ] = (byte) (value >> 8);
- array [offset + 1] = (byte) value;
- }
-
- internal void Write (byte[] array, int offset, ulong value)
- {
- if (offset > array.Length - 8)
- throw new ArgumentException ("offset");
-
- array [offset ] = (byte) (value >> 56);
- array [offset + 1] = (byte) (value >> 48);
- array [offset + 2] = (byte) (value >> 40);
- array [offset + 3] = (byte) (value >> 32);
- array [offset + 4] = (byte) (value >> 24);
- array [offset + 5] = (byte) (value >> 16);
- array [offset + 6] = (byte) (value >> 8);
- array [offset + 7] = (byte) value;
- }
-
- public void InitializeCipher()
- {
- this.createEncryptionCipher();
- this.createDecryptionCipher();
- }
-
- public byte[] EncryptRecord(byte[] fragment, byte[] mac)
- {
- // Encryption ( fragment + mac [+ padding + padding_length] )
- int length = fragment.Length + mac.Length;
- int padlen = 0;
- if (this.CipherMode == CipherMode.CBC) {
- // Calculate padding_length
- length++; // keep an extra byte
- padlen = (this.blockSize - length % this.blockSize);
- if (padlen == this.blockSize) {
- padlen = 0;
- }
- length += padlen;
- }
-
- byte[] plain = new byte [length];
- Buffer.BlockCopy (fragment, 0, plain, 0, fragment.Length);
- Buffer.BlockCopy (mac, 0, plain, fragment.Length, mac.Length);
- if (padlen > 0) {
- int start = fragment.Length + mac.Length;
- for (int i = start; i < (start + padlen + 1); i++) {
- plain[i] = (byte)padlen;
- }
- }
-
- this.EncryptionCipher.TransformBlock (plain, 0, plain.Length, plain, 0);
- return plain;
- }
-
- public void DecryptRecord(byte[] fragment, out byte[] dcrFragment, out byte[] dcrMAC)
- {
- int fragmentSize = 0;
- int paddingLength = 0;
-
- // Decrypt message fragment ( fragment + mac [+ padding + padding_length] )
- this.DecryptionCipher.TransformBlock(fragment, 0, fragment.Length, fragment, 0);
- // optimization: decrypt "in place", worst case: padding will reduce the size of the data
- // this will cut in half the memory allocations (dcrFragment and dcrMAC remains)
-
- // Calculate fragment size
- if (this.CipherMode == CipherMode.CBC)
- {
- // Calculate padding_length
- paddingLength = fragment[fragment.Length - 1];
- fragmentSize = (fragment.Length - (paddingLength + 1)) - this.HashSize;
- }
- else
- {
- fragmentSize = fragment.Length - this.HashSize;
- }
-
- dcrFragment = new byte[fragmentSize];
- dcrMAC = new byte[HashSize];
-
- Buffer.BlockCopy(fragment, 0, dcrFragment, 0, dcrFragment.Length);
- Buffer.BlockCopy(fragment, dcrFragment.Length, dcrMAC, 0, dcrMAC.Length);
- }
-
- #endregion
-
- #region Abstract Methods
-
- public abstract byte[] ComputeClientRecordMAC(ContentType contentType, byte[] fragment);
-
- public abstract byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment);
-
- public abstract void ComputeMasterSecret(byte[] preMasterSecret);
-
- public abstract void ComputeKeys();
-
- #endregion
-
- #region Key Generation Methods
-
- public byte[] CreatePremasterSecret()
- {
- ClientContext context = (ClientContext)this.context;
-
- // Generate random bytes (total size)
- byte[] preMasterSecret = this.context.GetSecureRandomBytes (48);
- // and replace the first two bytes with the protocol version
- // (maximum support version not actual)
- preMasterSecret [0] = (byte)(context.ClientHelloProtocol >> 8);
- preMasterSecret [1] = (byte)context.ClientHelloProtocol;
-
- return preMasterSecret;
- }
-
- public byte[] PRF(byte[] secret, string label, byte[] data, int length)
- {
- /* Secret Length calc exmplain from the RFC2246. Section 5
- *
- * S1 and S2 are the two halves of the secret and each is the same
- * length. S1 is taken from the first half of the secret, S2 from the
- * second half. Their length is created by rounding up the length of the
- * overall secret divided by two; thus, if the original secret is an odd
- * number of bytes long, the last byte of S1 will be the same as the
- * first byte of S2.
- */
-
- // split secret in 2
- int secretLen = secret.Length >> 1;
- // rounding up
- if ((secret.Length & 0x1) == 0x1)
- secretLen++;
-
- // Seed
- TlsStream seedStream = new TlsStream();
- seedStream.Write(Encoding.ASCII.GetBytes(label));
- seedStream.Write(data);
- byte[] seed = seedStream.ToArray();
- seedStream.Reset();
-
- // Secret 1
- byte[] secret1 = new byte[secretLen];
- Buffer.BlockCopy(secret, 0, secret1, 0, secretLen);
-
- // Secret2
- byte[] secret2 = new byte[secretLen];
- Buffer.BlockCopy(secret, (secret.Length - secretLen), secret2, 0, secretLen);
-
- // Secret 1 processing
- byte[] p_md5 = Expand (MD5.Create (), secret1, seed, length);
-
- // Secret 2 processing
- byte[] p_sha = Expand (SHA1.Create (), secret2, seed, length);
-
- // Perfor XOR of both results
- byte[] masterSecret = new byte[length];
- for (int i = 0; i < masterSecret.Length; i++)
- {
- masterSecret[i] = (byte)(p_md5[i] ^ p_sha[i]);
- }
-
- return masterSecret;
- }
-
- public byte[] Expand (HashAlgorithm hash, byte[] secret, byte[] seed, int length)
- {
- int hashLength = hash.HashSize / 8;
- int iterations = (int)(length / hashLength);
- if ((length % hashLength) > 0)
- {
- iterations++;
- }
-
- M.HMAC hmac = new M.HMAC (hash, secret);
- TlsStream resMacs = new TlsStream();
-
- byte[][] hmacs = new byte[iterations + 1][];
- hmacs[0] = seed;
- for (int i = 1; i <= iterations; i++)
- {
- TlsStream hcseed = new TlsStream();
- hmac.TransformFinalBlock(hmacs[i-1], 0, hmacs[i-1].Length);
- hmacs[i] = hmac.Hash;
- hcseed.Write(hmacs[i]);
- hcseed.Write(seed);
- hmac.TransformFinalBlock(hcseed.ToArray(), 0, (int)hcseed.Length);
- resMacs.Write(hmac.Hash);
- hcseed.Reset();
- }
-
- byte[] res = new byte[length];
-
- Buffer.BlockCopy(resMacs.ToArray(), 0, res, 0, res.Length);
-
- resMacs.Reset();
-
- return res;
- }
-
- #endregion
-
- #region Private Methods
-
- private void createEncryptionCipher()
- {
- // Create and configure the symmetric algorithm
- switch (this.cipherAlgorithmType)
- {
- case CipherAlgorithmType.Des:
- this.encryptionAlgorithm = DES.Create();
- break;
-
- case CipherAlgorithmType.Rc2:
- this.encryptionAlgorithm = RC2.Create();
- break;
-
- case CipherAlgorithmType.Rc4:
- this.encryptionAlgorithm = new ARC4Managed();
- break;
-
- case CipherAlgorithmType.TripleDes:
- this.encryptionAlgorithm = TripleDES.Create();
- break;
-
- case CipherAlgorithmType.Rijndael:
- // only AES is really used - and we can use CommonCrypto for iOS and OSX this way
- this.encryptionAlgorithm = Aes.Create();
- break;
- }
-
- // If it's a block cipher
- if (this.cipherMode == CipherMode.CBC)
- {
- // Configure encrypt algorithm
- this.encryptionAlgorithm.Mode = this.cipherMode;
- this.encryptionAlgorithm.Padding = PaddingMode.None;
- this.encryptionAlgorithm.KeySize = this.expandedKeyMaterialSize * 8;
- this.encryptionAlgorithm.BlockSize = this.blockSize * 8;
- }
-
- // Set the key and IV for the algorithm
- if (this.context is ClientContext)
- {
- this.encryptionAlgorithm.Key = this.context.ClientWriteKey;
- this.encryptionAlgorithm.IV = this.context.ClientWriteIV;
- }
- else
- {
- this.encryptionAlgorithm.Key = this.context.ServerWriteKey;
- this.encryptionAlgorithm.IV = this.context.ServerWriteIV;
- }
-
- // Create encryption cipher
- this.encryptionCipher = this.encryptionAlgorithm.CreateEncryptor();
-
- // Create the HMAC algorithm
- if (this.context is ClientContext)
- {
- this.clientHMAC = new M.HMAC(
- CreateHashAlgorithm (),
- this.context.Negotiating.ClientWriteMAC);
- }
- else
- {
- this.serverHMAC = new M.HMAC(
- CreateHashAlgorithm (),
- this.context.Negotiating.ServerWriteMAC);
- }
- }
-
- private void createDecryptionCipher()
- {
- // Create and configure the symmetric algorithm
- switch (this.cipherAlgorithmType)
- {
- case CipherAlgorithmType.Des:
- this.decryptionAlgorithm = DES.Create();
- break;
-
- case CipherAlgorithmType.Rc2:
- this.decryptionAlgorithm = RC2.Create();
- break;
-
- case CipherAlgorithmType.Rc4:
- this.decryptionAlgorithm = new ARC4Managed();
- break;
-
- case CipherAlgorithmType.TripleDes:
- this.decryptionAlgorithm = TripleDES.Create();
- break;
-
- case CipherAlgorithmType.Rijndael:
- // only AES is really used - and we can use CommonCrypto for iOS and OSX this way
- this.decryptionAlgorithm = Aes.Create();
- break;
- }
-
- // If it's a block cipher
- if (this.cipherMode == CipherMode.CBC)
- {
- // Configure encrypt algorithm
- this.decryptionAlgorithm.Mode = this.cipherMode;
- this.decryptionAlgorithm.Padding = PaddingMode.None;
- this.decryptionAlgorithm.KeySize = this.expandedKeyMaterialSize * 8;
- this.decryptionAlgorithm.BlockSize = this.blockSize * 8;
- }
-
- // Set the key and IV for the algorithm
- if (this.context is ClientContext)
- {
- this.decryptionAlgorithm.Key = this.context.ServerWriteKey;
- this.decryptionAlgorithm.IV = this.context.ServerWriteIV;
- }
- else
- {
- this.decryptionAlgorithm.Key = this.context.ClientWriteKey;
- this.decryptionAlgorithm.IV = this.context.ClientWriteIV;
- }
-
- // Create decryption cipher
- this.decryptionCipher = this.decryptionAlgorithm.CreateDecryptor();
-
- // Create the HMAC
- if (this.context is ClientContext)
- {
- this.serverHMAC = new M.HMAC(
- CreateHashAlgorithm (),
- this.context.Negotiating.ServerWriteMAC);
- }
- else
- {
- this.clientHMAC = new M.HMAC(
- CreateHashAlgorithm (),
- this.context.Negotiating.ClientWriteMAC);
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteCollection.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteCollection.cs
deleted file mode 100644
index 973f4b788b8..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteCollection.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright 2013-2014 Xamarin Inc.
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.Generic;
-
-namespace Mono.Security.Protocol.Tls {
-
- internal sealed class CipherSuiteCollection : List<CipherSuite> {
-
- #region Fields
-
- SecurityProtocolType protocol;
-
- #endregion
-
- #region Indexers
-
- public CipherSuite this [string name] {
- get {
- int n = IndexOf (name);
- return n == -1 ? null : this [n];
- }
- }
-
- public CipherSuite this [short code] {
- get {
- int n = IndexOf (code);
- return n == -1 ? null : this [n];
- }
- }
-
- #endregion
-
- #region Constructors
-
- public CipherSuiteCollection (SecurityProtocolType protocol)
- {
- switch (protocol) {
- case SecurityProtocolType.Default:
- case SecurityProtocolType.Tls:
- case SecurityProtocolType.Ssl3:
- this.protocol = protocol;
- break;
- case SecurityProtocolType.Ssl2:
- default:
- throw new NotSupportedException ("Unsupported security protocol type.");
- }
- }
-
- #endregion
-
- #region Methods
-
- public int IndexOf (string name)
- {
- int index = 0;
- foreach (CipherSuite cipherSuite in this) {
- if (String.CompareOrdinal (name, cipherSuite.Name) == 0)
- return index;
- index++;
- }
- return -1;
- }
-
- public int IndexOf (short code)
- {
- int index = 0;
- foreach (CipherSuite cipherSuite in this) {
- if (cipherSuite.Code == code)
- return index;
- index++;
- }
- return -1;
- }
-
- public void Add (
- short code, string name, CipherAlgorithmType cipherType,
- HashAlgorithmType hashType, ExchangeAlgorithmType exchangeType,
- bool exportable, bool blockMode, byte keyMaterialSize,
- byte expandedKeyMaterialSize, short effectiveKeyBytes,
- byte ivSize, byte blockSize)
- {
- switch (protocol) {
- case SecurityProtocolType.Default:
- case SecurityProtocolType.Tls:
- Add (new TlsCipherSuite (code, name, cipherType, hashType, exchangeType, exportable, blockMode,
- keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize));
- break;
-
- case SecurityProtocolType.Ssl3:
- Add (new SslCipherSuite (code, name, cipherType, hashType, exchangeType, exportable, blockMode,
- keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize));
- break;
- }
- }
-
- public IList<string> GetNames ()
- {
- var list = new List<string> (Count);
- foreach (CipherSuite cipherSuite in this)
- list.Add (cipherSuite.Name);
- return list;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteFactory.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteFactory.cs
deleted file mode 100644
index cdba0f655dd..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/CipherSuiteFactory.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright 2013-2014 Xamarin Inc.
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Net;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal static class CipherSuiteFactory
- {
-#if false && !INSIDE_SYSTEM && !BOOTSTRAP_BASIC
- static Type spm = typeof (ServicePointManager);
- static PropertyInfo client_callback;
- static PropertyInfo server_callback;
-#endif
-
- public static CipherSuiteCollection GetSupportedCiphers (bool server, SecurityProtocolType protocol)
- {
- switch (protocol) {
- case SecurityProtocolType.Default:
- case SecurityProtocolType.Tls:
- return CipherSuiteFactory.GetTls1SupportedCiphers ();
- case SecurityProtocolType.Ssl3:
- return CipherSuiteFactory.GetSsl3SupportedCiphers ();
- case SecurityProtocolType.Ssl2:
- default:
- throw new NotSupportedException ("Unsupported security protocol type");
- }
- }
-
- #region Private Static Methods
-
- private static CipherSuiteCollection GetTls1SupportedCiphers()
- {
- CipherSuiteCollection scs = new CipherSuiteCollection(SecurityProtocolType.Tls);
-
- // Supported ciphers
- scs.Add((0x00 << 0x08) | 0x35, "TLS_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 32, 32, 256, 16, 16);
- scs.Add((0x00 << 0x08) | 0x2F, "TLS_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 16, 16, 128, 16, 16);
- scs.Add((0x00 << 0x08) | 0x0A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 24, 24, 168, 8, 8);
- scs.Add((0x00 << 0x08) | 0x05, "TLS_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
- scs.Add((0x00 << 0x08) | 0x04, "TLS_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
- scs.Add((0x00 << 0x08) | 0x09, "TLS_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 8, 8, 56, 8, 8);
-
- // Supported exportable ciphers
- // scs.Add((0x00 << 0x08) | 0x03, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x06, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x08, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x60, "TLS_RSA_EXPORT_WITH_RC4_56_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x61, "TLS_RSA_EXPORT_WITH_RC2_CBC_56_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 7, 16, 56, 8, 8);
- // 56 bits but we use 64 bits because of parity (DES is really 56 bits)
- // scs.Add((0x00 << 0x08) | 0x62, "TLS_RSA_EXPORT_WITH_DES_CBC_56_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 8, 8, 64, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x64, "TLS_RSA_EXPORT_WITH_RC4_56_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
-
- // Default CipherSuite
- // scs.Add(0, "TLS_NULL_WITH_NULL_NULL", CipherAlgorithmType.None, HashAlgorithmType.None, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
-
- // RSA Cipher Suites
- // scs.Add((0x00 << 0x08) | 0x01, "TLS_RSA_WITH_NULL_MD5", CipherAlgorithmType.None, HashAlgorithmType.Md5, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x02, "TLS_RSA_WITH_NULL_SHA", CipherAlgorithmType.None, HashAlgorithmType.Sha1, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x03, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x05, "TLS_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x04, "TLS_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x06, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x07, "TLS_RSA_WITH_IDEA_CBC_SHA", "IDEA", HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 16, 16, 128, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x08, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x09, "TLS_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 24, 24, 168, 8, 8);
-
- // Diffie-Hellman Cipher Suites
- // scs.Add((0x00 << 0x08) | 0x0B, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0C, "TLS_DH_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, false, ExchangeAlgorithmType.DiffieHellman, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0D, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0E, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0F, "TLS_DH_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, false, ExchangeAlgorithmType.DiffieHellman, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x10, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x11, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x12, "TLS_DHE_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x13, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x14, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x15, "TLS_DHE_RSA_WITH_DES_CBC_SHA", HashAlgorithmType.Sha1, CipherAlgorithmType.Des, false, ExchangeAlgorithmType.DiffieHellman, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x16, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
-
- // Anonymous Diffie-Hellman Cipher Suites
- // scs.Add((0x00 << 0x08) | 0x17, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.DiffieHellman, true, false, 5, 16, 40, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x18, "TLS_DH_anon_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, false, ExchangeAlgorithmType.DiffieHellman, false, 16, 16, 128, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x19, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x1A, "TLS_DH_anon_WITH_DES_CBC_SHA", "DES4", HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x1B, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
-
- // AES CipherSuites
- //
- // Ref: RFC3268 - (http://www.ietf.org/rfc/rfc3268.txt)
-
- // scs.Add((0x00 << 0x08) | 0x2F, "TLS_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 16, 16, 128, 16, 16);
- // scs.Add((0x00 << 0x08) | 0x30, "TLS_DH_DSS_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x31, "TLS_DH_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x32, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x33, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x34, "TLS_DH_anon_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 16, 16, 128, 8, 8);
-
- // scs.Add((0x00 << 0x08) | 0x35, "TLS_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 32, 32, 256, 16, 16);
- // scs.Add((0x00 << 0x08) | 0x36, "TLS_DH_DSS_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
- // scs.Add((0x00 << 0x08) | 0x37, "TLS_DH_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
- // scs.Add((0x00 << 0x08) | 0x38, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
- // scs.Add((0x00 << 0x08) | 0x39, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
- // scs.Add((0x00 << 0x08) | 0x3A, "TLS_DH_anon_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 32, 32, 256, 16, 16);
-
- return scs;
- }
-
- private static CipherSuiteCollection GetSsl3SupportedCiphers()
- {
- CipherSuiteCollection scs = new CipherSuiteCollection(SecurityProtocolType.Ssl3);
-
- // Supported ciphers
- scs.Add((0x00 << 0x08) | 0x35, "SSL_RSA_WITH_AES_256_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 32, 32, 256, 16, 16);
- scs.Add((0x00 << 0x08) | 0x2F, "SSL_RSA_WITH_AES_128_CBC_SHA", CipherAlgorithmType.Rijndael, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 16, 16, 128, 16, 16);
- scs.Add((0x00 << 0x08) | 0x0A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 24, 24, 168, 8, 8);
- scs.Add((0x00 << 0x08) | 0x05, "SSL_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
- scs.Add((0x00 << 0x08) | 0x04, "SSL_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, false, false, 16, 16, 128, 0, 0);
- scs.Add((0x00 << 0x08) | 0x09, "SSL_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, false, true, 8, 8, 56, 8, 8);
-
- // Supported exportable ciphers
- // scs.Add((0x00 << 0x08) | 0x03, "SSL_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x06, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x08, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x60, "SSL_RSA_EXPORT_WITH_RC4_56_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x61, "SSL_RSA_EXPORT_WITH_RC2_CBC_56_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 7, 16, 56, 8, 8);
- // 56 bits but we use 64 bits because of parity (DES is really 56 bits)
- // scs.Add((0x00 << 0x08) | 0x62, "SSL_RSA_EXPORT_WITH_DES_CBC_56_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, true, 8, 8, 64, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x64, "SSL_RSA_EXPORT_WITH_RC4_56_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyX, true, false, 7, 16, 56, 0, 0);
-
- // Default CipherSuite
- // scs.Add(0, "SSL_NULL_WITH_NULL_NULL", CipherAlgorithmType.None, HashAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
-
- // RSA Cipher Suites
- // scs.Add((0x00 << 0x08) | 0x01, "SSL_RSA_WITH_NULL_MD5", CipherAlgorithmType.None, HashAlgorithmType.Md5, ExchangeAlgorithmType.None, true, false, 0, 0, 0, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x02, "SSL_RSA_WITH_NULL_SHA", CipherAlgorithmType.None, HashAlgorithmType.Sha1, true, ExchangeAlgorithmType.None, false, 0, 0, 0, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x03, "SSL_RSA_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, false, 5, 16, 40, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x05, "SSL_RSA_WITH_RC4_128_SHA", CipherAlgorithmType.Rc4, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x04, "SSL_RSA_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaSign, false, false, 16, 16, 128, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x06, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5", CipherAlgorithmType.Rc2, HashAlgorithmType.Md5, ExchangeAlgorithmType.RsaKeyX, true, true, 5, 16, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x07, "SSL_RSA_WITH_IDEA_CBC_SHA", "IDEA", HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 16, 16, 128, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x08, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaKeyEx, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x09, "SSL_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.RsaSign, false, true, 24, 24, 168, 8, 8);
-
- // Diffie-Hellman Cipher Suites
- // scs.Add((0x00 << 0x08) | 0x0B, "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0C, "SSL_DH_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0D, "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0E, "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x0F, "SSL_DH_RSA_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x10, "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x11, "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x12, "SSL_DHE_DSS_WITH_DES_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x13, "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x14, "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, true, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x15, "SSL_DHE_RSA_WITH_DES_CBC_SHA", HashAlgorithmType.Sha1, CipherAlgorithmType.Des, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x16, "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
-
- // Anonymous Diffie-Hellman Cipher Suites
- // scs.Add((0x00 << 0x08) | 0x17, "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, ExchangeAlgorithmType.DiffieHellman, true, false, 5, 16, 40, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x18, "SSL_DH_anon_WITH_RC4_128_MD5", CipherAlgorithmType.Rc4, HashAlgorithmType.Md5, false, ExchangeAlgorithmType.DiffieHellman, false, 16, 16, 128, 0, 0);
- // scs.Add((0x00 << 0x08) | 0x19, "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", CipherAlgorithmType.Des, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 5, 8, 40, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x1A, "SSL_DH_anon_WITH_DES_CBC_SHA", "DES4", HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 8, 8, 56, 8, 8);
- // scs.Add((0x00 << 0x08) | 0x1B, "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", CipherAlgorithmType.TripleDes, HashAlgorithmType.Sha1, ExchangeAlgorithmType.DiffieHellman, false, true, 24, 24, 168, 8, 8);
-
- return scs;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientContext.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientContext.cs
deleted file mode 100644
index 2472f9a2fae..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientContext.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class ClientContext : Context
- {
- #region Fields
-
- private SslClientStream sslStream;
- private short clientHelloProtocol;
-
- #endregion
-
- #region Properties
-
- public SslClientStream SslStream
- {
- get { return this.sslStream; }
- }
-
- public short ClientHelloProtocol
- {
- get { return this.clientHelloProtocol; }
- set { this.clientHelloProtocol = value; }
- }
-
- #endregion
-
- #region Constructors
-
- public ClientContext(
- SslClientStream stream,
- SecurityProtocolType securityProtocolType,
- string targetHost,
- X509CertificateCollection clientCertificates)
- : base(securityProtocolType)
- {
- this.sslStream = stream;
- this.ClientSettings.Certificates = clientCertificates;
- this.ClientSettings.TargetHost = targetHost;
- }
-
- #endregion
-
- #region Methods
-
- public override void Clear()
- {
- this.clientHelloProtocol = 0;
- base.Clear();
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientRecordProtocol.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientRecordProtocol.cs
deleted file mode 100644
index 0602e702750..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientRecordProtocol.cs
+++ /dev/null
@@ -1,195 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Globalization;
-using System.IO;
-
-using Mono.Security.Protocol.Tls.Handshake;
-using Mono.Security.Protocol.Tls.Handshake.Client;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class ClientRecordProtocol : RecordProtocol
- {
- #region Constructors
-
- public ClientRecordProtocol(
- Stream innerStream,
- ClientContext context) : base(innerStream, context)
- {
- }
-
- #endregion
-
- #region Send Messages
-
- public override HandshakeMessage GetMessage(HandshakeType type)
- {
- HandshakeMessage msg = this.createClientHandshakeMessage(type);
-
- return msg;
- }
-
- #endregion
-
- #region Handshake Processing Methods
-
- protected override void ProcessHandshakeMessage(TlsStream handMsg)
- {
- HandshakeType handshakeType = (HandshakeType)handMsg.ReadByte();
- HandshakeMessage message = null;
-
- DebugHelper.WriteLine(">>>> Processing Handshake record ({0})", handshakeType);
-
- // Read message length
- int length = handMsg.ReadInt24();
-
- // Read message data
- byte[] data = null;
- if (length > 0)
- {
- data = new byte[length];
- handMsg.Read (data, 0, length);
- }
-
- // Create and process the server message
- message = this.createServerHandshakeMessage(handshakeType, data);
- if (message != null)
- {
- message.Process();
- }
-
- // Update the last handshake message
- this.Context.LastHandshakeMsg = handshakeType;
-
- // Update session
- if (message != null)
- {
- message.Update();
- this.Context.HandshakeMessages.WriteByte ((byte) handshakeType);
- this.Context.HandshakeMessages.WriteInt24 (length);
- if (length > 0)
- {
- this.Context.HandshakeMessages.Write (data, 0, data.Length);
- }
- }
- }
-
- #endregion
-
- #region Client Handshake Message Factories
-
- private HandshakeMessage createClientHandshakeMessage(HandshakeType type)
- {
- switch (type)
- {
- case HandshakeType.ClientHello:
- return new TlsClientHello(this.context);
-
- case HandshakeType.Certificate:
- return new TlsClientCertificate(this.context);
-
- case HandshakeType.ClientKeyExchange:
- return new TlsClientKeyExchange(this.context);
-
- case HandshakeType.CertificateVerify:
- return new TlsClientCertificateVerify(this.context);
-
- case HandshakeType.Finished:
- return new TlsClientFinished(this.context);
-
- default:
- throw new InvalidOperationException("Unknown client handshake message type: " + type.ToString() );
- }
- }
-
- private HandshakeMessage createServerHandshakeMessage(
- HandshakeType type, byte[] buffer)
- {
- ClientContext context = (ClientContext)this.context;
- var last = context.LastHandshakeMsg;
-
- switch (type)
- {
- case HandshakeType.HelloRequest:
- if (context.HandshakeState != HandshakeState.Started)
- {
- context.HandshakeState = HandshakeState.None;
- // re-negotiation will occur at next read/write
- // (i.e. not during an existing encode/decode op)
- }
- else
- {
- this.SendAlert(
- AlertLevel.Warning,
- AlertDescription.NoRenegotiation);
- }
- return null;
-
- case HandshakeType.ServerHello:
- if (last != HandshakeType.HelloRequest)
- break;
- return new TlsServerHello(this.context, buffer);
-
- // Optional
- case HandshakeType.Certificate:
- if (last != HandshakeType.ServerHello)
- break;
- return new TlsServerCertificate(this.context, buffer);
-
- // Optional
- case HandshakeType.CertificateRequest:
- if (last == HandshakeType.ServerKeyExchange || last == HandshakeType.Certificate)
- return new TlsServerCertificateRequest(this.context, buffer);
- break;
-
- case HandshakeType.ServerHelloDone:
- if (last == HandshakeType.CertificateRequest || last == HandshakeType.Certificate || last == HandshakeType.ServerHello)
- return new TlsServerHelloDone(this.context, buffer);
- break;
-
- case HandshakeType.Finished:
- // depends if a full (ServerHelloDone) or an abbreviated handshake (ServerHello) is being done
- bool check = context.AbbreviatedHandshake ? (last == HandshakeType.ServerHello) : (last == HandshakeType.ServerHelloDone);
- // ChangeCipherSpecDone is not an handshake message (it's a content type) but still needs to be happens before finished
- if (check && context.ChangeCipherSpecDone) {
- context.ChangeCipherSpecDone = false;
- return new TlsServerFinished (this.context, buffer);
- }
- break;
-
- default:
- throw new TlsException(
- AlertDescription.UnexpectedMessage,
- String.Format(CultureInfo.CurrentUICulture,
- "Unknown server handshake message received ({0})",
- type.ToString()));
- }
- throw new TlsException (AlertDescription.HandshakeFailiure, String.Format ("Protocol error, unexpected protocol transition from {0} to {1}", last, type));
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientSessionCache.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientSessionCache.cs
deleted file mode 100644
index 749a51edea4..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ClientSessionCache.cs
+++ /dev/null
@@ -1,254 +0,0 @@
-//
-// ClientSessionCache.cs: Client-side cache for re-using sessions
-//
-// Author:
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// Copyright (C) 2006 Novell (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-
-namespace Mono.Security.Protocol.Tls {
-
- internal class ClientSessionInfo : IDisposable {
-
- // (by default) we keep this item valid for 3 minutes (if unused)
- private const int DefaultValidityInterval = 3 * 60;
- private static readonly int ValidityInterval;
-
- private bool disposed;
- private DateTime validuntil;
- private string host;
-
- // see RFC2246 - Section 7
- private byte[] sid;
- private byte[] masterSecret;
-
- static ClientSessionInfo ()
- {
- string user_cache_timeout = Environment.GetEnvironmentVariable ("MONO_TLS_SESSION_CACHE_TIMEOUT");
- if (user_cache_timeout == null) {
- ValidityInterval = DefaultValidityInterval;
- } else {
- try {
- ValidityInterval = Int32.Parse (user_cache_timeout);
- }
- catch {
- ValidityInterval = DefaultValidityInterval;
- }
- }
- }
-
- public ClientSessionInfo (string hostname, byte[] id)
- {
- host = hostname;
- sid = id;
- KeepAlive ();
- }
-
- ~ClientSessionInfo ()
- {
- Dispose (false);
- }
-
-
- public string HostName {
- get { return host; }
- }
-
- public byte[] Id {
- get { return sid; }
- }
-
- public bool Valid {
- get { return ((masterSecret != null) && (validuntil > DateTime.UtcNow)); }
- }
-
-
- public void GetContext (Context context)
- {
- CheckDisposed ();
- if (context.MasterSecret != null)
- masterSecret = (byte[]) context.MasterSecret.Clone ();
- }
-
- public void SetContext (Context context)
- {
- CheckDisposed ();
- if (masterSecret != null)
- context.MasterSecret = (byte[]) masterSecret.Clone ();
- }
-
- public void KeepAlive ()
- {
- CheckDisposed ();
- validuntil = DateTime.UtcNow.AddSeconds (ValidityInterval);
- }
-
- public void Dispose ()
- {
- Dispose (true);
- GC.SuppressFinalize (this);
- }
-
- private void Dispose (bool disposing)
- {
- if (!disposed) {
- validuntil = DateTime.MinValue;
- host = null;
- sid = null;
-
- if (masterSecret != null) {
- Array.Clear (masterSecret, 0, masterSecret.Length);
- masterSecret = null;
- }
- }
- disposed = true;
- }
-
- private void CheckDisposed ()
- {
- if (disposed) {
- string msg = Locale.GetText ("Cache session information were disposed.");
- throw new ObjectDisposedException (msg);
- }
- }
- }
-
- // note: locking is aggressive but isn't used often (and we gain much more :)
- internal class ClientSessionCache {
-
- static Hashtable cache;
- static object locker;
-
- static ClientSessionCache ()
- {
- cache = new Hashtable ();
- locker = new object ();
- }
-
- // note: we may have multiple connections with a host, so
- // possibly multiple entries per host (each with a different
- // id), so we do not use the host as the hashtable key
- static public void Add (string host, byte[] id)
- {
- lock (locker) {
- string uid = BitConverter.ToString (id);
- ClientSessionInfo si = (ClientSessionInfo) cache[uid];
- if (si == null) {
- cache.Add (uid, new ClientSessionInfo (host, id));
- } else if (si.HostName == host) {
- // we already have this and it's still valid
- // on the server, so we'll keep it a little longer
- si.KeepAlive ();
- } else {
- // it's very unlikely but the same session id
- // could be used by more than one host. In this
- // case we replace the older one with the new one
- si.Dispose ();
- cache.Remove (uid);
- cache.Add (uid, new ClientSessionInfo (host, id));
- }
- }
- }
-
- // return the first session us
- static public byte[] FromHost (string host)
- {
- lock (locker) {
- foreach (ClientSessionInfo si in cache.Values) {
- if (si.HostName == host) {
- if (si.Valid) {
- // ensure it's still valid when we really need it
- si.KeepAlive ();
- return si.Id;
- }
- }
- }
- return null;
- }
- }
-
- // only called inside the lock
- static private ClientSessionInfo FromContext (Context context, bool checkValidity)
- {
- if (context == null)
- return null;
-
- byte[] id = context.SessionId;
- if ((id == null) || (id.Length == 0))
- return null;
-
- // do we have a session cached for this host ?
- string uid = BitConverter.ToString (id);
-
- ClientSessionInfo si = (ClientSessionInfo) cache[uid];
- if (si == null)
- return null;
-
- // In the unlikely case of multiple hosts using the same
- // session id, we just act like we do not know about it
- if (context.ClientSettings.TargetHost != si.HostName)
- return null;
-
- // yes, so what's its status ?
- if (checkValidity && !si.Valid) {
- si.Dispose ();
- cache.Remove (uid);
- return null;
- }
-
- // ok, it make sense
- return si;
- }
-
- static public bool SetContextInCache (Context context)
- {
- lock (locker) {
- // Don't check the validity because the masterKey of the ClientSessionInfo
- // can still be null when this is called the first time
- ClientSessionInfo csi = FromContext (context, false);
- if (csi == null)
- return false;
-
- csi.GetContext (context);
- csi.KeepAlive ();
- return true;
- }
- }
-
- static public bool SetContextFromCache (Context context)
- {
- lock (locker) {
- ClientSessionInfo csi = FromContext (context, true);
- if (csi == null)
- return false;
-
- csi.SetContext (context);
- csi.KeepAlive ();
- return true;
- }
- }
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ContentType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ContentType.cs
deleted file mode 100644
index e07d64e461e..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ContentType.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
- [Serializable]
- internal enum ContentType : byte
- {
- ChangeCipherSpec = 20,
- Alert = 21,
- Handshake = 22,
- ApplicationData = 23,
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Context.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Context.cs
deleted file mode 100644
index 3923daf1a8b..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Context.cs
+++ /dev/null
@@ -1,519 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Text;
-using System.Collections;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.Cryptography;
-using Mono.Security.Protocol.Tls.Handshake;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal abstract class Context
- {
- #region Internal Constants
-
- internal const short MAX_FRAGMENT_SIZE = 16384; // 2^14
- internal const short TLS1_PROTOCOL_CODE = (0x03 << 8) | 0x01;
- internal const short SSL3_PROTOCOL_CODE = (0x03 << 8) | 0x00;
- internal const long UNIX_BASE_TICKS = 621355968000000000;
-
- #endregion
-
- #region Fields
-
- // Protocol version
- private SecurityProtocolType securityProtocol;
-
- // Sesison ID
- private byte[] sessionId;
-
- // Compression method
- private SecurityCompressionType compressionMethod;
-
- // Information sent and request by the server in the Handshake protocol
- private TlsServerSettings serverSettings;
-
- // Client configuration
- private TlsClientSettings clientSettings;
-
- // Cipher suite information
- private SecurityParameters current;
- private SecurityParameters negotiating;
- private SecurityParameters read;
- private SecurityParameters write;
- private CipherSuiteCollection supportedCiphers;
-
- // Last handshake message received
- private HandshakeType lastHandshakeMsg;
-
- // Handshake negotiation state
- private HandshakeState handshakeState;
-
- // Misc
- private bool abbreviatedHandshake;
- private bool receivedConnectionEnd;
- private bool sentConnectionEnd;
- private bool protocolNegotiated;
-
- // Sequence numbers
- private ulong writeSequenceNumber;
- private ulong readSequenceNumber;
-
- // Random data
- private byte[] clientRandom;
- private byte[] serverRandom;
- private byte[] randomCS;
- private byte[] randomSC;
-
- // Key information
- private byte[] masterSecret;
- private byte[] clientWriteKey;
- private byte[] serverWriteKey;
- private byte[] clientWriteIV;
- private byte[] serverWriteIV;
-
- // Handshake hashes
- private TlsStream handshakeMessages;
-
- // Secure Random generator
- private RandomNumberGenerator random;
-
- // Record protocol
- private RecordProtocol recordProtocol;
-
- #endregion
-
- #region Properties
-
- public bool AbbreviatedHandshake
- {
- get { return abbreviatedHandshake; }
- set { abbreviatedHandshake = value; }
- }
-
- public bool ProtocolNegotiated
- {
- get { return this.protocolNegotiated; }
- set { this.protocolNegotiated = value; }
- }
-
- public bool ChangeCipherSpecDone { get; set; }
-
- public SecurityProtocolType SecurityProtocol
- {
- get
- {
- if ((this.securityProtocol & SecurityProtocolType.Tls) == SecurityProtocolType.Tls ||
- (this.securityProtocol & SecurityProtocolType.Default) == SecurityProtocolType.Default)
- {
- return SecurityProtocolType.Tls;
- }
- else
- {
- if ((this.securityProtocol & SecurityProtocolType.Ssl3) == SecurityProtocolType.Ssl3)
- {
- return SecurityProtocolType.Ssl3;
- }
- }
-
- throw new NotSupportedException("Unsupported security protocol type");
- }
-
- set { this.securityProtocol = value; }
- }
-
- public SecurityProtocolType SecurityProtocolFlags
- {
- get { return this.securityProtocol; }
- }
-
- public short Protocol
- {
- get
- {
- switch (this.SecurityProtocol)
- {
- case SecurityProtocolType.Tls:
- case SecurityProtocolType.Default:
- return Context.TLS1_PROTOCOL_CODE;
-
- case SecurityProtocolType.Ssl3:
- return Context.SSL3_PROTOCOL_CODE;
-
- case SecurityProtocolType.Ssl2:
- default:
- throw new NotSupportedException("Unsupported security protocol type");
- }
- }
- }
-
- public byte[] SessionId
- {
- get { return this.sessionId; }
- set { this.sessionId = value; }
- }
-
- public SecurityCompressionType CompressionMethod
- {
- get { return this.compressionMethod; }
- set { this.compressionMethod = value; }
- }
-
- public TlsServerSettings ServerSettings
- {
- get { return this.serverSettings; }
- }
-
- public TlsClientSettings ClientSettings
- {
- get { return this.clientSettings; }
- }
-
- public HandshakeType LastHandshakeMsg
- {
- get { return this.lastHandshakeMsg; }
- set { this.lastHandshakeMsg = value; }
- }
-
- public HandshakeState HandshakeState
- {
- get { return this.handshakeState; }
- set { this.handshakeState = value; }
- }
-
- public bool ReceivedConnectionEnd
- {
- get { return this.receivedConnectionEnd; }
- set { this.receivedConnectionEnd = value; }
- }
-
- public bool SentConnectionEnd
- {
- get { return this.sentConnectionEnd; }
- set { this.sentConnectionEnd = value; }
- }
-
- public CipherSuiteCollection SupportedCiphers
- {
- get { return supportedCiphers; }
- set { supportedCiphers = value; }
- }
-
- public TlsStream HandshakeMessages
- {
- get { return this.handshakeMessages; }
- }
-
- public ulong WriteSequenceNumber
- {
- get { return this.writeSequenceNumber; }
- set { this.writeSequenceNumber = value; }
- }
-
- public ulong ReadSequenceNumber
- {
- get { return this.readSequenceNumber; }
- set { this.readSequenceNumber = value; }
- }
-
- public byte[] ClientRandom
- {
- get { return this.clientRandom; }
- set { this.clientRandom = value; }
- }
-
- public byte[] ServerRandom
- {
- get { return this.serverRandom; }
- set { this.serverRandom = value; }
- }
-
- public byte[] RandomCS
- {
- get { return this.randomCS; }
- set { this.randomCS = value; }
- }
-
- public byte[] RandomSC
- {
- get { return this.randomSC; }
- set { this.randomSC = value; }
- }
-
- public byte[] MasterSecret
- {
- get { return this.masterSecret; }
- set { this.masterSecret = value; }
- }
-
- public byte[] ClientWriteKey
- {
- get { return this.clientWriteKey; }
- set { this.clientWriteKey = value; }
- }
-
- public byte[] ServerWriteKey
- {
- get { return this.serverWriteKey; }
- set { this.serverWriteKey = value; }
- }
-
- public byte[] ClientWriteIV
- {
- get { return this.clientWriteIV; }
- set { this.clientWriteIV = value; }
- }
-
- public byte[] ServerWriteIV
- {
- get { return this.serverWriteIV; }
- set { this.serverWriteIV = value; }
- }
-
- public RecordProtocol RecordProtocol
- {
- get { return this.recordProtocol; }
- set { this.recordProtocol = value; }
- }
-
- #endregion
-
- #region Constructors
-
- public Context(SecurityProtocolType securityProtocolType)
- {
- this.SecurityProtocol = securityProtocolType;
- this.compressionMethod = SecurityCompressionType.None;
- this.serverSettings = new TlsServerSettings();
- this.clientSettings = new TlsClientSettings();
- this.handshakeMessages = new TlsStream();
- this.sessionId = null;
- this.handshakeState = HandshakeState.None;
- this.random = RandomNumberGenerator.Create();
- }
-
- #endregion
-
- #region Methods
-
- public int GetUnixTime()
- {
- DateTime now = DateTime.UtcNow;
-
- return (int)((now.Ticks - UNIX_BASE_TICKS) / TimeSpan.TicksPerSecond);
- }
-
- public byte[] GetSecureRandomBytes(int count)
- {
- byte[] secureBytes = new byte[count];
-
- this.random.GetNonZeroBytes(secureBytes);
-
- return secureBytes;
- }
-
- public virtual void Clear()
- {
- this.compressionMethod = SecurityCompressionType.None;
- this.serverSettings = new TlsServerSettings();
- this.clientSettings = new TlsClientSettings();
- this.handshakeMessages = new TlsStream();
- this.sessionId = null;
- this.handshakeState = HandshakeState.None;
-
- this.ClearKeyInfo();
- }
-
- public virtual void ClearKeyInfo()
- {
- // Clear Master Secret
- if (masterSecret != null) {
- Array.Clear (masterSecret, 0, masterSecret.Length);
- masterSecret = null;
- }
-
- // Clear client and server random
- if (clientRandom != null) {
- Array.Clear (clientRandom, 0, clientRandom.Length);
- clientRandom = null;
- }
- if (serverRandom != null) {
- Array.Clear (serverRandom, 0, serverRandom.Length);
- serverRandom = null;
- }
- if (randomCS != null) {
- Array.Clear (randomCS, 0, randomCS.Length);
- randomCS = null;
- }
- if (randomSC != null) {
- Array.Clear (randomSC, 0, randomSC.Length);
- randomSC = null;
- }
-
- // Clear client keys
- if (clientWriteKey != null) {
- Array.Clear (clientWriteKey, 0, clientWriteKey.Length);
- clientWriteKey = null;
- }
- if (clientWriteIV != null) {
- Array.Clear (clientWriteIV, 0, clientWriteIV.Length);
- clientWriteIV = null;
- }
-
- // Clear server keys
- if (serverWriteKey != null) {
- Array.Clear (serverWriteKey, 0, serverWriteKey.Length);
- serverWriteKey = null;
- }
- if (serverWriteIV != null) {
- Array.Clear (serverWriteIV, 0, serverWriteIV.Length);
- serverWriteIV = null;
- }
-
- // Reset handshake messages
- this.handshakeMessages.Reset();
-
- // Clear MAC keys if protocol is different than Ssl3
- // SSLv3 needs them inside Mono.Security.Protocol.Tls.SslCipherSuite.Compute[Client|Server]RecordMAC
- if (this.securityProtocol != SecurityProtocolType.Ssl3)
- {
-// this.clientWriteMAC = null;
-// this.serverWriteMAC = null;
- }
- }
-
- public SecurityProtocolType DecodeProtocolCode (short code, bool allowFallback = false)
- {
- switch (code)
- {
- case Context.TLS1_PROTOCOL_CODE:
- return SecurityProtocolType.Tls;
-
- case Context.SSL3_PROTOCOL_CODE:
- return SecurityProtocolType.Ssl3;
-
- default:
- // if allowed we'll continue using TLS (1.0) even if the other side is capable of using a newer
- // version of the TLS protocol
- if (allowFallback && (code > (short) Context.TLS1_PROTOCOL_CODE))
- return SecurityProtocolType.Tls;
- throw new NotSupportedException("Unsupported security protocol type");
- }
- }
-
- public void ChangeProtocol(short protocol)
- {
- SecurityProtocolType protocolType = this.DecodeProtocolCode(protocol);
-
- if ((protocolType & this.SecurityProtocolFlags) == protocolType ||
- (this.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
- {
- this.SecurityProtocol = protocolType;
- this.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers ((this is ServerContext), protocolType);
- }
- else
- {
- throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server");
- }
- }
-
-
- public SecurityParameters Current
- {
- get
- {
- if (current == null)
- current = new SecurityParameters ();
- if (current.Cipher != null)
- current.Cipher.Context = this;
- return current;
- }
- }
-
- public SecurityParameters Negotiating
- {
- get
- {
- if (negotiating == null)
- negotiating = new SecurityParameters ();
- if (negotiating.Cipher != null)
- negotiating.Cipher.Context = this;
- return negotiating;
- }
- }
-
- public SecurityParameters Read
- {
- get { return read; }
- }
-
- public SecurityParameters Write
- {
- get { return write; }
- }
-
- public void StartSwitchingSecurityParameters (bool client)
- {
- if (client) {
- // everything we write from now on is encrypted
- write = negotiating;
- // but we still read with the older cipher until we
- // receive the ChangeCipherSpec message
- read = current;
- } else {
- // everything we read from now on is encrypted
- read = negotiating;
- // but we still write with the older cipher until we
- // receive the ChangeCipherSpec message
- write = current;
- }
- current = negotiating;
- }
-
- public void EndSwitchingSecurityParameters (bool client)
- {
- SecurityParameters temp;
- if (client) {
- temp = read;
- // we now read with the new, negotiated, security parameters
- read = current;
- } else {
- temp = write;
- // we now write with the new, negotiated, security parameters
- write = current;
- }
- // so we clear the old one (last reference)
- if (temp != null)
- temp.Clear ();
- negotiating = temp;
- // and are now ready for a future renegotiation
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/DebugHelper.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/DebugHelper.cs
deleted file mode 100644
index ff122878c95..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/DebugHelper.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Diagnostics;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class DebugHelper
- {
- private static bool isInitialized;
-
- [Conditional("DEBUG")]
- public static void Initialize()
- {
- if (!isInitialized)
- {
-#if !MOBILE
- Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
- // Debug.Listeners.Add(new TextWriterTraceListener(@"c:\ssl.log"));
- Debug.AutoFlush = true;
- Debug.Indent();
-#endif
-
- isInitialized = true;
- }
- }
-
- [Conditional("DEBUG")]
- public static void WriteLine(string format, params object[] args)
- {
- Initialize();
- Debug.WriteLine(String.Format(format, args));
- }
-
- [Conditional("DEBUG")]
- public static void WriteLine(string message)
- {
- Initialize();
- Debug.WriteLine(message);
- }
-
- [Conditional("DEBUG")]
- public static void WriteLine(string message, byte[] buffer)
- {
- Initialize();
- DebugHelper.WriteLine(String.Format("{0} ({1} bytes))", message, buffer.Length));
- DebugHelper.WriteBuffer(buffer);
- }
-
- [Conditional("DEBUG")]
- public static void WriteBuffer(byte[] buffer)
- {
- Initialize();
- DebugHelper.WriteBuffer(buffer, 0, buffer.Length);
- }
-
- [Conditional("DEBUG")]
- public static void WriteBuffer(byte[] buffer, int index, int length)
- {
- Initialize();
- for (int i = index; i < length; i += 16)
- {
- int count = (length - i) >= 16 ? 16 : (length - i);
- string buf = "";
- for (int j = 0; j < count; j++)
- {
- buf += buffer[i + j].ToString("x2") + " ";
- }
- Debug.WriteLine(buf);
- }
- }
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs
deleted file mode 100644
index 3f5156ea93a..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
-#if INSIDE_SYSTEM
- internal
-#else
- [Serializable]
- public
-#endif
- enum ExchangeAlgorithmType
- {
- DiffieHellman,
- Fortezza,
- None,
- RsaKeyX,
- RsaSign
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HandshakeState.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HandshakeState.cs
deleted file mode 100644
index cf15386f0fd..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HandshakeState.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
- [Serializable]
- internal enum HandshakeState
- {
- None,
- Started,
- Finished
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HashAlgorithmType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HashAlgorithmType.cs
deleted file mode 100644
index 3f6a60cd7cf..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HashAlgorithmType.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
-#if INSIDE_SYSTEM
- internal
-#else
- [Serializable]
- public
-#endif
- enum HashAlgorithmType
- {
- Md5,
- None,
- Sha1
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HttpsClientStream.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HttpsClientStream.cs
deleted file mode 100644
index 6eb85f53890..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/HttpsClientStream.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-//
-// HttpsClientStream.cs: Glue between HttpWebRequest and SslClientStream to
-// reduce reflection usage.
-//
-// Author:
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// Copyright (C) 2004-2007 Novell, Inc. (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Net;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-using SNS = System.Net.Security;
-using SNCX = System.Security.Cryptography.X509Certificates;
-
-namespace Mono.Security.Protocol.Tls {
-
- // Note: DO NOT REUSE this class - instead use SslClientStream
-
- [Obsolete ("This class is obsolete and will be removed shortly.")]
- internal class HttpsClientStream : SslClientStream {
-
- private HttpWebRequest _request;
- private int _status;
-
- public HttpsClientStream (Stream stream, X509CertificateCollection clientCertificates,
- HttpWebRequest request, byte [] buffer)
- : base (stream, request.Address.Host, false, (Mono.Security.Protocol.Tls.SecurityProtocolType)
- ServicePointManager.SecurityProtocol, clientCertificates)
- {
- // this constructor permit access to the WebRequest to call
- // ICertificatePolicy.CheckValidationResult
- _request = request;
- _status = 0;
- if (buffer != null)
- InputBuffer.Write (buffer, 0, buffer.Length);
- // also saved from reflection
- base.CheckCertRevocationStatus = ServicePointManager.CheckCertificateRevocationList;
-
- ClientCertSelection += delegate (X509CertificateCollection clientCerts, X509Certificate serverCertificate,
- string targetHost, X509CertificateCollection serverRequestedCertificates) {
- return ((clientCerts == null) || (clientCerts.Count == 0)) ? null : clientCerts [0];
- };
- PrivateKeySelection += delegate (X509Certificate certificate, string targetHost) {
- X509Certificate2 cert = (certificate as X509Certificate2);
- return (cert == null) ? null : cert.PrivateKey;
- };
- }
-
- public bool TrustFailure {
- get {
- switch (_status) {
- case -2146762486: // CERT_E_CHAINING 0x800B010A
- case -2146762487: // CERT_E_UNTRUSTEDROOT 0x800B0109
- return true;
- default:
- return false;
- }
- }
- }
-
- internal override bool RaiseServerCertificateValidation (X509Certificate certificate, int[] certificateErrors)
- {
- bool failed = (certificateErrors.Length > 0);
- // only one problem can be reported by this interface
- _status = ((failed) ? certificateErrors [0] : 0);
-
-#pragma warning disable 618
- if (ServicePointManager.CertificatePolicy != null) {
- ServicePoint sp = _request.ServicePoint;
- bool res = ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, _request, _status);
- if (!res)
- return false;
- failed = true;
- }
-#pragma warning restore 618
- if (HaveRemoteValidation2Callback)
- return failed; // The validation already tried the 2.0 callback
-
- SNS.RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
- if (cb != null) {
- SNS.SslPolicyErrors ssl_errors = 0;
- foreach (int i in certificateErrors) {
- if (i == (int)-2146762490) // TODO: is this what happens when the purpose is wrong?
- ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNotAvailable;
- else if (i == (int) -2146762481)
- ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNameMismatch;
- else
- ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
- }
- SNCX.X509Certificate2 cert2 = new SNCX.X509Certificate2 (certificate.GetRawCertData ());
- SNCX.X509Chain chain = new SNCX.X509Chain ();
- if (!chain.Build (cert2))
- ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
- return cb (_request, cert2, chain, ssl_errors);
- }
- return failed;
- }
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/MD5SHA1.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/MD5SHA1.cs
deleted file mode 100644
index 01680df44ec..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/MD5SHA1.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-/* Transport Security Layer (TLS)
- * Copyright (c) 2003-2004 Carlos Guzman Alvarez
- *
- * Permission is hereby granted, free of charge, to any person
- * obtaining a copy of this software and associated documentation
- * files (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- */
-
-using System;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class MD5SHA1 : HashAlgorithm
- {
- #region Fields
-
- private HashAlgorithm md5;
- private HashAlgorithm sha;
- private bool hashing;
-
- #endregion
-
- #region Constructors
-
- public MD5SHA1() : base()
- {
- this.md5 = MD5.Create();
- this.sha = SHA1.Create();
-
- // Set HashSizeValue
- this.HashSizeValue = this.md5.HashSize + this.sha.HashSize;
- }
-
- #endregion
-
- #region Methods
-
- public override void Initialize()
- {
- this.md5.Initialize();
- this.sha.Initialize();
- this.hashing = false;
- }
-
- protected override byte[] HashFinal()
- {
- if (!hashing)
- {
- this.hashing = true;
- }
- // Finalize the original hash
- this.md5.TransformFinalBlock(new byte[0], 0, 0);
- this.sha.TransformFinalBlock(new byte[0], 0, 0);
-
- byte[] hash = new byte[36];
-
- Buffer.BlockCopy(this.md5.Hash, 0, hash, 0, 16);
- Buffer.BlockCopy(this.sha.Hash, 0, hash, 16, 20);
-
- return hash;
- }
-
- protected override void HashCore(
- byte[] array,
- int ibStart,
- int cbSize)
- {
- if (!hashing)
- {
- hashing = true;
- }
- this.md5.TransformBlock(array, ibStart, cbSize, array, ibStart);
- this.sha.TransformBlock(array, ibStart, cbSize, array, ibStart);
- }
-
- public byte[] CreateSignature(RSA rsa)
- {
- if (rsa == null)
- {
- throw new CryptographicUnexpectedOperationException ("missing key");
- }
-
- RSASslSignatureFormatter f = new RSASslSignatureFormatter(rsa);
- f.SetHashAlgorithm("MD5SHA1");
-
- return f.CreateSignature(this.Hash);
- }
-
- public bool VerifySignature(RSA rsa, byte[] rgbSignature)
- {
- if (rsa == null)
- {
- throw new CryptographicUnexpectedOperationException ("missing key");
- }
- if (rgbSignature == null)
- {
- throw new ArgumentNullException ("rgbSignature");
- }
-
- RSASslSignatureDeformatter d = new RSASslSignatureDeformatter(rsa);
- d.SetHashAlgorithm("MD5SHA1");
-
- return d.VerifySignature(this.Hash, rgbSignature);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs
deleted file mode 100644
index 8131197887d..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class RSASslSignatureDeformatter : AsymmetricSignatureDeformatter
- {
- #region Fields
-
- private RSA key;
- private HashAlgorithm hash;
-
- #endregion
-
- #region Constructors
-
- public RSASslSignatureDeformatter()
- {
- }
-
- public RSASslSignatureDeformatter(AsymmetricAlgorithm key)
- {
- this.SetKey(key);
- }
-
- #endregion
-
- #region Methods
-
- public override bool VerifySignature(
- byte[] rgbHash,
- byte[] rgbSignature)
- {
- if (this.key == null)
- {
- throw new CryptographicUnexpectedOperationException("The key is a null reference");
- }
- if (hash == null)
- {
- throw new CryptographicUnexpectedOperationException("The hash algorithm is a null reference.");
- }
- if (rgbHash == null)
- {
- throw new ArgumentNullException("The rgbHash parameter is a null reference.");
- }
-
- return Mono.Security.Cryptography.PKCS1.Verify_v15(
- this.key,
- this.hash,
- rgbHash,
- rgbSignature);
- }
-
- public override void SetHashAlgorithm(string strName)
- {
-#if INSIDE_SYSTEM
- hash = new Mono.Security.Cryptography.MD5SHA1 ();
-#else
- switch (strName)
- {
- case "MD5SHA1":
- this.hash = new MD5SHA1();
- break;
-
- default:
- this.hash = HashAlgorithm.Create(strName);
- break;
- }
-#endif
- }
-
- public override void SetKey(AsymmetricAlgorithm key)
- {
- if (!(key is RSA))
- {
- throw new ArgumentException("Specfied key is not an RSA key");
- }
-
- this.key = key as RSA;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs
deleted file mode 100644
index b313f005a9a..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class RSASslSignatureFormatter : AsymmetricSignatureFormatter
- {
- #region Fields
-
- private RSA key;
- private HashAlgorithm hash;
-
- #endregion
-
- #region Constructors
-
- public RSASslSignatureFormatter()
- {
- }
-
- public RSASslSignatureFormatter(AsymmetricAlgorithm key)
- {
- this.SetKey(key);
- }
-
- #endregion
-
- #region Methods
-
- public override byte[] CreateSignature(byte[] rgbHash)
- {
- if (this.key == null)
- {
- throw new CryptographicUnexpectedOperationException("The key is a null reference");
- }
- if (hash == null)
- {
- throw new CryptographicUnexpectedOperationException("The hash algorithm is a null reference.");
- }
- if (rgbHash == null)
- {
- throw new ArgumentNullException("The rgbHash parameter is a null reference.");
- }
-
- return Mono.Security.Cryptography.PKCS1.Sign_v15(
- this.key,
- this.hash,
- rgbHash);
- }
-
- public override void SetHashAlgorithm(string strName)
- {
-#if INSIDE_SYSTEM
- hash = new Mono.Security.Cryptography.MD5SHA1 ();
-#else
- switch (strName)
- {
- case "MD5SHA1":
- this.hash = new MD5SHA1();
- break;
-
- default:
- this.hash = HashAlgorithm.Create(strName);
- break;
- }
-#endif
- }
-
- public override void SetKey(AsymmetricAlgorithm key)
- {
- if (!(key is RSA))
- {
- throw new ArgumentException("Specfied key is not an RSA key");
- }
-
- this.key = key as RSA;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
deleted file mode 100644
index 30270c801c8..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
+++ /dev/null
@@ -1,965 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using System.IO;
-using System.Threading;
-
-using Mono.Security.Protocol.Tls.Handshake;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal abstract class RecordProtocol
- {
- #region Fields
-
- private static ManualResetEvent record_processing = new ManualResetEvent (true);
-
- protected Stream innerStream;
- protected Context context;
-
- #endregion
-
- #region Properties
-
- public Context Context
- {
- get { return this.context; }
- set { this.context = value; }
- }
-
- #endregion
-
- #region Constructors
-
- public RecordProtocol(Stream innerStream, Context context)
- {
- this.innerStream = innerStream;
- this.context = context;
- this.context.RecordProtocol = this;
- }
-
- #endregion
-
- #region Abstract Methods
-
- public virtual void SendRecord(HandshakeType type)
- {
-
- IAsyncResult ar = this.BeginSendRecord(type, null, null);
-
- this.EndSendRecord(ar);
-
- }
-
- protected abstract void ProcessHandshakeMessage(TlsStream handMsg);
-
- protected virtual void ProcessChangeCipherSpec ()
- {
- Context ctx = this.Context;
-
- // Reset sequence numbers
- ctx.ReadSequenceNumber = 0;
-
- if (ctx is ClientContext) {
- ctx.EndSwitchingSecurityParameters (true);
- } else {
- ctx.StartSwitchingSecurityParameters (false);
- }
-
- ctx.ChangeCipherSpecDone = true;
- }
-
- public virtual HandshakeMessage GetMessage(HandshakeType type)
- {
- throw new NotSupportedException();
- }
-
- #endregion
-
- #region Receive Record Async Result
- private class ReceiveRecordAsyncResult : IAsyncResult
- {
- private object locker = new object ();
- private AsyncCallback _userCallback;
- private object _userState;
- private Exception _asyncException;
- private ManualResetEvent handle;
- private byte[] _resultingBuffer;
- private Stream _record;
- private bool completed;
-
- private byte[] _initialBuffer;
-
- public ReceiveRecordAsyncResult(AsyncCallback userCallback, object userState, byte[] initialBuffer, Stream record)
- {
- _userCallback = userCallback;
- _userState = userState;
- _initialBuffer = initialBuffer;
- _record = record;
- }
-
- public Stream Record
- {
- get { return _record; }
- }
-
- public byte[] ResultingBuffer
- {
- get { return _resultingBuffer; }
- }
-
- public byte[] InitialBuffer
- {
- get { return _initialBuffer; }
- }
-
- public object AsyncState
- {
- get { return _userState; }
- }
-
- public Exception AsyncException
- {
- get { return _asyncException; }
- }
-
- public bool CompletedWithError
- {
- get {
- if (!IsCompleted)
- return false; // Perhaps throw InvalidOperationExcetion?
-
- return null != _asyncException;
- }
- }
-
- public WaitHandle AsyncWaitHandle
- {
- get {
- lock (locker) {
- if (handle == null)
- handle = new ManualResetEvent (completed);
- }
- return handle;
- }
-
- }
-
- public bool CompletedSynchronously
- {
- get { return false; }
- }
-
- public bool IsCompleted
- {
- get {
- lock (locker) {
- return completed;
- }
- }
- }
-
- private void SetComplete(Exception ex, byte[] resultingBuffer)
- {
- lock (locker) {
- if (completed)
- return;
-
- completed = true;
- _asyncException = ex;
- _resultingBuffer = resultingBuffer;
- if (handle != null)
- handle.Set ();
-
- if (_userCallback != null)
- _userCallback.BeginInvoke (this, null, null);
- }
- }
-
- public void SetComplete(Exception ex)
- {
- SetComplete(ex, null);
- }
-
- public void SetComplete(byte[] resultingBuffer)
- {
- SetComplete(null, resultingBuffer);
- }
-
- public void SetComplete()
- {
- SetComplete(null, null);
- }
- }
- #endregion
-
- #region Receive Record Async Result
- private class SendRecordAsyncResult : IAsyncResult
- {
- private object locker = new object ();
- private AsyncCallback _userCallback;
- private object _userState;
- private Exception _asyncException;
- private ManualResetEvent handle;
- private HandshakeMessage _message;
- private bool completed;
-
- public SendRecordAsyncResult(AsyncCallback userCallback, object userState, HandshakeMessage message)
- {
- _userCallback = userCallback;
- _userState = userState;
- _message = message;
- }
-
- public HandshakeMessage Message
- {
- get { return _message; }
- }
-
- public object AsyncState
- {
- get { return _userState; }
- }
-
- public Exception AsyncException
- {
- get { return _asyncException; }
- }
-
- public bool CompletedWithError
- {
- get {
- if (!IsCompleted)
- return false; // Perhaps throw InvalidOperationExcetion?
-
- return null != _asyncException;
- }
- }
-
- public WaitHandle AsyncWaitHandle
- {
- get {
- lock (locker) {
- if (handle == null)
- handle = new ManualResetEvent (completed);
- }
- return handle;
- }
-
- }
-
- public bool CompletedSynchronously
- {
- get { return false; }
- }
-
- public bool IsCompleted
- {
- get {
- lock (locker) {
- return completed;
- }
- }
- }
-
- public void SetComplete(Exception ex)
- {
- lock (locker) {
- if (completed)
- return;
-
- completed = true;
- if (handle != null)
- handle.Set ();
-
- if (_userCallback != null)
- _userCallback.BeginInvoke (this, null, null);
-
- _asyncException = ex;
- }
- }
-
- public void SetComplete()
- {
- SetComplete(null);
- }
- }
- #endregion
-
- #region Reveive Record Methods
-
- public IAsyncResult BeginReceiveRecord(Stream record, AsyncCallback callback, object state)
- {
- if (this.context.ReceivedConnectionEnd)
- {
- throw new TlsException(
- AlertDescription.InternalError,
- "The session is finished and it's no longer valid.");
- }
-
- record_processing.Reset ();
- byte[] recordTypeBuffer = new byte[1];
-
- ReceiveRecordAsyncResult internalResult = new ReceiveRecordAsyncResult(callback, state, recordTypeBuffer, record);
-
- record.BeginRead(internalResult.InitialBuffer, 0, internalResult.InitialBuffer.Length, new AsyncCallback(InternalReceiveRecordCallback), internalResult);
-
- return internalResult;
- }
-
- private void InternalReceiveRecordCallback(IAsyncResult asyncResult)
- {
- ReceiveRecordAsyncResult internalResult = asyncResult.AsyncState as ReceiveRecordAsyncResult;
- Stream record = internalResult.Record;
-
- try
- {
-
- int bytesRead = internalResult.Record.EndRead(asyncResult);
-
- //We're at the end of the stream. Time to bail.
- if (bytesRead == 0)
- {
- internalResult.SetComplete((byte[])null);
- return;
- }
-
- // Try to read the Record Content Type
- int type = internalResult.InitialBuffer[0];
-
- ContentType contentType = (ContentType)type;
- byte[] buffer = this.ReadRecordBuffer(type, record);
- if (buffer == null)
- {
- // record incomplete (at the moment)
- internalResult.SetComplete((byte[])null);
- return;
- }
-
- // Decrypt message contents if needed
- if (contentType == ContentType.Alert && buffer.Length == 2)
- {
- }
- else if ((this.Context.Read != null) && (this.Context.Read.Cipher != null))
- {
- buffer = this.decryptRecordFragment (contentType, buffer);
- DebugHelper.WriteLine ("Decrypted record data", buffer);
- }
-
- // Process record
- switch (contentType)
- {
- case ContentType.Alert:
- 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:
- this.ProcessChangeCipherSpec();
- break;
-
- case ContentType.ApplicationData:
- break;
-
- case ContentType.Handshake:
- TlsStream message = new TlsStream (buffer);
- while (!message.EOF)
- {
- this.ProcessHandshakeMessage(message);
- }
- break;
-
- case (ContentType)0x80:
- this.context.HandshakeMessages.Write (buffer);
- break;
-
- default:
- throw new TlsException(
- AlertDescription.UnexpectedMessage,
- "Unknown record received from server.");
- }
-
- internalResult.SetComplete(buffer);
- }
- catch (Exception ex)
- {
- internalResult.SetComplete(ex);
- }
-
- }
-
- public byte[] EndReceiveRecord(IAsyncResult asyncResult)
- {
- ReceiveRecordAsyncResult internalResult = asyncResult as ReceiveRecordAsyncResult;
-
- if (null == internalResult)
- throw new ArgumentException("Either the provided async result is null or was not created by this RecordProtocol.");
-
- if (!internalResult.IsCompleted)
- internalResult.AsyncWaitHandle.WaitOne();
-
- if (internalResult.CompletedWithError)
- throw internalResult.AsyncException;
-
- byte[] result = internalResult.ResultingBuffer;
- record_processing.Set ();
- return result;
- }
-
- public byte[] ReceiveRecord(Stream record)
- {
- if (this.context.ReceivedConnectionEnd)
- {
- throw new TlsException(
- AlertDescription.InternalError,
- "The session is finished and it's no longer valid.");
- }
-
- record_processing.Reset ();
- byte[] recordTypeBuffer = new byte[1];
-
- int bytesRead = record.Read(recordTypeBuffer, 0, recordTypeBuffer.Length);
-
- //We're at the end of the stream. Time to bail.
- if (bytesRead == 0)
- {
- return null;
- }
-
- // Try to read the Record Content Type
- int type = recordTypeBuffer[0];
-
- ContentType contentType = (ContentType)type;
- byte[] buffer = this.ReadRecordBuffer(type, record);
- if (buffer == null)
- {
- // record incomplete (at the moment)
- return null;
- }
-
- // Decrypt message contents if needed
- if (contentType == ContentType.Alert && buffer.Length == 2)
- {
- }
- else if ((this.Context.Read != null) && (this.Context.Read.Cipher != null))
- {
- buffer = this.decryptRecordFragment (contentType, buffer);
- DebugHelper.WriteLine ("Decrypted record data", buffer);
- }
-
- // Process record
- switch (contentType)
- {
- case ContentType.Alert:
- 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:
- this.ProcessChangeCipherSpec();
- break;
-
- case ContentType.ApplicationData:
- break;
-
- case ContentType.Handshake:
- TlsStream message = new TlsStream (buffer);
- while (!message.EOF)
- {
- this.ProcessHandshakeMessage(message);
- }
- break;
-
- case (ContentType)0x80:
- this.context.HandshakeMessages.Write (buffer);
- break;
-
- default:
- throw new TlsException(
- AlertDescription.UnexpectedMessage,
- "Unknown record received from server.");
- }
-
- record_processing.Set ();
- return buffer;
- }
-
- private byte[] ReadRecordBuffer (int contentType, Stream record)
- {
- if (!Enum.IsDefined(typeof(ContentType), (ContentType)contentType))
- {
- throw new TlsException(AlertDescription.DecodeError);
- }
-
- byte[] header = new byte[4];
- if (record.Read (header, 0, 4) != 4)
- throw new TlsException ("buffer underrun");
-
- short protocol = (short)((header [0] << 8) | header [1]);
- short length = (short)((header [2] << 8) | header [3]);
-
- // 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 totalReceived = 0;
- byte[] buffer = new byte[length];
- while (totalReceived != length)
- {
- int justReceived = record.Read(buffer, totalReceived, buffer.Length - totalReceived);
-
- //Make sure we get some data so we don't end up in an infinite loop here before shutdown.
- if (0 == justReceived)
- {
- throw new TlsException(AlertDescription.CloseNotify, "Received 0 bytes from stream. It must be closed.");
- }
-
- totalReceived += justReceived;
- }
-
- // Check that the message has a valid protocol version
- if (protocol != this.context.Protocol && this.context.ProtocolNegotiated)
- {
- throw new TlsException(
- AlertDescription.ProtocolVersion, "Invalid protocol version on message received");
- }
-
- DebugHelper.WriteLine("Record data", buffer);
-
- return buffer;
- }
-
- private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
- {
- switch (alertLevel)
- {
- case AlertLevel.Fatal:
- throw new TlsException(alertLevel, alertDesc);
-
- case AlertLevel.Warning:
- default:
- switch (alertDesc)
- {
- case AlertDescription.CloseNotify:
- this.context.ReceivedConnectionEnd = true;
- break;
- }
- break;
- }
- }
-
- #endregion
-
- #region Send Alert Methods
-
- internal void SendAlert(ref Exception ex)
- {
- var tlsEx = ex as TlsException;
- var alert = tlsEx != null ? tlsEx.Alert : new Alert(AlertDescription.InternalError);
-
- try {
- SendAlert(alert);
- } catch (Exception alertEx) {
- ex = new IOException (string.Format ("Error while sending TLS Alert ({0}:{1}): {2}", alert.Level, alert.Description, ex), alertEx);
- }
- }
-
- public void SendAlert(AlertDescription description)
- {
- this.SendAlert(new Alert(description));
- }
-
- public void SendAlert(AlertLevel level, AlertDescription description)
- {
- this.SendAlert(new Alert(level, description));
- }
-
- public void SendAlert(Alert alert)
- {
- AlertLevel level;
- AlertDescription description;
- bool close;
-
- if (alert == null) {
- DebugHelper.WriteLine(">>>> Write Alert NULL");
- level = AlertLevel.Fatal;
- description = AlertDescription.InternalError;
- close = true;
- } else {
- DebugHelper.WriteLine(">>>> Write Alert ({0}|{1})", alert.Description, alert.Message);
- level = alert.Level;
- description = alert.Description;
- close = alert.IsCloseNotify;
- }
-
- // Write record
- this.SendRecord (ContentType.Alert, new byte[2] { (byte) level, (byte) description });
-
- if (close) {
- this.context.SentConnectionEnd = true;
- }
- }
-
- #endregion
-
- #region Send Record Methods
-
- public void SendChangeCipherSpec()
- {
- DebugHelper.WriteLine(">>>> Write Change Cipher Spec");
-
- // Send Change Cipher Spec message with the current cipher
- // or as plain text if this is the initial negotiation
- this.SendRecord(ContentType.ChangeCipherSpec, new byte[] {1});
-
- Context ctx = this.context;
-
- // Reset sequence numbers
- ctx.WriteSequenceNumber = 0;
-
- // all further data sent will be encrypted with the negotiated
- // security parameters (now the current parameters)
- if (ctx is ClientContext) {
- ctx.StartSwitchingSecurityParameters (true);
- } else {
- ctx.EndSwitchingSecurityParameters (false);
- }
- }
-
- public void SendChangeCipherSpec(Stream recordStream)
- {
- DebugHelper.WriteLine(">>>> Write Change Cipher Spec");
-
- byte[] record = this.EncodeRecord (ContentType.ChangeCipherSpec, new byte[] { 1 });
-
- // Send Change Cipher Spec message with the current cipher
- // or as plain text if this is the initial negotiation
- recordStream.Write(record, 0, record.Length);
-
- Context ctx = this.context;
-
- // Reset sequence numbers
- ctx.WriteSequenceNumber = 0;
-
- // all further data sent will be encrypted with the negotiated
- // security parameters (now the current parameters)
- if (ctx is ClientContext) {
- ctx.StartSwitchingSecurityParameters (true);
- } else {
- ctx.EndSwitchingSecurityParameters (false);
- }
- }
-
- public IAsyncResult BeginSendChangeCipherSpec(AsyncCallback callback, object state)
- {
- DebugHelper.WriteLine (">>>> Write Change Cipher Spec");
-
- // Send Change Cipher Spec message with the current cipher
- // or as plain text if this is the initial negotiation
- return this.BeginSendRecord (ContentType.ChangeCipherSpec, new byte[] { 1 }, callback, state);
- }
-
- public void EndSendChangeCipherSpec (IAsyncResult asyncResult)
- {
- this.EndSendRecord (asyncResult);
-
- Context ctx = this.context;
-
- // Reset sequence numbers
- ctx.WriteSequenceNumber = 0;
-
- // all further data sent will be encrypted with the negotiated
- // security parameters (now the current parameters)
- if (ctx is ClientContext) {
- ctx.StartSwitchingSecurityParameters (true);
- } else {
- ctx.EndSwitchingSecurityParameters (false);
- }
- }
-
- public IAsyncResult BeginSendRecord(HandshakeType handshakeType, AsyncCallback callback, object state)
- {
- HandshakeMessage msg = this.GetMessage(handshakeType);
-
- msg.Process();
-
- DebugHelper.WriteLine(">>>> Write handshake record ({0}|{1})", context.Protocol, msg.ContentType);
-
- SendRecordAsyncResult internalResult = new SendRecordAsyncResult(callback, state, msg);
-
- this.BeginSendRecord(msg.ContentType, msg.EncodeMessage(), new AsyncCallback(InternalSendRecordCallback), internalResult);
-
- return internalResult;
- }
-
- private void InternalSendRecordCallback(IAsyncResult ar)
- {
- SendRecordAsyncResult internalResult = ar.AsyncState as SendRecordAsyncResult;
-
- try
- {
- this.EndSendRecord(ar);
-
- // Update session
- internalResult.Message.Update();
-
- // Reset message contents
- internalResult.Message.Reset();
-
- internalResult.SetComplete();
- }
- catch (Exception ex)
- {
- internalResult.SetComplete(ex);
- }
- }
-
- public IAsyncResult BeginSendRecord(ContentType contentType, byte[] recordData, AsyncCallback callback, object state)
- {
- if (this.context.SentConnectionEnd)
- {
- throw new TlsException(
- AlertDescription.InternalError,
- "The session is finished and it's no longer valid.");
- }
-
- byte[] record = this.EncodeRecord(contentType, recordData);
-
- return this.innerStream.BeginWrite(record, 0, record.Length, callback, state);
- }
-
- public void EndSendRecord(IAsyncResult asyncResult)
- {
- if (asyncResult is SendRecordAsyncResult)
- {
- SendRecordAsyncResult internalResult = asyncResult as SendRecordAsyncResult;
- if (!internalResult.IsCompleted)
- internalResult.AsyncWaitHandle.WaitOne();
- if (internalResult.CompletedWithError)
- throw internalResult.AsyncException;
- }
- else
- {
- this.innerStream.EndWrite(asyncResult);
- }
- }
-
- public void SendRecord(ContentType contentType, byte[] recordData)
- {
- IAsyncResult ar = this.BeginSendRecord(contentType, recordData, null, null);
-
- this.EndSendRecord(ar);
- }
-
- public byte[] EncodeRecord(ContentType contentType, byte[] recordData)
- {
- return this.EncodeRecord(
- contentType,
- recordData,
- 0,
- recordData.Length);
- }
-
- public byte[] EncodeRecord(
- ContentType contentType,
- byte[] recordData,
- int offset,
- int count)
- {
- if (this.context.SentConnectionEnd)
- {
- throw new TlsException(
- AlertDescription.InternalError,
- "The session is finished and it's no longer valid.");
- }
-
- TlsStream record = new TlsStream();
-
- int position = offset;
-
- while (position < ( offset + count ))
- {
- short fragmentLength = 0;
- byte[] fragment;
-
- if ((count + offset - position) > Context.MAX_FRAGMENT_SIZE)
- {
- fragmentLength = Context.MAX_FRAGMENT_SIZE;
- }
- else
- {
- fragmentLength = (short)(count + offset - position);
- }
-
- // Fill the fragment data
- fragment = new byte[fragmentLength];
- Buffer.BlockCopy(recordData, position, fragment, 0, fragmentLength);
-
- if ((this.Context.Write != null) && (this.Context.Write.Cipher != null))
- {
- // Encrypt fragment
- fragment = this.encryptRecordFragment (contentType, fragment);
- }
-
- // Write tls message
- record.Write((byte)contentType);
- record.Write(this.context.Protocol);
- record.Write((short)fragment.Length);
- record.Write(fragment);
-
- DebugHelper.WriteLine("Record data", fragment);
-
- // Update buffer position
- position += fragmentLength;
- }
-
- return record.ToArray();
- }
-
- public byte[] EncodeHandshakeRecord(HandshakeType handshakeType)
- {
- HandshakeMessage msg = this.GetMessage(handshakeType);
-
- msg.Process();
-
- var bytes = this.EncodeRecord (msg.ContentType, msg.EncodeMessage ());
-
- msg.Update();
-
- msg.Reset();
-
- return bytes;
- }
-
- #endregion
-
- #region Cryptography Methods
-
- private byte[] encryptRecordFragment(
- ContentType contentType,
- byte[] fragment)
- {
- byte[] mac = null;
-
- // Calculate message MAC
- if (this.Context is ClientContext)
- {
- mac = this.context.Write.Cipher.ComputeClientRecordMAC(contentType, fragment);
- }
- else
- {
- mac = this.context.Write.Cipher.ComputeServerRecordMAC (contentType, fragment);
- }
-
- DebugHelper.WriteLine(">>>> Record MAC", mac);
-
- // Encrypt the message
- byte[] ecr = this.context.Write.Cipher.EncryptRecord (fragment, mac);
-
- // Update sequence number
- this.context.WriteSequenceNumber++;
-
- return ecr;
- }
-
- private byte[] decryptRecordFragment(
- ContentType contentType,
- byte[] fragment)
- {
- byte[] dcrFragment = null;
- byte[] dcrMAC = null;
-
- try
- {
- this.context.Read.Cipher.DecryptRecord (fragment, out dcrFragment, out dcrMAC);
- }
- catch
- {
- if (this.context is ServerContext)
- {
- this.Context.RecordProtocol.SendAlert(AlertDescription.DecryptionFailed);
- }
- throw;
- }
-
- // Generate record MAC
- byte[] mac = null;
-
- if (this.Context is ClientContext)
- {
- mac = this.context.Read.Cipher.ComputeServerRecordMAC(contentType, dcrFragment);
- }
- else
- {
- mac = this.context.Read.Cipher.ComputeClientRecordMAC (contentType, dcrFragment);
- }
-
- DebugHelper.WriteLine(">>>> Record MAC", mac);
-
- // Check record MAC
- if (!Compare (mac, dcrMAC))
- {
- throw new TlsException(AlertDescription.BadRecordMAC, "Bad record MAC");
- }
-
- // Update sequence number
- this.context.ReadSequenceNumber++;
-
- return dcrFragment;
- }
-
- private bool Compare (byte[] array1, byte[] array2)
- {
- if (array1 == null)
- return (array2 == null);
- if (array2 == null)
- return false;
- if (array1.Length != array2.Length)
- return false;
- for (int i = 0; i < array1.Length; i++) {
- if (array1[i] != array2[i])
- return false;
- }
- return true;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityCompressionType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityCompressionType.cs
deleted file mode 100644
index 07f5c49a38a..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityCompressionType.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
- // Information about compression methods allowed by TLS
- // can be found in:
- // draft-ietf-tls-compression-05.txt (http://www.ietf.org/internet-drafts/draft-ietf-tls-compression-05.txt)
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- enum SecurityCompressionType
- {
- None = 0,
- Zlib = 1
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityParameters.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityParameters.cs
deleted file mode 100644
index 3c744ea2402..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityParameters.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls {
-
- // note: other things should be moved here
- internal class SecurityParameters {
-
- private CipherSuite cipher;
- private byte[] clientWriteMAC;
- private byte[] serverWriteMAC;
-
- public SecurityParameters ()
- {
- }
-
- public CipherSuite Cipher {
- get { return cipher; }
- set { cipher = value; }
- }
-
- public byte[] ClientWriteMAC {
- get { return clientWriteMAC; }
- set { clientWriteMAC = value; }
- }
-
- public byte[] ServerWriteMAC {
- get { return serverWriteMAC; }
- set { serverWriteMAC = value; }
- }
-
- public void Clear ()
- {
- // FIXME: clear cipher
- cipher = null;
- }
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityProtocolType.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityProtocolType.cs
deleted file mode 100644
index bf425763924..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SecurityProtocolType.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2014 Xamarin Inc. (http://www.xamarin.com)
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-
-namespace Mono.Security.Protocol.Tls
-{
- [Flags]
-#if INSIDE_SYSTEM
- internal
-#else
- [Serializable]
- public
-#endif
- enum SecurityProtocolType
- {
- Default = -1073741824,
- Ssl2 = 12,
- Ssl3 = 48,
- Tls = 192,
- Tls11 = 768,
- Tls12 = 3072,
- }
-} \ No newline at end of file
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerContext.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerContext.cs
deleted file mode 100644
index a1bbd02ae79..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerContext.cs
+++ /dev/null
@@ -1,118 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.Protocol.Tls.Handshake;
-using Mono.Security.Interface;
-using MonoX509 = Mono.Security.X509;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class ServerContext : Context
- {
- #region Fields
-
- private SslServerStream sslStream;
- private bool request_client_certificate;
- private bool clientCertificateRequired;
-
- #endregion
-
- #region Properties
-
- public SslServerStream SslStream
- {
- get { return this.sslStream; }
- }
-
- public bool ClientCertificateRequired
- {
- get { return this.clientCertificateRequired; }
- }
-
- public bool RequestClientCertificate {
- get { return request_client_certificate; }
- }
-
- #endregion
-
- #region Constructors
-
- public ServerContext(
- SslServerStream stream,
- SecurityProtocolType securityProtocolType,
- X509Certificate serverCertificate,
- bool clientCertificateRequired,
- bool requestClientCertificate)
- : base(securityProtocolType)
- {
- this.sslStream = stream;
- this.clientCertificateRequired = clientCertificateRequired;
- this.request_client_certificate = requestClientCertificate;
-
- // Convert the System.Security cert to a Mono Cert
- MonoX509.X509Certificate cert = new MonoX509.X509Certificate(serverCertificate.GetRawCertData());
-
- // Add server certificate to the certificate collection
- this.ServerSettings.Certificates = new MonoX509.X509CertificateCollection();
- this.ServerSettings.Certificates.Add(cert);
-
- this.ServerSettings.UpdateCertificateRSA();
-
- if (CertificateValidationHelper.SupportsX509Chain) {
- // Build the chain for the certificate and if the chain is correct, add all certificates
- // (except the root certificate [FIRST ONE] ... the client is supposed to know that one,
- // otherwise the whole concept of a trusted chain doesn't work out ...
- MonoX509.X509Chain chain = new MonoX509.X509Chain (MonoX509.X509StoreManager.IntermediateCACertificates);
-
- if (chain.Build (cert)) {
- for (int j = chain.Chain.Count - 1; j > 0; j--)
- ServerSettings.Certificates.Add (chain.Chain [j]);
- }
- }
-
- // Add requested certificate types
- ServerSettings.CertificateTypes = new ClientCertificateType [ServerSettings.Certificates.Count];
- for (int j = 0; j < this.ServerSettings.CertificateTypes.Length; j++)
- ServerSettings.CertificateTypes [j] = ClientCertificateType.RSA;
-
- if (CertificateValidationHelper.SupportsX509Chain) {
- // Add certificate authorities
- MonoX509.X509CertificateCollection trusted = MonoX509.X509StoreManager.TrustedRootCertificates;
- string[] list = new string [trusted.Count];
- int i = 0;
- foreach (MonoX509.X509Certificate root in trusted) {
- list [i++] = root.IssuerName;
- }
- this.ServerSettings.DistinguisedNames = list;
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs
deleted file mode 100644
index f8207297cb3..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs
+++ /dev/null
@@ -1,173 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Globalization;
-using System.IO;
-
-using Mono.Security.Protocol.Tls.Handshake;
-using Mono.Security.Protocol.Tls.Handshake.Server;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class ServerRecordProtocol : RecordProtocol
- {
- TlsClientCertificate cert;
-
- #region Constructors
-
- public ServerRecordProtocol(
- Stream innerStream,
- ServerContext context) : base(innerStream, context)
- {
- }
-
- #endregion
-
- #region Send Messages
-
- public override HandshakeMessage GetMessage(HandshakeType type)
- {
- // Create and process the record message
- HandshakeMessage msg = this.createServerHandshakeMessage(type);
-
- return msg;
- }
-
- #endregion
-
- #region Handshake Processing Methods
-
- protected override void ProcessHandshakeMessage(TlsStream handMsg)
- {
- HandshakeType handshakeType = (HandshakeType)handMsg.ReadByte();
- HandshakeMessage message = null;
-
- // Read message length
- int length = handMsg.ReadInt24();
-
- // Read message data
- byte[] data = new byte[length];
- handMsg.Read(data, 0, length);
-
- // Create and process the server message
- message = this.createClientHandshakeMessage(handshakeType, data);
- message.Process();
-
- // Update the last handshake message
- this.Context.LastHandshakeMsg = handshakeType;
-
- // Update session
- if (message != null)
- {
- message.Update();
- this.Context.HandshakeMessages.WriteByte ((byte) handshakeType);
- this.Context.HandshakeMessages.WriteInt24 (length);
- this.Context.HandshakeMessages.Write (data, 0, data.Length);
- }
- }
-
- #endregion
-
- #region Server Handshake Message Factories
-
- private HandshakeMessage createClientHandshakeMessage(
- HandshakeType type, byte[] buffer)
- {
- var last = context.LastHandshakeMsg;
- switch (type)
- {
- case HandshakeType.ClientHello:
- return new TlsClientHello(this.context, buffer);
-
- case HandshakeType.Certificate:
- if (last != HandshakeType.ClientHello)
- break;
- cert = new TlsClientCertificate(this.context, buffer);
- return cert;
-
- case HandshakeType.ClientKeyExchange:
- if (last == HandshakeType.ClientHello || last == HandshakeType.Certificate)
- return new TlsClientKeyExchange(this.context, buffer);
- break;
-
- case HandshakeType.CertificateVerify:
- if (last == HandshakeType.ClientKeyExchange && cert != null)
- return new TlsClientCertificateVerify(this.context, buffer);
- break;
-
- case HandshakeType.Finished:
- // Certificates are optional, but if provided, they should send a CertificateVerify
- bool hasCert = cert != null && cert.HasCertificate;
- bool check = hasCert ? (last == HandshakeType.CertificateVerify) : (last == HandshakeType.ClientKeyExchange);
- // ChangeCipherSpecDone is not an handshake message (it's a content type) but still needs to be happens before finished
- if (check && context.ChangeCipherSpecDone) {
- context.ChangeCipherSpecDone = false;
- return new TlsClientFinished(this.context, buffer);
- }
- break;
-
- default:
- throw new TlsException(AlertDescription.UnexpectedMessage, String.Format(CultureInfo.CurrentUICulture,
- "Unknown server handshake message received ({0})",
- type.ToString()));
- }
- throw new TlsException (AlertDescription.HandshakeFailiure, String.Format ("Protocol error, unexpected protocol transition from {0} to {1}", last, type));
- }
-
- private HandshakeMessage createServerHandshakeMessage(
- HandshakeType type)
- {
- switch (type)
- {
- case HandshakeType.HelloRequest:
- this.SendRecord(HandshakeType.ClientHello);
- return null;
-
- case HandshakeType.ServerHello:
- return new TlsServerHello(this.context);
-
- case HandshakeType.Certificate:
- return new TlsServerCertificate(this.context);
-
- case HandshakeType.ServerKeyExchange:
- return new TlsServerKeyExchange(this.context);
-
- case HandshakeType.CertificateRequest:
- return new TlsServerCertificateRequest(this.context);
-
- case HandshakeType.ServerHelloDone:
- return new TlsServerHelloDone(this.context);
-
- case HandshakeType.Finished:
- return new TlsServerFinished(this.context);
-
- default:
- throw new InvalidOperationException("Unknown server handshake message type: " + type.ToString() );
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslCipherSuite.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslCipherSuite.cs
deleted file mode 100644
index da95ed15e54..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslCipherSuite.cs
+++ /dev/null
@@ -1,251 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class SslCipherSuite : CipherSuite
- {
- #region Fields
-
- private byte[] pad1;
- private byte[] pad2;
-
- private const int MacHeaderLength = 11;
- private byte[] header;
-
- #endregion
-
- #region Constructors
-
- public SslCipherSuite(
- short code, string name, CipherAlgorithmType cipherAlgorithmType,
- HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType,
- bool exportable, bool blockMode, byte keyMaterialSize,
- byte expandedKeyMaterialSize, short effectiveKeyBytes,
- byte ivSize, byte blockSize) :
- base(code, name, cipherAlgorithmType, hashAlgorithmType,
- exchangeAlgorithmType, exportable, blockMode, keyMaterialSize,
- expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize)
-
- {
- int padLength = (hashAlgorithmType == HashAlgorithmType.Md5) ? 48 : 40;
-
- // Fill pad arrays
- this.pad1 = new byte[padLength];
- this.pad2 = new byte[padLength];
-
- /* Pad the key for inner and outer digest */
- for (int i = 0; i < padLength; ++i)
- {
- this.pad1[i] = 0x36;
- this.pad2[i] = 0x5C;
- }
- }
-
- #endregion
-
- #region MAC Generation Methods
-
- public override byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment)
- {
- HashAlgorithm hash = CreateHashAlgorithm ();
-
- byte[] smac = this.Context.Read.ServerWriteMAC;
- hash.TransformBlock (smac, 0, smac.Length, smac, 0);
- hash.TransformBlock (pad1, 0, pad1.Length, pad1, 0);
-
- if (header == null)
- header = new byte [MacHeaderLength];
-
- ulong seqnum = (Context is ClientContext) ? Context.ReadSequenceNumber : Context.WriteSequenceNumber;
- Write (header, 0, seqnum);
- header [8] = (byte) contentType;
- Write (header, 9, (short)fragment.Length);
- hash.TransformBlock (header, 0, header.Length, header, 0);
- hash.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
- // hack, else the method will allocate a new buffer of the same length (negative half the optimization)
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- byte[] blockHash = hash.Hash;
-
- hash.Initialize ();
-
- hash.TransformBlock (smac, 0, smac.Length, smac, 0);
- hash.TransformBlock (pad2, 0, pad2.Length, pad2, 0);
- hash.TransformBlock (blockHash, 0, blockHash.Length, blockHash, 0);
- // hack again
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- return hash.Hash;
- }
-
- public override byte[] ComputeClientRecordMAC(ContentType contentType, byte[] fragment)
- {
- HashAlgorithm hash = CreateHashAlgorithm ();
-
- byte[] cmac = this.Context.Current.ClientWriteMAC;
- hash.TransformBlock (cmac, 0, cmac.Length, cmac, 0);
- hash.TransformBlock (pad1, 0, pad1.Length, pad1, 0);
-
- if (header == null)
- header = new byte [MacHeaderLength];
-
- ulong seqnum = (Context is ClientContext) ? Context.WriteSequenceNumber : Context.ReadSequenceNumber;
- Write (header, 0, seqnum);
- header [8] = (byte) contentType;
- Write (header, 9, (short)fragment.Length);
- hash.TransformBlock (header, 0, header.Length, header, 0);
- hash.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
- // hack, else the method will allocate a new buffer of the same length (negative half the optimization)
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- byte[] blockHash = hash.Hash;
-
- hash.Initialize ();
-
- hash.TransformBlock (cmac, 0, cmac.Length, cmac, 0);
- hash.TransformBlock (pad2, 0, pad2.Length, pad2, 0);
- hash.TransformBlock (blockHash, 0, blockHash.Length, blockHash, 0);
- // hack again
- hash.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
-
- return hash.Hash;
- }
-
- #endregion
-
- #region Key Generation Methods
-
- public override void ComputeMasterSecret(byte[] preMasterSecret)
- {
- TlsStream masterSecret = new TlsStream();
-
- masterSecret.Write(this.prf(preMasterSecret, "A", this.Context.RandomCS));
- masterSecret.Write(this.prf(preMasterSecret, "BB", this.Context.RandomCS));
- masterSecret.Write(this.prf(preMasterSecret, "CCC", this.Context.RandomCS));
-
- this.Context.MasterSecret = masterSecret.ToArray();
-
- DebugHelper.WriteLine(">>>> MasterSecret", this.Context.MasterSecret);
- }
-
- public override void ComputeKeys()
- {
- // Compute KeyBlock
- TlsStream tmp = new TlsStream();
-
- char labelChar = 'A';
- int count = 1;
-
- while (tmp.Length < this.KeyBlockSize)
- {
- string label = String.Empty;
-
- for (int i = 0; i < count; i++)
- {
- label += labelChar.ToString();
- }
-
- byte[] block = this.prf(this.Context.MasterSecret, label.ToString(), this.Context.RandomSC);
-
- int size = (tmp.Length + block.Length) > this.KeyBlockSize ? (this.KeyBlockSize - (int)tmp.Length) : block.Length;
-
- tmp.Write(block, 0, size);
-
- labelChar++;
- count++;
- }
-
- // Create keyblock
- TlsStream keyBlock = new TlsStream(tmp.ToArray());
-
- this.Context.Negotiating.ClientWriteMAC = keyBlock.ReadBytes(this.HashSize);
- this.Context.Negotiating.ServerWriteMAC = keyBlock.ReadBytes(this.HashSize);
- this.Context.ClientWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
- this.Context.ServerWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
-
- if (this.IvSize != 0)
- {
- this.Context.ClientWriteIV = keyBlock.ReadBytes(this.IvSize);
- this.Context.ServerWriteIV = keyBlock.ReadBytes(this.IvSize);
- }
- else
- {
- this.Context.ClientWriteIV = CipherSuite.EmptyArray;
- this.Context.ServerWriteIV = CipherSuite.EmptyArray;
- }
-
- DebugHelper.WriteLine(">>>> KeyBlock", keyBlock.ToArray());
- DebugHelper.WriteLine(">>>> ClientWriteKey", this.Context.ClientWriteKey);
- DebugHelper.WriteLine(">>>> ClientWriteIV", this.Context.ClientWriteIV);
- DebugHelper.WriteLine(">>>> ClientWriteMAC", this.Context.Negotiating.ClientWriteMAC);
- DebugHelper.WriteLine(">>>> ServerWriteKey", this.Context.ServerWriteKey);
- DebugHelper.WriteLine(">>>> ServerWriteIV", this.Context.ServerWriteIV);
- DebugHelper.WriteLine(">>>> ServerWriteMAC", this.Context.Negotiating.ServerWriteMAC);
-
- ClientSessionCache.SetContextInCache (this.Context);
- // Clear no more needed data
- keyBlock.Reset();
- tmp.Reset();
- }
-
- #endregion
-
- #region Private Methods
-
- private byte[] prf(byte[] secret, string label, byte[] random)
- {
- HashAlgorithm md5 = MD5.Create();
- HashAlgorithm sha = SHA1.Create();
-
- // Compute SHA hash
- TlsStream block = new TlsStream();
- block.Write(Encoding.ASCII.GetBytes(label));
- block.Write(secret);
- block.Write(random);
-
- byte[] shaHash = sha.ComputeHash(block.ToArray(), 0, (int)block.Length);
-
- block.Reset();
-
- // Compute MD5 hash
- block.Write(secret);
- block.Write(shaHash);
-
- byte[] result = md5.ComputeHash(block.ToArray(), 0, (int)block.Length);
-
- // Free resources
- block.Reset();
-
- return result;
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
deleted file mode 100644
index 39680547b05..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs
+++ /dev/null
@@ -1,659 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading;
-
-using Mono.Security.Protocol.Tls.Handshake;
-using Mono.Security.Interface;
-
-namespace Mono.Security.Protocol.Tls
-{
- #region Delegates
-
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- delegate bool CertificateValidationCallback(
- X509Certificate certificate,
- int[] certificateErrors);
-
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- delegate ValidationResult CertificateValidationCallback2 (Mono.Security.X509.X509CertificateCollection collection);
-
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- delegate X509Certificate CertificateSelectionCallback(
- X509CertificateCollection clientCertificates,
- X509Certificate serverCertificate,
- string targetHost,
- X509CertificateCollection serverRequestedCertificates);
-
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- delegate AsymmetricAlgorithm PrivateKeySelectionCallback(
- X509Certificate certificate,
- string targetHost);
-
- #endregion
-
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- class SslClientStream : SslStreamBase
- {
- #region Internal Events
-
- internal event CertificateValidationCallback ServerCertValidation;
- internal event CertificateSelectionCallback ClientCertSelection;
- internal event PrivateKeySelectionCallback PrivateKeySelection;
-
- #endregion
-
- #region Properties
-
- // required by HttpsClientStream for proxy support
- internal Stream InputBuffer
- {
- get { return base.inputBuffer; }
- }
-
- public X509CertificateCollection ClientCertificates
- {
- get { return this.context.ClientSettings.Certificates; }
- }
-
- public X509Certificate SelectedClientCertificate
- {
- get { return this.context.ClientSettings.ClientCertificate; }
- }
-
- #endregion
-
- #region Callback Properties
-
- public CertificateValidationCallback ServerCertValidationDelegate
- {
- get { return this.ServerCertValidation; }
- set { this.ServerCertValidation = value; }
- }
-
- public CertificateSelectionCallback ClientCertSelectionDelegate
- {
- get { return this.ClientCertSelection; }
- set { this.ClientCertSelection = value; }
- }
-
- public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
- {
- get { return this.PrivateKeySelection; }
- set { this.PrivateKeySelection = value; }
- }
-
- #endregion
-
- public event CertificateValidationCallback2 ServerCertValidation2;
-
- #region Constructors
-
- public SslClientStream(
- Stream stream,
- string targetHost,
- bool ownsStream)
- : this(
- stream, targetHost, ownsStream,
- SecurityProtocolType.Default, null)
- {
- }
-
- public SslClientStream(
- Stream stream,
- string targetHost,
- X509Certificate clientCertificate)
- : this(
- stream, targetHost, false, SecurityProtocolType.Default,
- new X509CertificateCollection(new X509Certificate[]{clientCertificate}))
- {
- }
-
- public SslClientStream(
- Stream stream,
- string targetHost,
- X509CertificateCollection clientCertificates) :
- this(
- stream, targetHost, false, SecurityProtocolType.Default,
- clientCertificates)
- {
- }
-
- public SslClientStream(
- Stream stream,
- string targetHost,
- bool ownsStream,
- SecurityProtocolType securityProtocolType)
- : this(
- stream, targetHost, ownsStream, securityProtocolType,
- new X509CertificateCollection())
- {
- }
-
- public SslClientStream(
- Stream stream,
- string targetHost,
- bool ownsStream,
- SecurityProtocolType securityProtocolType,
- X509CertificateCollection clientCertificates):
- base(stream, ownsStream)
- {
- if (targetHost == null || targetHost.Length == 0)
- {
- throw new ArgumentNullException("targetHost is null or an empty string.");
- }
-
- this.context = new ClientContext(
- this,
- securityProtocolType,
- targetHost,
- clientCertificates);
-
- this.protocol = new ClientRecordProtocol(innerStream, (ClientContext)this.context);
- }
-
- #endregion
-
- #region Finalizer
-
- ~SslClientStream()
- {
- base.Dispose(false);
- }
-
- #endregion
-
- #region IDisposable Methods
-
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
-
- if (disposing)
- {
- this.ServerCertValidation = null;
- this.ClientCertSelection = null;
- this.PrivateKeySelection = null;
- this.ServerCertValidation2 = null;
- }
- }
-
- #endregion
-
- #region Handshake Methods
-
- /*
- Client Server
-
- ClientHello -------->
- ServerHello
- Certificate*
- ServerKeyExchange*
- CertificateRequest*
- <-------- ServerHelloDone
- Certificate*
- ClientKeyExchange
- CertificateVerify*
- [ChangeCipherSpec]
- Finished -------->
- [ChangeCipherSpec]
- <-------- Finished
- Application Data <-------> Application Data
-
- Fig. 1 - Message flow for a full handshake
- */
-
- private void SafeEndReceiveRecord (IAsyncResult ar, bool ignoreEmpty = false)
- {
- byte[] record = this.protocol.EndReceiveRecord (ar);
- if (!ignoreEmpty && ((record == null) || (record.Length == 0))) {
- throw new TlsException (
- AlertDescription.HandshakeFailiure,
- "The server stopped the handshake.");
- }
- }
-
- private enum NegotiateState
- {
- SentClientHello,
- ReceiveClientHelloResponse,
- SentCipherSpec,
- ReceiveCipherSpecResponse,
- SentKeyExchange,
- ReceiveFinishResponse,
- SentFinished,
- };
-
- private class NegotiateAsyncResult : IAsyncResult
- {
- private object locker = new object ();
- private AsyncCallback _userCallback;
- private object _userState;
- private Exception _asyncException;
- private ManualResetEvent handle;
- private NegotiateState _state;
- private bool completed;
-
- public NegotiateAsyncResult(AsyncCallback userCallback, object userState, NegotiateState state)
- {
- _userCallback = userCallback;
- _userState = userState;
- _state = state;
- }
-
- public NegotiateState State
- {
- get { return _state; }
- set { _state = value; }
- }
-
- public object AsyncState
- {
- get { return _userState; }
- }
-
- public Exception AsyncException
- {
- get { return _asyncException; }
- }
-
- public bool CompletedWithError
- {
- get {
- if (!IsCompleted)
- return false; // Perhaps throw InvalidOperationExcetion?
-
- return null != _asyncException;
- }
- }
-
- public WaitHandle AsyncWaitHandle
- {
- get {
- lock (locker) {
- if (handle == null)
- handle = new ManualResetEvent (completed);
- }
- return handle;
- }
-
- }
-
- public bool CompletedSynchronously
- {
- get { return false; }
- }
-
- public bool IsCompleted
- {
- get {
- lock (locker) {
- return completed;
- }
- }
- }
-
- public void SetComplete(Exception ex)
- {
- lock (locker) {
- if (completed)
- return;
-
- completed = true;
- if (handle != null)
- handle.Set ();
-
- if (_userCallback != null)
- _userCallback.BeginInvoke (this, null, null);
-
- _asyncException = ex;
- }
- }
-
- public void SetComplete()
- {
- SetComplete(null);
- }
- }
-
- internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
- {
- if (this.context.HandshakeState != HandshakeState.None) {
- this.context.Clear ();
- }
-
- // Obtain supported cipher suites
- this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (false, context.SecurityProtocol);
-
- // Set handshake state
- this.context.HandshakeState = HandshakeState.Started;
-
- NegotiateAsyncResult result = new NegotiateAsyncResult (callback, state, NegotiateState.SentClientHello);
-
- // Begin sending the client hello
- this.protocol.BeginSendRecord (HandshakeType.ClientHello, NegotiateAsyncWorker, result);
-
- return result;
- }
-
- internal override void EndNegotiateHandshake (IAsyncResult result)
- {
- NegotiateAsyncResult negotiate = result as NegotiateAsyncResult;
-
- if (negotiate == null)
- throw new ArgumentNullException ();
- if (!negotiate.IsCompleted)
- negotiate.AsyncWaitHandle.WaitOne();
- if (negotiate.CompletedWithError)
- throw negotiate.AsyncException;
- }
-
- private void NegotiateAsyncWorker (IAsyncResult result)
- {
- NegotiateAsyncResult negotiate = result.AsyncState as NegotiateAsyncResult;
-
- try
- {
- switch (negotiate.State)
- {
- case NegotiateState.SentClientHello:
- this.protocol.EndSendRecord (result);
-
- // we are now ready to ready the receive the hello response.
- negotiate.State = NegotiateState.ReceiveClientHelloResponse;
-
- // Start reading the client hello response
- this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
- break;
-
- case NegotiateState.ReceiveClientHelloResponse:
- this.SafeEndReceiveRecord (result, true);
-
- if (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone &&
- (!this.context.AbbreviatedHandshake || this.context.LastHandshakeMsg != HandshakeType.ServerHello)) {
- // Read next record (skip empty, e.g. warnings alerts)
- this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
- break;
- }
-
- // special case for abbreviated handshake where no ServerHelloDone is sent from the server
- if (this.context.AbbreviatedHandshake) {
- ClientSessionCache.SetContextFromCache (this.context);
- this.context.Negotiating.Cipher.ComputeKeys ();
- this.context.Negotiating.Cipher.InitializeCipher ();
-
- negotiate.State = NegotiateState.SentCipherSpec;
-
- // Send Change Cipher Spec message with the current cipher
- // or as plain text if this is the initial negotiation
- this.protocol.BeginSendChangeCipherSpec(NegotiateAsyncWorker, negotiate);
- } else {
- // Send client certificate if requested
- // even if the server ask for it it _may_ still be optional
- bool clientCertificate = this.context.ServerSettings.CertificateRequest;
-
- using (var memstream = new MemoryStream())
- {
- // NOTE: sadly SSL3 and TLS1 differs in how they handle this and
- // the current design doesn't allow a very cute way to handle
- // SSL3 alert warning for NoCertificate (41).
- if (this.context.SecurityProtocol == SecurityProtocolType.Ssl3)
- {
- clientCertificate = ((this.context.ClientSettings.Certificates != null) &&
- (this.context.ClientSettings.Certificates.Count > 0));
- // this works well with OpenSSL (but only for SSL3)
- }
-
- byte[] record = null;
-
- if (clientCertificate)
- {
- record = this.protocol.EncodeHandshakeRecord(HandshakeType.Certificate);
- memstream.Write(record, 0, record.Length);
- }
-
- // Send Client Key Exchange
- record = this.protocol.EncodeHandshakeRecord(HandshakeType.ClientKeyExchange);
- memstream.Write(record, 0, record.Length);
-
- // Now initialize session cipher with the generated keys
- this.context.Negotiating.Cipher.InitializeCipher();
-
- // Send certificate verify if requested (optional)
- if (clientCertificate && (this.context.ClientSettings.ClientCertificate != null))
- {
- record = this.protocol.EncodeHandshakeRecord(HandshakeType.CertificateVerify);
- memstream.Write(record, 0, record.Length);
- }
-
- // send the chnage cipher spec.
- this.protocol.SendChangeCipherSpec(memstream);
-
- // Send Finished message
- record = this.protocol.EncodeHandshakeRecord(HandshakeType.Finished);
- memstream.Write(record, 0, record.Length);
-
- negotiate.State = NegotiateState.SentKeyExchange;
-
- // send all the records.
- this.innerStream.BeginWrite (memstream.GetBuffer (), 0, (int)memstream.Length, NegotiateAsyncWorker, negotiate);
- }
- }
- break;
-
- case NegotiateState.SentKeyExchange:
- this.innerStream.EndWrite (result);
-
- negotiate.State = NegotiateState.ReceiveFinishResponse;
-
- this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
-
- break;
-
- case NegotiateState.ReceiveFinishResponse:
- this.SafeEndReceiveRecord (result);
-
- // Read record until server finished is received
- if (this.context.HandshakeState != HandshakeState.Finished) {
- // If all goes well this will process messages:
- // Change Cipher Spec
- // Server finished
- this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
- }
- else {
- // Reset Handshake messages information
- this.context.HandshakeMessages.Reset ();
-
- // Clear Key Info
- this.context.ClearKeyInfo();
-
- negotiate.SetComplete ();
- }
- break;
-
-
- case NegotiateState.SentCipherSpec:
- this.protocol.EndSendChangeCipherSpec (result);
-
- negotiate.State = NegotiateState.ReceiveCipherSpecResponse;
-
- // Start reading the cipher spec response
- this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
- break;
-
- case NegotiateState.ReceiveCipherSpecResponse:
- this.SafeEndReceiveRecord (result, true);
-
- if (this.context.HandshakeState != HandshakeState.Finished)
- {
- this.protocol.BeginReceiveRecord (this.innerStream, NegotiateAsyncWorker, negotiate);
- }
- else
- {
- negotiate.State = NegotiateState.SentFinished;
- this.protocol.BeginSendRecord(HandshakeType.Finished, NegotiateAsyncWorker, negotiate);
- }
- break;
-
- case NegotiateState.SentFinished:
- this.protocol.EndSendRecord (result);
-
- // Reset Handshake messages information
- this.context.HandshakeMessages.Reset ();
-
- // Clear Key Info
- this.context.ClearKeyInfo();
-
- negotiate.SetComplete ();
-
- break;
- }
- }
- catch (TlsException ex)
- {
- try {
- Exception e = ex;
- this.protocol.SendAlert(ref e);
- } catch {
- }
- negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex));
- }
- catch (Exception ex)
- {
- try {
- this.protocol.SendAlert(AlertDescription.InternalError);
- } catch {
- }
- negotiate.SetComplete(new IOException("The authentication or decryption has failed.", ex));
- }
- }
-
- #endregion
-
- #region Event Methods
-
- internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
- {
- if (this.ClientCertSelection != null)
- {
- return this.ClientCertSelection(
- clientCertificates,
- serverCertificate,
- targetHost,
- serverRequestedCertificates);
- }
-
- return null;
- }
-
- internal override bool HaveRemoteValidation2Callback {
- get { return ServerCertValidation2 != null; }
- }
-
- internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
- {
- CertificateValidationCallback2 cb = ServerCertValidation2;
- if (cb != null)
- return cb (collection);
- return null;
- }
-
- internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
- {
- if (this.ServerCertValidation != null)
- {
- return this.ServerCertValidation(certificate, errors);
- }
-
- return (errors != null && errors.Length == 0);
- }
-
- internal virtual bool RaiseServerCertificateValidation(
- X509Certificate certificate,
- int[] certificateErrors)
- {
- return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
- }
-
- internal virtual ValidationResult RaiseServerCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
- {
- return base.RaiseRemoteCertificateValidation2 (collection);
- }
-
- internal X509Certificate RaiseClientCertificateSelection(
- X509CertificateCollection clientCertificates,
- X509Certificate serverCertificate,
- string targetHost,
- X509CertificateCollection serverRequestedCertificates)
- {
- return base.RaiseLocalCertificateSelection(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
- }
-
- internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
- {
- if (this.PrivateKeySelection != null)
- {
- return this.PrivateKeySelection(certificate, targetHost);
- }
-
- return null;
- }
-
- internal AsymmetricAlgorithm RaisePrivateKeySelection(
- X509Certificate certificate,
- string targetHost)
- {
- return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslHandshakeHash.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslHandshakeHash.cs
deleted file mode 100644
index 2a670b40d51..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslHandshakeHash.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class SslHandshakeHash : System.Security.Cryptography.HashAlgorithm
- {
- #region Fields
-
- private HashAlgorithm md5;
- private HashAlgorithm sha;
- private bool hashing;
- private byte[] secret;
- private byte[] innerPadMD5;
- private byte[] outerPadMD5;
- private byte[] innerPadSHA;
- private byte[] outerPadSHA;
-
- #endregion
-
- #region Constructors
-
- public SslHandshakeHash(byte[] secret)
- {
- // Create md5 and sha1 hashes
- this.md5 = MD5.Create ();
- this.sha = SHA1.Create ();
-
- // Set HashSizeValue
- this.HashSizeValue = md5.HashSize + sha.HashSize;
-
- // Update secret
- this.secret = secret;
-
- this.Initialize();
- }
-
- #endregion
-
- #region Methods
-
- public override void Initialize()
- {
- this.md5.Initialize();
- this.sha.Initialize();
- this.initializePad();
- this.hashing = false;
- }
-
- protected override byte[] HashFinal()
- {
- if (!this.hashing)
- {
- this.hashing = true;
- }
-
- // Finalize the md5 hash
- this.md5.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
- this.md5.TransformFinalBlock(this.innerPadMD5, 0, this.innerPadMD5.Length);
-
- byte[] firstResultMD5 = this.md5.Hash;
-
- this.md5.Initialize();
- this.md5.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
- this.md5.TransformBlock(this.outerPadMD5, 0, this.outerPadMD5.Length, this.outerPadMD5, 0);
- this.md5.TransformFinalBlock(firstResultMD5, 0, firstResultMD5.Length);
-
- // Finalize the sha1 hash
- this.sha.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
- this.sha.TransformFinalBlock(this.innerPadSHA, 0, this.innerPadSHA.Length);
-
- byte[] firstResultSHA = this.sha.Hash;
-
- this.sha.Initialize();
- this.sha.TransformBlock(this.secret, 0, this.secret.Length, this.secret, 0);
- this.sha.TransformBlock(this.outerPadSHA, 0, this.outerPadSHA.Length, this.outerPadSHA, 0);
- this.sha.TransformFinalBlock(firstResultSHA, 0, firstResultSHA.Length);
-
- this.Initialize();
-
- byte[] result = new byte[36];
-
- Buffer.BlockCopy(this.md5.Hash, 0, result, 0, 16);
- Buffer.BlockCopy(this.sha.Hash, 0, result, 16, 20);
-
- return result;
- }
-
- protected override void HashCore(byte[] array, int ibStart, int cbSize)
- {
- if (!this.hashing)
- {
- this.hashing = true;
- }
-
- this.md5.TransformBlock(array, ibStart, cbSize, array, ibStart);
- this.sha.TransformBlock(array, ibStart, cbSize, array, ibStart);
- }
-
- public byte[] CreateSignature(RSA rsa)
- {
- if (rsa == null)
- {
- throw new CryptographicUnexpectedOperationException ("missing key");
- }
-
- RSASslSignatureFormatter f = new RSASslSignatureFormatter(rsa);
- f.SetHashAlgorithm("MD5SHA1");
-
- return f.CreateSignature(this.Hash);
- }
-
- public bool VerifySignature(RSA rsa, byte[] rgbSignature)
- {
- if (rsa == null)
- {
- throw new CryptographicUnexpectedOperationException ("missing key");
- }
- if (rgbSignature == null)
- {
- throw new ArgumentNullException ("rgbSignature");
- }
-
- RSASslSignatureDeformatter d = new RSASslSignatureDeformatter(rsa);
- d.SetHashAlgorithm("MD5SHA1");
-
- return d.VerifySignature(this.Hash, rgbSignature);
- }
-
- #endregion
-
- #region Private Methods
-
- private void initializePad()
- {
- // Fill md5 arrays
- this.innerPadMD5 = new byte[48];
- this.outerPadMD5 = new byte[48];
-
- /* Pad the key for inner and outer digest */
- for (int i = 0; i < 48; ++i)
- {
- this.innerPadMD5[i] = 0x36;
- this.outerPadMD5[i] = 0x5C;
- }
-
- // Fill sha arrays
- this.innerPadSHA = new byte[40];
- this.outerPadSHA = new byte[40];
-
- /* Pad the key for inner and outer digest */
- for (int i = 0; i < 40; ++i)
- {
- this.innerPadSHA[i] = 0x36;
- this.outerPadSHA[i] = 0x5C;
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
deleted file mode 100644
index f93ab4425e0..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslServerStream.cs
+++ /dev/null
@@ -1,332 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-
-using Mono.Security.Protocol.Tls.Handshake;
-using Mono.Security.Interface;
-
-namespace Mono.Security.Protocol.Tls
-{
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- class SslServerStream : SslStreamBase
- {
- #region Internal Events
-
- internal event CertificateValidationCallback ClientCertValidation;
- internal event PrivateKeySelectionCallback PrivateKeySelection;
-
- #endregion
-
- #region Properties
-
- public X509Certificate ClientCertificate
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.ClientSettings.ClientCertificate;
- }
-
- return null;
- }
- }
-
- #endregion
-
- #region Callback Properties
-
- public CertificateValidationCallback ClientCertValidationDelegate
- {
- get { return this.ClientCertValidation; }
- set { this.ClientCertValidation = value; }
- }
-
- public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
- {
- get { return this.PrivateKeySelection; }
- set { this.PrivateKeySelection = value; }
- }
-
- #endregion
-
- public event CertificateValidationCallback2 ClientCertValidation2;
- #region Constructors
-
- public SslServerStream(
- Stream stream,
- X509Certificate serverCertificate) : this(
- stream,
- serverCertificate,
- false,
- false,
- SecurityProtocolType.Default)
- {
- }
-
- public SslServerStream(
- Stream stream,
- X509Certificate serverCertificate,
- bool clientCertificateRequired,
- bool ownsStream): this(
- stream,
- serverCertificate,
- clientCertificateRequired,
- ownsStream,
- SecurityProtocolType.Default)
- {
- }
-
- public SslServerStream(
- Stream stream,
- X509Certificate serverCertificate,
- bool clientCertificateRequired,
- bool requestClientCertificate,
- bool ownsStream)
- : this (stream, serverCertificate, clientCertificateRequired, requestClientCertificate, ownsStream, SecurityProtocolType.Default)
- {
- }
-
- public SslServerStream(
- Stream stream,
- X509Certificate serverCertificate,
- bool clientCertificateRequired,
- bool ownsStream,
- SecurityProtocolType securityProtocolType)
- : this (stream, serverCertificate, clientCertificateRequired, false, ownsStream, securityProtocolType)
- {
- }
-
- public SslServerStream(
- Stream stream,
- X509Certificate serverCertificate,
- bool clientCertificateRequired,
- bool requestClientCertificate,
- bool ownsStream,
- SecurityProtocolType securityProtocolType)
- : base(stream, ownsStream)
- {
- this.context = new ServerContext(
- this,
- securityProtocolType,
- serverCertificate,
- clientCertificateRequired,
- requestClientCertificate);
-
- this.protocol = new ServerRecordProtocol(innerStream, (ServerContext)this.context);
- }
-
- #endregion
-
- #region Finalizer
-
- ~SslServerStream()
- {
- this.Dispose(false);
- }
-
- #endregion
-
- #region IDisposable Methods
-
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
-
- if (disposing)
- {
- this.ClientCertValidation = null;
- this.PrivateKeySelection = null;
- }
- }
-
- #endregion
-
- #region Handsake Methods
-
- /*
- Client Server
-
- ClientHello -------->
- ServerHello
- Certificate*
- ServerKeyExchange*
- CertificateRequest*
- <-------- ServerHelloDone
- Certificate*
- ClientKeyExchange
- CertificateVerify*
- [ChangeCipherSpec]
- Finished -------->
- [ChangeCipherSpec]
- <-------- Finished
- Application Data <-------> Application Data
-
- Fig. 1 - Message flow for a full handshake
- */
-
- internal override IAsyncResult BeginNegotiateHandshake(AsyncCallback callback, object state)
- {
- // Reset the context if needed
- if (this.context.HandshakeState != HandshakeState.None)
- {
- this.context.Clear();
- }
-
- // Obtain supported cipher suites
- this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (true, context.SecurityProtocol);
-
- // Set handshake state
- this.context.HandshakeState = HandshakeState.Started;
-
- // Receive Client Hello message
- return this.protocol.BeginReceiveRecord(this.innerStream, callback, state);
-
- }
-
- internal override void EndNegotiateHandshake(IAsyncResult asyncResult)
- {
- // Receive Client Hello message and ignore it
- this.protocol.EndReceiveRecord(asyncResult);
-
- // If received message is not an ClientHello send a
- // Fatal Alert
- if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
- {
- this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
- }
-
- // Send ServerHello message
- this.protocol.SendRecord(HandshakeType.ServerHello);
-
- // Send ServerCertificate message
- this.protocol.SendRecord(HandshakeType.Certificate);
-
- // If the client certificate is required send the CertificateRequest message
- if (((ServerContext)this.context).ClientCertificateRequired ||
- ((ServerContext)this.context).RequestClientCertificate)
- {
- this.protocol.SendRecord(HandshakeType.CertificateRequest);
- }
-
- // Send ServerHelloDone message
- this.protocol.SendRecord(HandshakeType.ServerHelloDone);
-
- // Receive client response, until the Client Finished message
- // is received. IE can be interrupted at this stage and never
- // complete the handshake
- while (this.context.LastHandshakeMsg != HandshakeType.Finished)
- {
- byte[] record = this.protocol.ReceiveRecord(this.innerStream);
- if ((record == null) || (record.Length == 0))
- {
- throw new TlsException(
- AlertDescription.HandshakeFailiure,
- "The client stopped the handshake.");
- }
- }
-
- // Send ChangeCipherSpec and ServerFinished messages
- this.protocol.SendChangeCipherSpec();
- this.protocol.SendRecord (HandshakeType.Finished);
-
- // The handshake is finished
- this.context.HandshakeState = HandshakeState.Finished;
-
- // Reset Handshake messages information
- this.context.HandshakeMessages.Reset ();
-
- // Clear Key Info
- this.context.ClearKeyInfo();
- }
-
- #endregion
-
- #region Event Methods
-
- internal override X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates)
- {
- throw new NotSupportedException();
- }
-
- internal override bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors)
- {
- if (this.ClientCertValidation != null)
- {
- return this.ClientCertValidation(certificate, errors);
- }
-
- return (errors != null && errors.Length == 0);
- }
-
- internal override bool HaveRemoteValidation2Callback {
- get { return ClientCertValidation2 != null; }
- }
-
- internal override ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
- {
- CertificateValidationCallback2 cb = ClientCertValidation2;
- if (cb != null)
- return cb (collection);
- return null;
- }
-
- internal bool RaiseClientCertificateValidation(
- X509Certificate certificate,
- int[] certificateErrors)
- {
- return base.RaiseRemoteCertificateValidation(certificate, certificateErrors);
- }
-
- internal override AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost)
- {
- if (this.PrivateKeySelection != null)
- {
- return this.PrivateKeySelection(certificate, targetHost);
- }
-
- return null;
- }
-
- internal AsymmetricAlgorithm RaisePrivateKeySelection(
- X509Certificate certificate,
- string targetHost)
- {
- return base.RaiseLocalPrivateKeySelection(certificate, targetHost);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs
deleted file mode 100644
index ffd1adc2050..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs
+++ /dev/null
@@ -1,1224 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Collections;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Security.Cryptography;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading;
-
-using Mono.Security.Interface;
-
-namespace Mono.Security.Protocol.Tls
-{
-#if INSIDE_SYSTEM
- internal
-#else
- public
-#endif
- abstract class SslStreamBase: Stream, IDisposable
- {
- private delegate void AsyncHandshakeDelegate(InternalAsyncResult asyncResult, bool fromWrite);
-
- #region Fields
-
- static ManualResetEvent record_processing = new ManualResetEvent (true);
-
- internal Stream innerStream;
- internal MemoryStream inputBuffer;
- internal Context context;
- internal RecordProtocol protocol;
- internal bool ownsStream;
- private volatile bool disposed;
- private bool checkCertRevocationStatus;
- private object negotiate;
- private object read;
- private object write;
- private ManualResetEvent negotiationComplete;
-
- #endregion
-
-
- #region Constructors
-
- protected SslStreamBase(
- Stream stream,
- bool ownsStream)
- {
- if (stream == null)
- {
- throw new ArgumentNullException("stream is null.");
- }
- if (!stream.CanRead || !stream.CanWrite)
- {
- throw new ArgumentNullException("stream is not both readable and writable.");
- }
-
- this.inputBuffer = new MemoryStream();
- this.innerStream = stream;
- this.ownsStream = ownsStream;
- this.negotiate = new object();
- this.read = new object();
- this.write = new object();
- this.negotiationComplete = new ManualResetEvent(false);
- }
-
- #endregion
-
- #region Handshakes
- private void AsyncHandshakeCallback(IAsyncResult asyncResult)
- {
- InternalAsyncResult internalResult = asyncResult.AsyncState as InternalAsyncResult;
-
- try
- {
- try
- {
- this.EndNegotiateHandshake(asyncResult);
- }
- catch (Exception ex)
- {
- this.protocol.SendAlert(ref ex);
- throw new IOException("The authentication or decryption has failed.", ex);
- }
-
- if (internalResult.ProceedAfterHandshake)
- {
- //kick off the read or write process (whichever called us) after the handshake is complete
- if (internalResult.FromWrite)
- {
- InternalBeginWrite(internalResult);
- }
- else
- {
- InternalBeginRead(internalResult);
- }
- negotiationComplete.Set();
- }
- else
- {
- negotiationComplete.Set();
- internalResult.SetComplete();
- }
-
- }
- catch (Exception ex)
- {
- negotiationComplete.Set();
- internalResult.SetComplete(ex);
- }
- }
-
- internal bool MightNeedHandshake
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return false;
- }
- else
- {
- lock (this.negotiate)
- {
- return (this.context.HandshakeState != HandshakeState.Finished);
- }
- }
- }
- }
-
- internal void NegotiateHandshake()
- {
- if (this.MightNeedHandshake)
- {
- InternalAsyncResult ar = new InternalAsyncResult(null, null, null, 0, 0, false, false);
-
- //if something already started negotiation, wait for it.
- //otherwise end it ourselves.
- if (!BeginNegotiateHandshake(ar))
- {
- this.negotiationComplete.WaitOne();
- }
- else
- {
- this.EndNegotiateHandshake(ar);
- }
- }
- }
-
- #endregion
-
- #region Abstracts/Virtuals
-
- internal abstract IAsyncResult BeginNegotiateHandshake (AsyncCallback callback, object state);
- internal abstract void EndNegotiateHandshake (IAsyncResult result);
-
- internal abstract X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates,
- X509Certificate serverCertificate,
- string targetHost,
- X509CertificateCollection serverRequestedCertificates);
-
- internal abstract bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors);
- internal abstract ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection);
- internal abstract bool HaveRemoteValidation2Callback { get; }
-
- internal abstract AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost);
-
- #endregion
-
- #region Event Methods
-
- internal X509Certificate RaiseLocalCertificateSelection(X509CertificateCollection certificates,
- X509Certificate remoteCertificate,
- string targetHost,
- X509CertificateCollection requestedCertificates)
- {
- return OnLocalCertificateSelection(certificates, remoteCertificate, targetHost, requestedCertificates);
- }
-
- internal bool RaiseRemoteCertificateValidation(X509Certificate certificate, int[] errors)
- {
- return OnRemoteCertificateValidation(certificate, errors);
- }
-
- internal ValidationResult RaiseRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
- {
- return OnRemoteCertificateValidation2 (collection);
- }
-
- internal AsymmetricAlgorithm RaiseLocalPrivateKeySelection(
- X509Certificate certificate,
- string targetHost)
- {
- return OnLocalPrivateKeySelection(certificate, targetHost);
- }
- #endregion
-
- #region Security Properties
-
- public bool CheckCertRevocationStatus
- {
- get { return this.checkCertRevocationStatus; }
- set { this.checkCertRevocationStatus = value; }
- }
-
- public CipherAlgorithmType CipherAlgorithm
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.Current.Cipher.CipherAlgorithmType;
- }
-
- return CipherAlgorithmType.None;
- }
- }
-
- public int CipherStrength
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.Current.Cipher.EffectiveKeyBits;
- }
-
- return 0;
- }
- }
-
- public HashAlgorithmType HashAlgorithm
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.Current.Cipher.HashAlgorithmType;
- }
-
- return HashAlgorithmType.None;
- }
- }
-
- public int HashStrength
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.Current.Cipher.HashSize * 8;
- }
-
- return 0;
- }
- }
-
- public int KeyExchangeStrength
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.ServerSettings.Certificates[0].RSA.KeySize;
- }
-
- return 0;
- }
- }
-
- public ExchangeAlgorithmType KeyExchangeAlgorithm
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.Current.Cipher.ExchangeAlgorithmType;
- }
-
- return ExchangeAlgorithmType.None;
- }
- }
-
- public SecurityProtocolType SecurityProtocol
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- return this.context.SecurityProtocol;
- }
-
- return 0;
- }
- }
-
- public X509Certificate ServerCertificate
- {
- get
- {
- if (this.context.HandshakeState == HandshakeState.Finished)
- {
- if (this.context.ServerSettings.Certificates != null &&
- this.context.ServerSettings.Certificates.Count > 0)
- {
- return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData);
- }
- }
-
- return null;
- }
- }
-
- // this is used by Mono's certmgr tool to download certificates
- internal Mono.Security.X509.X509CertificateCollection ServerCertificates
- {
- get { return context.ServerSettings.Certificates; }
- }
-
- #endregion
-
- #region Internal Async Result/State Class
-
- private class InternalAsyncResult : IAsyncResult
- {
- private object locker = new object ();
- private AsyncCallback _userCallback;
- private object _userState;
- private Exception _asyncException;
- private ManualResetEvent handle;
- private bool completed;
- private int _bytesRead;
- private bool _fromWrite;
- private bool _proceedAfterHandshake;
-
- private byte[] _buffer;
- private int _offset;
- private int _count;
-
- public InternalAsyncResult(AsyncCallback userCallback, object userState, byte[] buffer, int offset, int count, bool fromWrite, bool proceedAfterHandshake)
- {
- _userCallback = userCallback;
- _userState = userState;
- _buffer = buffer;
- _offset = offset;
- _count = count;
- _fromWrite = fromWrite;
- _proceedAfterHandshake = proceedAfterHandshake;
- }
-
- public bool ProceedAfterHandshake
- {
- get { return _proceedAfterHandshake; }
- }
-
- public bool FromWrite
- {
- get { return _fromWrite; }
- }
-
- public byte[] Buffer
- {
- get { return _buffer; }
- }
-
- public int Offset
- {
- get { return _offset; }
- }
-
- public int Count
- {
- get { return _count; }
- }
-
- public int BytesRead
- {
- get { return _bytesRead; }
- }
-
- public object AsyncState
- {
- get { return _userState; }
- }
-
- public Exception AsyncException
- {
- get { return _asyncException; }
- }
-
- public bool CompletedWithError
- {
- get {
- if (IsCompleted == false)
- return false;
- return null != _asyncException;
- }
- }
-
- public WaitHandle AsyncWaitHandle
- {
- get {
- lock (locker) {
- if (handle == null)
- handle = new ManualResetEvent (completed);
- }
- return handle;
- }
- }
-
- public bool CompletedSynchronously
- {
- get { return false; }
- }
-
- public bool IsCompleted
- {
- get {
- lock (locker)
- return completed;
- }
- }
-
- private void SetComplete(Exception ex, int bytesRead)
- {
- lock (locker) {
- if (completed)
- return;
-
- completed = true;
- _asyncException = ex;
- _bytesRead = bytesRead;
- if (handle != null)
- handle.Set ();
- }
- if (_userCallback != null)
- _userCallback.BeginInvoke (this, null, null);
- }
-
- public void SetComplete(Exception ex)
- {
- SetComplete(ex, 0);
- }
-
- public void SetComplete(int bytesRead)
- {
- SetComplete(null, bytesRead);
- }
-
- public void SetComplete()
- {
- SetComplete(null, 0);
- }
- }
- #endregion
-
- #region Stream Overrides and Async Stream Operations
-
- private bool BeginNegotiateHandshake(InternalAsyncResult asyncResult)
- {
- try
- {
- lock (this.negotiate)
- {
- if (this.context.HandshakeState == HandshakeState.None)
- {
- this.BeginNegotiateHandshake(new AsyncCallback(AsyncHandshakeCallback), asyncResult);
-
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- catch (Exception ex)
- {
- this.negotiationComplete.Set();
- this.protocol.SendAlert(ref ex);
-
- throw new IOException("The authentication or decryption has failed.", ex);
- }
- }
-
- private void EndNegotiateHandshake(InternalAsyncResult asyncResult)
- {
- if (asyncResult.IsCompleted == false)
- asyncResult.AsyncWaitHandle.WaitOne();
-
- if (asyncResult.CompletedWithError)
- {
- throw asyncResult.AsyncException;
- }
- }
-
- public override IAsyncResult BeginRead(
- byte[] buffer,
- int offset,
- int count,
- AsyncCallback callback,
- object state)
- {
- this.checkDisposed();
-
- if (buffer == null)
- {
- throw new ArgumentNullException("buffer is a null reference.");
- }
- if (offset < 0)
- {
- throw new ArgumentOutOfRangeException("offset is less than 0.");
- }
- if (offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException("count is less than 0.");
- }
- if (count > (buffer.Length - offset))
- {
- throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
- }
-
- InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, false, true);
-
- if (this.MightNeedHandshake)
- {
- if (! BeginNegotiateHandshake(asyncResult))
- {
- //we made it down here so the handshake was not started.
- //another thread must have started it in the mean time.
- //wait for it to complete and then perform our original operation
- this.negotiationComplete.WaitOne();
-
- InternalBeginRead(asyncResult);
- }
- }
- else
- {
- InternalBeginRead(asyncResult);
- }
-
- return asyncResult;
- }
-
- // bigger than max record length for SSL/TLS
- private byte[] recbuf = new byte[16384];
-
- private void InternalBeginRead(InternalAsyncResult asyncResult)
- {
- try
- {
- int preReadSize = 0;
-
- lock (this.read)
- {
- // If actual buffer is fully read, reset it
- bool shouldReset = this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0;
-
- // If the buffer isn't fully read, but does have data, we need to immediately
- // read the info from the buffer and let the user know that they have more data.
- bool shouldReadImmediately = (this.inputBuffer.Length > 0) && (asyncResult.Count > 0);
-
- if (shouldReset)
- {
- this.resetBuffer();
- }
- else if (shouldReadImmediately)
- {
- preReadSize = this.inputBuffer.Read(asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
- }
- }
-
- // This is explicitly done outside the synclock to avoid
- // any potential deadlocks in the delegate call.
- if (0 < preReadSize)
- {
- asyncResult.SetComplete(preReadSize);
- }
- else if (recordStream.Position < recordStream.Length) {
- InternalReadCallback_inner (asyncResult, recbuf, new object[] { recbuf, asyncResult }, false, 0);
- }
- else if (!this.context.ReceivedConnectionEnd)
- {
- // 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(InternalReadCallback), new object[] { recbuf, asyncResult });
- }
- else
- {
- // We're done with the connection so we need to let the caller know with 0 bytes read
- asyncResult.SetComplete(0);
- }
- }
- catch (Exception ex)
- {
- this.protocol.SendAlert(ref ex);
- throw new IOException("The authentication or decryption has failed.", ex);
- }
- }
-
-
- 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 InternalReadCallback(IAsyncResult result)
- {
- object[] state = (object[])result.AsyncState;
- byte[] recbuf = (byte[])state[0];
- InternalAsyncResult internalResult = (InternalAsyncResult)state[1];
-
- try
- {
- this.checkDisposed();
-
- int n = innerStream.EndRead(result);
- if (n > 0)
- {
- // Add the just received data to the waiting data
- recordStream.Write(recbuf, 0, n);
- }
- else
- {
- // 0 length data means this read operation is done (lost connection in the case of a network stream).
- internalResult.SetComplete(0);
- return;
- }
-
- InternalReadCallback_inner(internalResult, recbuf, state, true, n);
- }
- catch (Exception ex)
- {
- internalResult.SetComplete(ex);
- }
-
- }
-
- // 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 InternalReadCallback_inner(InternalAsyncResult internalResult, byte[] recbuf, object[] state, bool didRead, int n)
- {
- if (this.disposed)
- return;
-
- try
- {
- 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);
- }
-
- lock (this.read)
- {
- 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 && (!didRead || (n > 0)))
- {
- if (context.ReceivedConnectionEnd) {
- internalResult.SetComplete (0);
- } else {
- // 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(InternalReadCallback), state);
- }
- }
- else
- {
- // we have record(s) to return -or- no more available to read from network
- // reset position for further reading
- recordStream.Position = pos;
-
- int bytesRead = 0;
- lock (this.read)
- {
- bytesRead = this.inputBuffer.Read(internalResult.Buffer, internalResult.Offset, internalResult.Count);
- }
-
- internalResult.SetComplete(bytesRead);
- }
- }
- catch (Exception ex)
- {
- internalResult.SetComplete(ex);
- }
- }
-
- private void InternalBeginWrite(InternalAsyncResult asyncResult)
- {
- try
- {
- // Send the buffer as a TLS record
-
- lock (this.write)
- {
- byte[] record = this.protocol.EncodeRecord(
- ContentType.ApplicationData, asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
-
- this.innerStream.BeginWrite(
- record, 0, record.Length, new AsyncCallback(InternalWriteCallback), asyncResult);
- }
- }
- catch (Exception ex)
- {
- this.protocol.SendAlert (ref ex);
- this.Close();
-
- throw new IOException("The authentication or decryption has failed.", ex);
- }
- }
-
- private void InternalWriteCallback(IAsyncResult ar)
- {
- InternalAsyncResult internalResult = (InternalAsyncResult)ar.AsyncState;
-
- try
- {
- this.checkDisposed();
- this.innerStream.EndWrite(ar);
- internalResult.SetComplete();
- }
- catch (Exception ex)
- {
- internalResult.SetComplete(ex);
- }
- }
-
- public override IAsyncResult BeginWrite(
- byte[] buffer,
- int offset,
- int count,
- AsyncCallback callback,
- object state)
- {
- this.checkDisposed();
-
- if (buffer == null)
- {
- throw new ArgumentNullException("buffer is a null reference.");
- }
- if (offset < 0)
- {
- throw new ArgumentOutOfRangeException("offset is less than 0.");
- }
- if (offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException("count is less than 0.");
- }
- if (count > (buffer.Length - offset))
- {
- throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
- }
-
-
- InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, true, true);
-
- if (this.MightNeedHandshake)
- {
- if (! BeginNegotiateHandshake(asyncResult))
- {
- //we made it down here so the handshake was not started.
- //another thread must have started it in the mean time.
- //wait for it to complete and then perform our original operation
- this.negotiationComplete.WaitOne();
-
- InternalBeginWrite(asyncResult);
- }
- }
- else
- {
- InternalBeginWrite(asyncResult);
- }
-
- return asyncResult;
- }
-
- public override int EndRead(IAsyncResult asyncResult)
- {
- this.checkDisposed();
-
- InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
- if (internalResult == null)
- {
- throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
- }
-
- // Always wait until the read is complete
- if (!asyncResult.IsCompleted)
- {
- if (!asyncResult.AsyncWaitHandle.WaitOne ())
- throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndRead");
- }
-
- if (internalResult.CompletedWithError)
- {
- throw internalResult.AsyncException;
- }
-
- return internalResult.BytesRead;
- }
-
- public override void EndWrite(IAsyncResult asyncResult)
- {
- this.checkDisposed();
-
- InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
- if (internalResult == null)
- {
- throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginWrite.");
- }
-
-
- if (!asyncResult.IsCompleted)
- {
- if (!internalResult.AsyncWaitHandle.WaitOne ())
- throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndWrite");
- }
-
- if (internalResult.CompletedWithError)
- {
- throw internalResult.AsyncException;
- }
- }
-
- public override void Close()
- {
- base.Close ();
- }
-
- public override void Flush()
- {
- this.checkDisposed();
-
- this.innerStream.Flush();
- }
-
- public int Read(byte[] buffer)
- {
- return this.Read(buffer, 0, buffer.Length);
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- this.checkDisposed ();
-
- if (buffer == null)
- {
- throw new ArgumentNullException ("buffer");
- }
- if (offset < 0)
- {
- throw new ArgumentOutOfRangeException("offset is less than 0.");
- }
- if (offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException("count is less than 0.");
- }
- if (count > (buffer.Length - offset))
- {
- throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
- }
-
- if (this.context.HandshakeState != HandshakeState.Finished)
- {
- this.NegotiateHandshake (); // Handshake negotiation
- }
-
- lock (this.read) {
- try {
- record_processing.Reset ();
- // do we already have some decrypted data ?
- if (this.inputBuffer.Position > 0) {
- // or maybe we used all the buffer before ?
- if (this.inputBuffer.Position == this.inputBuffer.Length) {
- this.inputBuffer.SetLength (0);
- } else {
- int n = this.inputBuffer.Read (buffer, offset, count);
- if (n > 0) {
- record_processing.Set ();
- return n;
- }
- }
- }
-
- bool needMoreData = false;
- while (true) {
- // we first try to process the read with the data we already have
- if ((recordStream.Position == 0) || needMoreData) {
- needMoreData = false;
- // if we loop, then it either means we need more data
- byte[] recbuf = new byte[16384];
- int n = 0;
- if (count == 1) {
- int value = innerStream.ReadByte ();
- if (value >= 0) {
- recbuf[0] = (byte) value;
- n = 1;
- }
- } else {
- n = innerStream.Read (recbuf, 0, recbuf.Length);
- }
- if (n > 0) {
- // Add the new received data to the waiting data
- if ((recordStream.Length > 0) && (recordStream.Position != recordStream.Length))
- recordStream.Seek (0, SeekOrigin.End);
- recordStream.Write (recbuf, 0, n);
- } else {
- // or that the read operation is done (lost connection in the case of a network stream).
- record_processing.Set ();
- return 0;
- }
- }
-
- bool dataToReturn = false;
-
- 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);
- needMoreData = (record == null);
- }
-
- // 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);
- recordStream.Position = 0;
- }
-
- if (dataToReturn) {
- // we have record(s) to return -or- no more available to read from network
- // reset position for further reading
- int i = inputBuffer.Read (buffer, offset, count);
- record_processing.Set ();
- return i;
- }
- }
- }
- }
- catch (TlsException ex)
- {
- throw new IOException("The authentication or decryption has failed.", ex);
- }
- catch (Exception ex)
- {
- throw new IOException("IO exception during read.", ex);
- }
- }
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotSupportedException();
- }
-
- public override void SetLength(long value)
- {
- throw new NotSupportedException();
- }
-
- public void Write(byte[] buffer)
- {
- this.Write(buffer, 0, buffer.Length);
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- this.checkDisposed ();
-
- if (buffer == null)
- {
- throw new ArgumentNullException ("buffer");
- }
- if (offset < 0)
- {
- throw new ArgumentOutOfRangeException("offset is less than 0.");
- }
- if (offset > buffer.Length)
- {
- throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException("count is less than 0.");
- }
- if (count > (buffer.Length - offset))
- {
- throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
- }
-
- if (this.context.HandshakeState != HandshakeState.Finished)
- {
- this.NegotiateHandshake ();
- }
-
- lock (this.write)
- {
- try
- {
- // Send the buffer as a TLS record
- byte[] record = this.protocol.EncodeRecord (ContentType.ApplicationData, buffer, offset, count);
- this.innerStream.Write (record, 0, record.Length);
- }
- catch (Exception ex)
- {
- this.protocol.SendAlert(ref ex);
- this.Close();
- throw new IOException("The authentication or decryption has failed.", ex);
- }
- }
- }
-
- public override bool CanRead
- {
- get { return this.innerStream.CanRead; }
- }
-
- public override bool CanSeek
- {
- get { return false; }
- }
-
- public override bool CanWrite
- {
- get { return this.innerStream.CanWrite; }
- }
-
- public override long Length
- {
- get { throw new NotSupportedException(); }
- }
-
- public override long Position
- {
- get
- {
- throw new NotSupportedException();
- }
- set
- {
- throw new NotSupportedException();
- }
- }
- #endregion
-
- #region IDisposable Members and Finalizer
-
- ~SslStreamBase()
- {
- this.Dispose(false);
- }
-
- protected override void Dispose (bool disposing)
- {
- if (!this.disposed)
- {
- if (disposing)
- {
- if (this.innerStream != null)
- {
- if (this.context.HandshakeState == HandshakeState.Finished &&
- !this.context.SentConnectionEnd)
- {
- // Write close notify
- try {
- this.protocol.SendAlert(AlertDescription.CloseNotify);
- } catch {
- }
- }
-
- if (this.ownsStream)
- {
- // Close inner stream
- this.innerStream.Close();
- }
- }
- this.ownsStream = false;
- this.innerStream = null;
- }
-
- this.disposed = true;
- base.Dispose (disposing);
- }
- }
-
- #endregion
-
- #region Misc Methods
-
- private void resetBuffer()
- {
- this.inputBuffer.SetLength(0);
- this.inputBuffer.Position = 0;
- }
-
- internal void checkDisposed()
- {
- if (this.disposed)
- {
- throw new ObjectDisposedException("The Stream is closed.");
- }
- }
-
- #endregion
-
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsCipherSuite.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsCipherSuite.cs
deleted file mode 100644
index 2b261bf36af..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsCipherSuite.cs
+++ /dev/null
@@ -1,152 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using System.Security.Cryptography;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class TlsCipherSuite : CipherSuite
- {
- private const int MacHeaderLength = 13;
- private byte[] header;
- private object headerLock = new object ();
-
- #region Constructors
-
- public TlsCipherSuite(
- short code, string name, CipherAlgorithmType cipherAlgorithmType,
- HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType,
- bool exportable, bool blockMode, byte keyMaterialSize,
- byte expandedKeyMaterialSize, short effectiveKeyBytes,
- byte ivSize, byte blockSize)
- :base(code, name, cipherAlgorithmType, hashAlgorithmType,
- exchangeAlgorithmType, exportable, blockMode, keyMaterialSize,
- expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize)
- {
- }
-
- #endregion
-
- #region MAC Generation Methods
-
- public override byte[] ComputeServerRecordMAC(ContentType contentType, byte[] fragment)
- {
- lock (headerLock) {
- if (header == null)
- header = new byte [MacHeaderLength];
-
- ulong seqnum = (Context is ClientContext) ? Context.ReadSequenceNumber : Context.WriteSequenceNumber;
- Write (header, 0, seqnum);
- header [8] = (byte)contentType;
- Write (header, 9, this.Context.Protocol);
- Write (header, 11, (short)fragment.Length);
-
- HashAlgorithm mac = this.ServerHMAC;
- mac.TransformBlock (header, 0, header.Length, header, 0);
- mac.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
- // hack, else the method will allocate a new buffer of the same length (negative half the optimization)
- mac.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
- return mac.Hash;
- }
- }
-
- public override byte[] ComputeClientRecordMAC(ContentType contentType, byte[] fragment)
- {
- lock (headerLock) {
- if (header == null)
- header = new byte [MacHeaderLength];
-
- ulong seqnum = (Context is ClientContext) ? Context.WriteSequenceNumber : Context.ReadSequenceNumber;
- Write (header, 0, seqnum);
- header [8] = (byte)contentType;
- Write (header, 9, this.Context.Protocol);
- Write (header, 11, (short)fragment.Length);
-
- HashAlgorithm mac = this.ClientHMAC;
- mac.TransformBlock (header, 0, header.Length, header, 0);
- mac.TransformBlock (fragment, 0, fragment.Length, fragment, 0);
- // hack, else the method will allocate a new buffer of the same length (negative half the optimization)
- mac.TransformFinalBlock (CipherSuite.EmptyArray, 0, 0);
- return mac.Hash;
- }
- }
-
- #endregion
-
- #region Key Generation Methods
-
- public override void ComputeMasterSecret(byte[] preMasterSecret)
- {
- // Create master secret
- this.Context.MasterSecret = new byte[preMasterSecret.Length];
- this.Context.MasterSecret = this.PRF(
- preMasterSecret, "master secret", this.Context.RandomCS, 48);
-
- DebugHelper.WriteLine(">>>> MasterSecret", this.Context.MasterSecret);
- }
-
- public override void ComputeKeys()
- {
- // Create keyblock
- TlsStream keyBlock = new TlsStream(
- this.PRF(
- this.Context.MasterSecret,
- "key expansion",
- this.Context.RandomSC,
- this.KeyBlockSize));
-
- this.Context.Negotiating.ClientWriteMAC = keyBlock.ReadBytes(this.HashSize);
- this.Context.Negotiating.ServerWriteMAC = keyBlock.ReadBytes(this.HashSize);
- this.Context.ClientWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
- this.Context.ServerWriteKey = keyBlock.ReadBytes(this.KeyMaterialSize);
-
- if (this.IvSize != 0)
- {
- this.Context.ClientWriteIV = keyBlock.ReadBytes(this.IvSize);
- this.Context.ServerWriteIV = keyBlock.ReadBytes(this.IvSize);
- }
- else
- {
- this.Context.ClientWriteIV = CipherSuite.EmptyArray;
- this.Context.ServerWriteIV = CipherSuite.EmptyArray;
- }
-
- DebugHelper.WriteLine(">>>> KeyBlock", keyBlock.ToArray());
- DebugHelper.WriteLine(">>>> ClientWriteKey", this.Context.ClientWriteKey);
- DebugHelper.WriteLine(">>>> ClientWriteIV", this.Context.ClientWriteIV);
- DebugHelper.WriteLine(">>>> ClientWriteMAC", this.Context.Negotiating.ClientWriteMAC);
- DebugHelper.WriteLine(">>>> ServerWriteKey", this.Context.ServerWriteKey);
- DebugHelper.WriteLine(">>>> ServerWriteIV", this.Context.ServerWriteIV);
- DebugHelper.WriteLine(">>>> ServerWriteMAC", this.Context.Negotiating.ServerWriteMAC);
-
- ClientSessionCache.SetContextInCache (this.Context);
- // Clear no more needed data
- keyBlock.Reset();
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsClientSettings.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsClientSettings.cs
deleted file mode 100644
index bcbc882cf35..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsClientSettings.cs
+++ /dev/null
@@ -1,124 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Text;
-using System.Security.Cryptography.X509Certificates;
-using Mono.Security.Cryptography;
-using X509 = Mono.Security.X509;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal sealed class TlsClientSettings
- {
- #region Fields
-
- private string targetHost;
- private X509CertificateCollection certificates;
- //private SecurityCompressionType compressionMethod;
- private X509Certificate clientCertificate;
- private RSAManaged certificateRSA;
-
- #endregion
-
- #region Properties
-
- public string TargetHost
- {
- get { return this.targetHost; }
- set { this.targetHost = value; }
- }
-
- public X509CertificateCollection Certificates
- {
- get { return this.certificates; }
- set { this.certificates = value; }
- }
-
- public X509Certificate ClientCertificate
- {
- get { return this.clientCertificate; }
- set
- {
- this.clientCertificate = value;
- this.UpdateCertificateRSA();
- }
- }
-
- public RSAManaged CertificateRSA
- {
- get { return this.certificateRSA; }
- }
-
- /*
- public SecurityCompressionType CompressionMethod
- {
- get { return this.compressionMethod; }
- set
- {
- if (value != SecurityCompressionType.None)
- {
- throw new NotSupportedException("Specified compression method is not supported");
- }
- this.compressionMethod = value;
- }
- }
- */
-
- #endregion
-
- #region Constructors
-
- public TlsClientSettings()
- {
- // this.compressionMethod = SecurityCompressionType.None;
- this.certificates = new X509CertificateCollection();
- this.targetHost = String.Empty;
- }
-
- #endregion
-
- #region Methods
-
- public void UpdateCertificateRSA()
- {
- if (this.clientCertificate == null)
- {
- this.certificateRSA = null;
- }
- else
- {
- X509.X509Certificate cert = new X509.X509Certificate(this.clientCertificate.GetRawCertData());
-
- this.certificateRSA = new RSAManaged(
- cert.RSA.KeySize);
-
- this.certificateRSA.ImportParameters(
- cert.RSA.ExportParameters(false));
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsException.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsException.cs
deleted file mode 100644
index ef2c5ce0900..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsException.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Text;
-using System.Runtime.Serialization;
-
-namespace Mono.Security.Protocol.Tls
-{
- [Serializable]
- internal sealed class TlsException : Exception
- {
- #region Fields
-
- private Alert alert;
-
- #endregion
-
- #region Properties
-
- public Alert Alert
- {
- get { return this.alert; }
- }
-
- #endregion
-
- #region Constructors
-
- internal TlsException(string message) : base(message)
- {
- }
-
- internal TlsException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
-
- internal TlsException(string message, Exception ex) : base(message, ex)
- {
- }
-
- internal TlsException(
- AlertLevel level,
- AlertDescription description)
- : this (level, description, Alert.GetAlertMessage(description))
- {
- }
-
- internal TlsException(
- AlertLevel level,
- AlertDescription description,
- string message) : base (message)
- {
- this.alert = new Alert(level, description);
- }
-
- internal TlsException(
- AlertDescription description)
- : this (description, Alert.GetAlertMessage(description))
- {
- }
-
- internal TlsException(
- AlertDescription description,
- string message) : base (message)
- {
- this.alert = new Alert(description);
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsServerSettings.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsServerSettings.cs
deleted file mode 100644
index fec31752e76..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsServerSettings.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.Security.Cryptography;
-
-using Mono.Security.Cryptography;
-using Mono.Security.X509;
-using Mono.Security.Protocol.Tls.Handshake;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class TlsServerSettings
- {
- #region Fields
-
- private X509CertificateCollection certificates;
- private RSA certificateRSA;
- private RSAParameters rsaParameters;
- private byte[] signedParams;
- private string[] distinguisedNames;
- private bool serverKeyExchange;
- private bool certificateRequest;
- private ClientCertificateType[] certificateTypes;
-
- #endregion
-
- #region Properties
-
- public bool ServerKeyExchange
- {
- get { return this.serverKeyExchange; }
- set { this.serverKeyExchange = value; }
- }
-
- public X509CertificateCollection Certificates
- {
- get { return this.certificates; }
- set { this.certificates = value; }
- }
-
- public RSA CertificateRSA
- {
- get { return this.certificateRSA; }
- }
-
- public RSAParameters RsaParameters
- {
- get { return this.rsaParameters; }
- set { this.rsaParameters = value; }
- }
-
- public byte[] SignedParams
- {
- get { return this.signedParams; }
- set { this.signedParams = value; }
- }
-
- public bool CertificateRequest
- {
- get { return this.certificateRequest; }
- set { this.certificateRequest = value; }
- }
-
- public ClientCertificateType[] CertificateTypes
- {
- get { return this.certificateTypes; }
- set { this.certificateTypes = value; }
- }
-
- public string[] DistinguisedNames
- {
- get { return this.distinguisedNames; }
- set { this.distinguisedNames = value; }
- }
-
- #endregion
-
- #region Constructors
-
- public TlsServerSettings()
- {
- }
-
- #endregion
-
- #region Methods
-
- public void UpdateCertificateRSA()
- {
- if (this.certificates == null ||
- this.certificates.Count == 0)
- {
- this.certificateRSA = null;
- }
- else
- {
- this.certificateRSA = new RSAManaged(
- this.certificates[0].RSA.KeySize);
-
- this.certificateRSA.ImportParameters(
- this.certificates[0].RSA.ExportParameters(false));
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsStream.cs b/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsStream.cs
deleted file mode 100644
index 4130ad10ec0..00000000000
--- a/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/TlsStream.cs
+++ /dev/null
@@ -1,274 +0,0 @@
-// Transport Security Layer (TLS)
-// Copyright (c) 2003-2004 Carlos Guzman Alvarez
-// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-
-namespace Mono.Security.Protocol.Tls
-{
- internal class TlsStream : Stream
- {
- #region Fields
-
- private bool canRead;
- private bool canWrite;
- private MemoryStream buffer;
- private byte[] temp;
- private const int temp_size = 4;
-
- #endregion
-
- #region Properties
-
- public bool EOF
- {
- get
- {
- if (this.Position < this.Length)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- }
-
- #endregion
-
- #region Stream Properties
-
- public override bool CanWrite
- {
- get { return this.canWrite; }
- }
-
- public override bool CanRead
- {
- get { return this.canRead; }
- }
-
- public override bool CanSeek
- {
- get { return this.buffer.CanSeek; }
- }
-
- public override long Position
- {
- get { return this.buffer.Position; }
- set { this.buffer.Position = value; }
- }
-
- public override long Length
- {
- get { return this.buffer.Length; }
- }
-
- #endregion
-
- #region Constructors
-
- public TlsStream() : base()
- {
- this.buffer = new MemoryStream(0);
- this.canRead = false;
- this.canWrite = true;
- }
-
- public TlsStream(byte[] data) : base()
- {
- if (data != null)
- this.buffer = new MemoryStream(data);
- else
- this.buffer = new MemoryStream ();
- this.canRead = true;
- this.canWrite = false;
- }
-
- #endregion
-
- #region Specific Read Methods
-
- // hack for reducing memory allocations
- // returned value is valid only for the length asked *and*
- // cannot be directly returned outside the class
- // note: Mono's Stream.ReadByte does a 1 byte array allocation
- private byte[] ReadSmallValue (int length)
- {
- if (length > temp_size)
- throw new ArgumentException ("8 bytes maximum");
- if (temp == null)
- temp = new byte[temp_size];
-
- if (this.Read (temp, 0, length) != length)
- throw new TlsException (String.Format ("buffer underrun"));
- return temp;
- }
-
- public new byte ReadByte()
- {
- byte[] result = ReadSmallValue (1);
- return result [0];
- }
-
- public short ReadInt16()
- {
- byte[] result = ReadSmallValue (2);
- return (short) (result[0] << 8 | result[1]);
- }
-
- public int ReadInt24()
- {
- byte[] result = ReadSmallValue (3);
- return ((result[0] << 16) | (result[1] << 8) | result[2]);
- }
-
- public int ReadInt32()
- {
- byte[] result = ReadSmallValue (4);
- return ((result[0] << 24) | (result[1] << 16) | (result[2] << 8) | result[3]);
- }
-
- public byte[] ReadBytes(int count)
- {
- byte[] bytes = new byte[count];
- if (this.Read(bytes, 0, count) != count)
- throw new TlsException ("buffer underrun");
-
- return bytes;
- }
-
- #endregion
-
- #region Specific Write Methods
-
- // note: Mono's Stream.WriteByte does a 1 byte array allocation
- public void Write(byte value)
- {
- if (temp == null)
- temp = new byte[temp_size];
- temp[0] = value;
- this.Write (temp, 0, 1);
- }
-
- public void Write(short value)
- {
- if (temp == null)
- temp = new byte[temp_size];
- temp[0] = ((byte)(value >> 8));
- temp[1] = ((byte)value);
- this.Write (temp, 0, 2);
- }
-
- public void WriteInt24(int value)
- {
- if (temp == null)
- temp = new byte[temp_size];
- temp[0] = ((byte)(value >> 16));
- temp[1] = ((byte)(value >> 8));
- temp[2] = ((byte)value);
- this.Write (temp, 0, 3);
- }
-
- public void Write(int value)
- {
- if (temp == null)
- temp = new byte[temp_size];
- temp[0] = ((byte)(value >> 24));
- temp[1] = ((byte)(value >> 16));
- temp[2] = ((byte)(value >> 8));
- temp[3] = ((byte)value);
- this.Write (temp, 0, 4);
- }
-
- public void Write(ulong value)
- {
- Write ((int)(value >> 32));
- Write ((int)value);
- }
-
- public void Write(byte[] buffer)
- {
- this.Write(buffer, 0, buffer.Length);
- }
-
- #endregion
-
- #region Methods
-
- public void Reset()
- {
- this.buffer.SetLength(0);
- this.buffer.Position = 0;
- }
-
- public byte[] ToArray()
- {
- return this.buffer.ToArray();
- }
-
- #endregion
-
- #region Stream Methods
-
- public override void Flush()
- {
- this.buffer.Flush();
- }
-
- public override void SetLength(long length)
- {
- this.buffer.SetLength(length);
- }
-
- public override long Seek(long offset, System.IO.SeekOrigin loc)
- {
- return this.buffer.Seek(offset, loc);
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- if (this.canRead)
- {
- return this.buffer.Read(buffer, offset, count);
- }
- throw new InvalidOperationException("Read operations are not allowed by this stream");
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- if (this.canWrite)
- {
- this.buffer.Write(buffer, offset, count);
- }
- else
- {
- throw new InvalidOperationException("Write operations are not allowed by this stream");
- }
- }
-
- #endregion
- }
-}
diff --git a/mcs/class/Mono.Security/Mono.Security.csproj b/mcs/class/Mono.Security/Mono.Security.csproj
index de767dabd30..676d178d26f 100644
--- a/mcs/class/Mono.Security/Mono.Security.csproj
+++ b/mcs/class/Mono.Security/Mono.Security.csproj
@@ -206,65 +206,6 @@
<Compile Include="Mono.Security.Protocol.Ntlm\Type1Message.cs" />
<Compile Include="Mono.Security.Protocol.Ntlm\Type2Message.cs" />
<Compile Include="Mono.Security.Protocol.Ntlm\Type3Message.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientCertificate.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientCertificateVerify.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientFinished.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientHello.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsClientKeyExchange.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerCertificate.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerCertificateRequest.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerFinished.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerHello.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerHelloDone.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Client\TlsServerKeyExchange.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientCertificate.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientCertificateVerify.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientFinished.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientHello.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsClientKeyExchange.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerCertificate.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerCertificateRequest.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerFinished.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerHello.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerHelloDone.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake.Server\TlsServerKeyExchange.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake\ClientCertificateType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake\HandshakeMessage.cs" />
- <Compile Include="Mono.Security.Protocol.Tls.Handshake\HandshakeType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\Alert.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\CipherAlgorithmType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\CipherSuite.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\CipherSuiteCollection.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\CipherSuiteFactory.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ClientContext.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ClientRecordProtocol.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ClientSessionCache.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ContentType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\Context.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\DebugHelper.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ExchangeAlgorithmType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\HandshakeState.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\HashAlgorithmType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\HttpsClientStream.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\MD5SHA1.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\RSASslSignatureDeformatter.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\RSASslSignatureFormatter.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\RecordProtocol.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SecurityCompressionType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SecurityParameters.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SecurityProtocolType.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ServerContext.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\ServerRecordProtocol.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SslCipherSuite.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SslClientStream.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SslHandshakeHash.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SslServerStream.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\SslStreamBase.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\TlsCipherSuite.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\TlsClientSettings.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\TlsException.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\TlsServerSettings.cs" />
- <Compile Include="Mono.Security.Protocol.Tls\TlsStream.cs" />
<Compile Include="Mono.Security.X509.Extensions\AuthorityKeyIdentifierExtension.cs" />
<Compile Include="Mono.Security.X509.Extensions\BasicConstraintsExtension.cs" />
<Compile Include="Mono.Security.X509.Extensions\CRLDistributionPointsExtension.cs" />
diff --git a/mcs/class/Mono.Security/Mono.Security.dll.sources b/mcs/class/Mono.Security/Mono.Security.dll.sources
index c6b8882cad7..d431140fdb7 100644
--- a/mcs/class/Mono.Security/Mono.Security.dll.sources
+++ b/mcs/class/Mono.Security/Mono.Security.dll.sources
@@ -74,65 +74,7 @@
./Mono.Security.Protocol.Ntlm/Type1Message.cs
./Mono.Security.Protocol.Ntlm/Type2Message.cs
./Mono.Security.Protocol.Ntlm/Type3Message.cs
-./Mono.Security.Protocol.Tls/Alert.cs
-./Mono.Security.Protocol.Tls/CipherAlgorithmType.cs
-./Mono.Security.Protocol.Tls/CipherSuite.cs
-./Mono.Security.Protocol.Tls/CipherSuiteCollection.cs
-./Mono.Security.Protocol.Tls/CipherSuiteFactory.cs
-./Mono.Security.Protocol.Tls/ClientContext.cs
-./Mono.Security.Protocol.Tls/ClientRecordProtocol.cs
-./Mono.Security.Protocol.Tls/ClientSessionCache.cs
-./Mono.Security.Protocol.Tls/ContentType.cs
-./Mono.Security.Protocol.Tls/Context.cs
-./Mono.Security.Protocol.Tls/DebugHelper.cs
-./Mono.Security.Protocol.Tls/ExchangeAlgorithmType.cs
-./Mono.Security.Protocol.Tls/HandshakeState.cs
-./Mono.Security.Protocol.Tls/HashAlgorithmType.cs
-./Mono.Security.Protocol.Tls/MD5SHA1.cs
-./Mono.Security.Protocol.Tls/HttpsClientStream.cs
-./Mono.Security.Protocol.Tls/RecordProtocol.cs
-./Mono.Security.Protocol.Tls/RSASslSignatureDeformatter.cs
-./Mono.Security.Protocol.Tls/RSASslSignatureFormatter.cs
-./Mono.Security.Protocol.Tls/SecurityCompressionType.cs
-./Mono.Security.Protocol.Tls/SecurityParameters.cs
-./Mono.Security.Protocol.Tls/SecurityProtocolType.cs
-./Mono.Security.Protocol.Tls/ServerContext.cs
-./Mono.Security.Protocol.Tls/ServerRecordProtocol.cs
-./Mono.Security.Protocol.Tls/SslClientStream.cs
-./Mono.Security.Protocol.Tls/SslCipherSuite.cs
-./Mono.Security.Protocol.Tls/SslHandshakeHash.cs
-./Mono.Security.Protocol.Tls/SslServerStream.cs
-./Mono.Security.Protocol.Tls/SslStreamBase.cs
-./Mono.Security.Protocol.Tls/TlsCipherSuite.cs
-./Mono.Security.Protocol.Tls/TlsClientSettings.cs
-./Mono.Security.Protocol.Tls/TlsException.cs
-./Mono.Security.Protocol.Tls/TlsServerSettings.cs
-./Mono.Security.Protocol.Tls/TlsStream.cs
-./Mono.Security.Protocol.Tls.Handshake/ClientCertificateType.cs
-./Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs
-./Mono.Security.Protocol.Tls.Handshake/HandshakeType.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificate.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientCertificateVerify.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientFinished.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientHello.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsClientKeyExchange.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificateRequest.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerFinished.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHello.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerHelloDone.cs
-./Mono.Security.Protocol.Tls.Handshake.Client/TlsServerKeyExchange.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificate.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientCertificateVerify.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientFinished.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsClientKeyExchange.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificate.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerCertificateRequest.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerFinished.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHello.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerHelloDone.cs
-./Mono.Security.Protocol.Tls.Handshake.Server/TlsServerKeyExchange.cs
+
./Mono.Xml/MiniParser.cs
./Mono.Xml/SecurityParser.cs