diff options
author | Peter Dettman <peter.dettman@gmail.com> | 2022-06-21 19:34:30 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@gmail.com> | 2022-06-21 19:34:30 +0700 |
commit | 28616776b548f3b68425a0e481a62c08de28d837 (patch) | |
tree | 8869d32d58251f4a4416558847957e6e2181657b /crypto/test | |
parent | ObsoleteAttribute cleanup (diff) | |
download | BouncyCastle.NET-ed25519-28616776b548f3b68425a0e481a62c08de28d837.tar.xz |
Remove legacy TLS
Diffstat (limited to 'crypto/test')
36 files changed, 0 insertions, 4108 deletions
diff --git a/crypto/test/UnitTests.csproj b/crypto/test/UnitTests.csproj index 92d3b7d92..8fd93a962 100644 --- a/crypto/test/UnitTests.csproj +++ b/crypto/test/UnitTests.csproj @@ -315,41 +315,6 @@ <Compile Include="src\crypto\test\cavp\KDFCounterTests.cs" /> <Compile Include="src\crypto\test\cavp\KDFDoublePipelineTests.cs" /> <Compile Include="src\crypto\test\cavp\KDFFeedbackCounterTests.cs" /> - <Compile Include="src\crypto\tls\test\ByteQueueStreamTest.cs" /> - <Compile Include="src\crypto\tls\test\DtlsProtocolTest.cs" /> - <Compile Include="src\crypto\tls\test\DtlsTestCase.cs" /> - <Compile Include="src\crypto\tls\test\DtlsTestClientProtocol.cs" /> - <Compile Include="src\crypto\tls\test\DtlsTestServerProtocol.cs" /> - <Compile Include="src\crypto\tls\test\DtlsTestSuite.cs" /> - <Compile Include="src\crypto\tls\test\LoggingDatagramTransport.cs" /> - <Compile Include="src\crypto\tls\test\MockDatagramAssociation.cs" /> - <Compile Include="src\crypto\tls\test\MockDtlsClient.cs" /> - <Compile Include="src\crypto\tls\test\MockDtlsServer.cs" /> - <Compile Include="src\crypto\tls\test\MockPskTlsClient.cs" /> - <Compile Include="src\crypto\tls\test\MockPskTlsServer.cs" /> - <Compile Include="src\crypto\tls\test\MockSrpTlsClient.cs" /> - <Compile Include="src\crypto\tls\test\MockSrpTlsServer.cs" /> - <Compile Include="src\crypto\tls\test\MockTlsClient.cs" /> - <Compile Include="src\crypto\tls\test\MockTlsServer.cs" /> - <Compile Include="src\crypto\tls\test\NetworkStream.cs" /> - <Compile Include="src\crypto\tls\test\PipedStream.cs" /> - <Compile Include="src\crypto\tls\test\PskTlsClientTest.cs" /> - <Compile Include="src\crypto\tls\test\PskTlsServerTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsClientTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsProtocolTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsProtocolNonBlockingTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsPskProtocolTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsServerTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsSrpProtocolTest.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestCase.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestClientImpl.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestClientProtocol.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestConfig.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestServerImpl.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestServerProtocol.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestSuite.cs" /> - <Compile Include="src\crypto\tls\test\TlsTestUtilities.cs" /> - <Compile Include="src\crypto\tls\test\UnreliableDatagramTransport.cs" /> <Compile Include="src\math\ec\custom\sec\test\SecP128R1FieldTest.cs" /> <Compile Include="src\math\ec\custom\sec\test\SecP256R1FieldTest.cs" /> <Compile Include="src\math\ec\custom\sec\test\SecP384R1FieldTest.cs" /> diff --git a/crypto/test/src/crypto/tls/test/ByteQueueStreamTest.cs b/crypto/test/src/crypto/tls/test/ByteQueueStreamTest.cs deleted file mode 100644 index 1d68a5215..000000000 --- a/crypto/test/src/crypto/tls/test/ByteQueueStreamTest.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; - -using NUnit.Framework; - -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class ByteQueueStreamTest - { - [Test] - public void TestAvailable() - { - ByteQueueStream input = new ByteQueueStream(); - - // buffer is empty - Assert.AreEqual(0, input.Available); - - // after adding once - input.Write(new byte[10]); - Assert.AreEqual(10, input.Available); - - // after adding more than once - input.Write(new byte[5]); - Assert.AreEqual(15, input.Available); - - // after reading a single byte - input.ReadByte(); - Assert.AreEqual(14, input.Available); - - // after reading into a byte array - input.Read(new byte[4]); - Assert.AreEqual(10, input.Available); - - input.Close(); // so compiler doesn't whine about a resource leak - } - - [Test] - public void TestSkip() - { - ByteQueueStream input = new ByteQueueStream(); - - // skip when buffer is empty - Assert.AreEqual(0, input.Skip(10)); - - // skip equal to available - input.Write(new byte[2]); - Assert.AreEqual(2, input.Skip(2)); - Assert.AreEqual(0, input.Available); - - // skip less than available - input.Write(new byte[10]); - Assert.AreEqual(5, input.Skip(5)); - Assert.AreEqual(5, input.Available); - - // skip more than available - Assert.AreEqual(5, input.Skip(20)); - Assert.AreEqual(0, input.Available); - - input.Close();// so compiler doesn't whine about a resource leak - } - - [Test] - public void TestRead() - { - ByteQueueStream input = new ByteQueueStream(); - input.Write(new byte[] { 0x01, 0x02 }); - input.Write(new byte[]{ 0x03 }); - - Assert.AreEqual(0x01, input.ReadByte()); - Assert.AreEqual(0x02, input.ReadByte()); - Assert.AreEqual(0x03, input.ReadByte()); - Assert.AreEqual(-1, input.ReadByte()); - - input.Close(); // so compiler doesn't whine about a resource leak - } - - [Test] - public void TestReadArray() - { - ByteQueueStream input = new ByteQueueStream(); - input.Write(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }); - - byte[] buffer = new byte[5]; - - // read less than available into specified position - Assert.AreEqual(1, input.Read(buffer, 2, 1)); - AssertArrayEquals(new byte[]{ 0x00, 0x00, 0x01, 0x00, 0x00 }, buffer); - - // read equal to available - Assert.AreEqual(5, input.Read(buffer)); - AssertArrayEquals(new byte[]{ 0x02, 0x03, 0x04, 0x05, 0x06 }, buffer); - - // read more than available - input.Write(new byte[]{ 0x01, 0x02, 0x03 }); - Assert.AreEqual(3, input.Read(buffer)); - AssertArrayEquals(new byte[]{ 0x01, 0x02, 0x03, 0x05, 0x06 }, buffer); - - input.Close(); // so compiler doesn't whine about a resource leak - } - - [Test] - public void TestPeek() - { - ByteQueueStream input = new ByteQueueStream(); - - byte[] buffer = new byte[5]; - - // peek more than available - Assert.AreEqual(0, input.Peek(buffer)); - AssertArrayEquals(new byte[]{ 0x00, 0x00, 0x00, 0x00, 0x00 }, buffer); - - // peek less than available - input.Write(new byte[]{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }); - Assert.AreEqual(5, input.Peek(buffer)); - AssertArrayEquals(new byte[]{ 0x01, 0x02, 0x03, 0x04, 0x05 }, buffer); - Assert.AreEqual(6, input.Available); - - // peek equal to available - input.ReadByte(); - Assert.AreEqual(5, input.Peek(buffer)); - AssertArrayEquals(new byte[]{ 0x02, 0x03, 0x04, 0x05, 0x06 }, buffer); - Assert.AreEqual(5, input.Available); - - input.Close(); // so compiler doesn't whine about a resource leak - } - - private static void AssertArrayEquals(byte[] a, byte[] b) - { - Assert.IsTrue(Arrays.AreEqual(a, b)); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/DtlsProtocolTest.cs b/crypto/test/src/crypto/tls/test/DtlsProtocolTest.cs deleted file mode 100644 index 43726c70c..000000000 --- a/crypto/test/src/crypto/tls/test/DtlsProtocolTest.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class DtlsProtocolTest - { - [Test] - public void TestClientServer() - { - SecureRandom secureRandom = new SecureRandom(); - - DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom); - DtlsServerProtocol serverProtocol = new DtlsServerProtocol(secureRandom); - - MockDatagramAssociation network = new MockDatagramAssociation(1500); - - Server server = new Server(serverProtocol, network.Server); - - Thread serverThread = new Thread(new ThreadStart(server.Run)); - serverThread.Start(); - - DatagramTransport clientTransport = network.Client; - - clientTransport = new UnreliableDatagramTransport(clientTransport, secureRandom, 0, 0); - - clientTransport = new LoggingDatagramTransport(clientTransport, Console.Out); - - MockDtlsClient client = new MockDtlsClient(null); - - DtlsTransport dtlsClient = clientProtocol.Connect(client, clientTransport); - - for (int i = 1; i <= 10; ++i) - { - byte[] data = new byte[i]; - Arrays.Fill(data, (byte)i); - dtlsClient.Send(data, 0, data.Length); - } - - byte[] buf = new byte[dtlsClient.GetReceiveLimit()]; - while (dtlsClient.Receive(buf, 0, buf.Length, 100) >= 0) - { - } - - dtlsClient.Close(); - - server.Shutdown(serverThread); - } - - internal class Server - { - private readonly DtlsServerProtocol mServerProtocol; - private readonly DatagramTransport mServerTransport; - private volatile bool isShutdown = false; - - internal Server(DtlsServerProtocol serverProtocol, DatagramTransport serverTransport) - { - this.mServerProtocol = serverProtocol; - this.mServerTransport = serverTransport; - } - - public void Run() - { - try - { - MockDtlsServer server = new MockDtlsServer(); - DtlsTransport dtlsServer = mServerProtocol.Accept(server, mServerTransport); - byte[] buf = new byte[dtlsServer.GetReceiveLimit()]; - while (!isShutdown) - { - int length = dtlsServer.Receive(buf, 0, buf.Length, 1000); - if (length >= 0) - { - dtlsServer.Send(buf, 0, length); - } - } - dtlsServer.Close(); - } - catch (Exception e) - { - Console.Error.WriteLine(e); - } - } - - internal void Shutdown(Thread serverThread) - { - if (!isShutdown) - { - isShutdown = true; - serverThread.Join(); - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/DtlsTestCase.cs b/crypto/test/src/crypto/tls/test/DtlsTestCase.cs deleted file mode 100644 index 1cea4bfe2..000000000 --- a/crypto/test/src/crypto/tls/test/DtlsTestCase.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class DtlsTestCase - { - private static void CheckDtlsVersion(ProtocolVersion version) - { - if (version != null && !version.IsDtls) - throw new InvalidOperationException("Non-DTLS version"); - } - - [Test, TestCaseSource(typeof(DtlsTestSuite), "Suite")] - public void RunTest(TlsTestConfig config) - { - CheckDtlsVersion(config.clientMinimumVersion); - CheckDtlsVersion(config.clientOfferVersion); - CheckDtlsVersion(config.serverMaximumVersion); - CheckDtlsVersion(config.serverMinimumVersion); - - SecureRandom secureRandom = new SecureRandom(); - - DtlsTestClientProtocol clientProtocol = new DtlsTestClientProtocol(secureRandom, config); - DtlsTestServerProtocol serverProtocol = new DtlsTestServerProtocol(secureRandom, config); - - MockDatagramAssociation network = new MockDatagramAssociation(1500); - - TlsTestClientImpl clientImpl = new TlsTestClientImpl(config); - TlsTestServerImpl serverImpl = new TlsTestServerImpl(config); - - Server server = new Server(this, serverProtocol, network.Server, serverImpl); - - Thread serverThread = new Thread(new ThreadStart(server.Run)); - serverThread.Start(); - - Exception caught = null; - try - { - DatagramTransport clientTransport = network.Client; - - if (TlsTestConfig.DEBUG) - { - clientTransport = new LoggingDatagramTransport(clientTransport, Console.Out); - } - - DtlsTransport dtlsClient = clientProtocol.Connect(clientImpl, clientTransport); - - for (int i = 1; i <= 10; ++i) - { - byte[] data = new byte[i]; - Arrays.Fill(data, (byte)i); - dtlsClient.Send(data, 0, data.Length); - } - - byte[] buf = new byte[dtlsClient.GetReceiveLimit()]; - while (dtlsClient.Receive(buf, 0, buf.Length, 100) >= 0) - { - } - - dtlsClient.Close(); - } - catch (Exception e) - { - caught = e; - LogException(caught); - } - - server.Shutdown(serverThread); - - // TODO Add checks that the various streams were closed - - Assert.AreEqual(config.expectFatalAlertConnectionEnd, clientImpl.FirstFatalAlertConnectionEnd, "Client fatal alert connection end"); - Assert.AreEqual(config.expectFatalAlertConnectionEnd, serverImpl.FirstFatalAlertConnectionEnd, "Server fatal alert connection end"); - - Assert.AreEqual(config.expectFatalAlertDescription, clientImpl.FirstFatalAlertDescription, "Client fatal alert description"); - Assert.AreEqual(config.expectFatalAlertDescription, serverImpl.FirstFatalAlertDescription, "Server fatal alert description"); - - if (config.expectFatalAlertConnectionEnd == -1) - { - Assert.IsNull(caught, "Unexpected client exception"); - Assert.IsNull(server.mCaught, "Unexpected server exception"); - } - } - - protected void LogException(Exception e) - { - if (TlsTestConfig.DEBUG) - { - Console.Error.WriteLine(e); - } - } - - internal class Server - { - private readonly DtlsTestCase mOuter; - private readonly DtlsTestServerProtocol mServerProtocol; - private readonly DatagramTransport mServerTransport; - private readonly TlsTestServerImpl mServerImpl; - - private volatile bool isShutdown = false; - internal Exception mCaught = null; - - internal Server(DtlsTestCase outer, DtlsTestServerProtocol serverProtocol, - DatagramTransport serverTransport, TlsTestServerImpl serverImpl) - { - this.mOuter = outer; - this.mServerProtocol = serverProtocol; - this.mServerTransport = serverTransport; - this.mServerImpl = serverImpl; - } - - public void Run() - { - try - { - DtlsTransport dtlsServer = mServerProtocol.Accept(mServerImpl, mServerTransport); - byte[] buf = new byte[dtlsServer.GetReceiveLimit()]; - while (!isShutdown) - { - int length = dtlsServer.Receive(buf, 0, buf.Length, 100); - if (length >= 0) - { - dtlsServer.Send(buf, 0, length); - } - } - dtlsServer.Close(); - } - catch (Exception e) - { - mCaught = e; - mOuter.LogException(mCaught); - } - } - - internal void Shutdown(Thread serverThread) - { - if (!isShutdown) - { - isShutdown = true; - //serverThread.Interrupt(); - serverThread.Join(); - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/DtlsTestClientProtocol.cs b/crypto/test/src/crypto/tls/test/DtlsTestClientProtocol.cs deleted file mode 100644 index 41ed93eb0..000000000 --- a/crypto/test/src/crypto/tls/test/DtlsTestClientProtocol.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; - -using Org.BouncyCastle.Security; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class DtlsTestClientProtocol - : DtlsClientProtocol - { - protected readonly TlsTestConfig config; - - public DtlsTestClientProtocol(SecureRandom secureRandom, TlsTestConfig config) - : base(secureRandom) - { - this.config = config; - } - - protected override byte[] GenerateCertificateVerify(ClientHandshakeState state, DigitallySigned certificateVerify) - { - if (certificateVerify.Algorithm != null && config.clientAuthSigAlgClaimed != null) - { - certificateVerify = new DigitallySigned(config.clientAuthSigAlgClaimed, certificateVerify.Signature); - } - - return base.GenerateCertificateVerify(state, certificateVerify); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/DtlsTestServerProtocol.cs b/crypto/test/src/crypto/tls/test/DtlsTestServerProtocol.cs deleted file mode 100644 index 006473cef..000000000 --- a/crypto/test/src/crypto/tls/test/DtlsTestServerProtocol.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -using Org.BouncyCastle.Security; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class DtlsTestServerProtocol - : DtlsServerProtocol - { - protected readonly TlsTestConfig config; - - public DtlsTestServerProtocol(SecureRandom secureRandom, TlsTestConfig config) - : base(secureRandom) - { - this.config = config; - } - } -} diff --git a/crypto/test/src/crypto/tls/test/DtlsTestSuite.cs b/crypto/test/src/crypto/tls/test/DtlsTestSuite.cs deleted file mode 100644 index f191ef005..000000000 --- a/crypto/test/src/crypto/tls/test/DtlsTestSuite.cs +++ /dev/null @@ -1,228 +0,0 @@ -using System; -using System.Collections; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class DtlsTestSuite - { - // Make the access to constants less verbose - internal class C : TlsTestConfig {} - - public DtlsTestSuite() - { - } - - public static IEnumerable Suite() - { - IList testSuite = new ArrayList(); - - AddFallbackTests(testSuite); - AddVersionTests(testSuite, ProtocolVersion.DTLSv10); - AddVersionTests(testSuite, ProtocolVersion.DTLSv12); - - return testSuite; - } - - private static void AddFallbackTests(IList testSuite) - { - { - TlsTestConfig c = CreateDtlsTestConfig(ProtocolVersion.DTLSv12); - c.clientFallback = true; - - AddTestCase(testSuite, c, "FallbackGood"); - } - - /* - * NOTE: Temporarily disabled automatic test runs because of problems getting a clean exit - * of the DTLS server after a fatal alert. As of writing, manual runs show the correct - * alerts being raised - */ - -#if false - { - TlsTestConfig c = CreateDtlsTestConfig(ProtocolVersion.DTLSv12); - c.clientOfferVersion = ProtocolVersion.DTLSv10; - c.clientFallback = true; - c.ExpectServerFatalAlert(AlertDescription.inappropriate_fallback); - - AddTestCase(testSuite, c, "FallbackBad"); - } -#endif - - { - TlsTestConfig c = CreateDtlsTestConfig(ProtocolVersion.DTLSv12); - c.clientOfferVersion = ProtocolVersion.DTLSv10; - - AddTestCase(testSuite, c, "FallbackNone"); - } - } - - private static void AddVersionTests(IList testSuite, ProtocolVersion version) - { - string prefix = version.ToString() - .Replace(" ", "") - .Replace("\\", "") - .Replace(".", "") - + "_"; - - /* - * NOTE: Temporarily disabled automatic test runs because of problems getting a clean exit - * of the DTLS server after a fatal alert. As of writing, manual runs show the correct - * alerts being raised - */ - -#if false - /* - * Server only declares support for SHA1/RSA, client selects MD5/RSA. Since the client is - * NOT actually tracking MD5 over the handshake, we expect fatal alert from the client. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_VALID; - c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa); - c.serverCertReqSigAlgs = TlsUtilities.GetDefaultRsaSignatureAlgorithms(); - c.ExpectClientFatalAlert(AlertDescription.internal_error); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifyHashAlg"); - } - - /* - * Server only declares support for SHA1/ECDSA, client selects SHA1/RSA. Since the client is - * actually tracking SHA1 over the handshake, we expect fatal alert to come from the server - * when it verifies the selected algorithm against the CertificateRequest supported - * algorithms. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_VALID; - c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa); - c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms(); - c.ExpectServerFatalAlert(AlertDescription.illegal_parameter); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlg"); - } - - /* - * Server only declares support for SHA1/ECDSA, client signs with SHA1/RSA, but sends - * SHA1/ECDSA in the CertificateVerify. Since the client is actually tracking SHA1 over the - * handshake, and the claimed algorithm is in the CertificateRequest supported algorithms, - * we expect fatal alert to come from the server when it finds the claimed algorithm - * doesn't match the client certificate. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_VALID; - c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa); - c.clientAuthSigAlgClaimed = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa); - c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms(); - c.ExpectServerFatalAlert(AlertDescription.decrypt_error); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlgMismatch"); - } - - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY; - c.ExpectServerFatalAlert(AlertDescription.decrypt_error); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifySignature"); - } - - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_INVALID_CERT; - c.ExpectServerFatalAlert(AlertDescription.bad_certificate); - - AddTestCase(testSuite, c, prefix + "BadClientCertificate"); - } - - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_NONE; - c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY; - c.ExpectServerFatalAlert(AlertDescription.handshake_failure); - - AddTestCase(testSuite, c, prefix + "BadMandatoryCertReqDeclined"); - } - - /* - * Server selects MD5/RSA for ServerKeyExchange signature, which is not in the default - * supported signature algorithms that the client sent. We expect fatal alert from the - * client when it verifies the selected algorithm against the supported algorithms. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa); - c.ExpectClientFatalAlert(AlertDescription.illegal_parameter); - - AddTestCase(testSuite, c, prefix + "BadServerKeyExchangeSigAlg"); - } - - /* - * Server selects MD5/RSA for ServerKeyExchange signature, which is not the default {sha1,rsa} - * implied by the absent signature_algorithms extension. We expect fatal alert from the - * client when it verifies the selected algorithm against the implicit default. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientSendSignatureAlgorithms = false; - c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa); - c.ExpectClientFatalAlert(AlertDescription.illegal_parameter); - - AddTestCaseDebug(testSuite, c, prefix + "BadServerKeyExchangeSigAlg2"); - } -#endif - - { - TlsTestConfig c = CreateDtlsTestConfig(version); - - AddTestCase(testSuite, c, prefix + "GoodDefault"); - } - - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.serverCertReq = C.SERVER_CERT_REQ_NONE; - - AddTestCase(testSuite, c, prefix + "GoodNoCertReq"); - } - - { - TlsTestConfig c = CreateDtlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_NONE; - - AddTestCase(testSuite, c, prefix + "GoodOptionalCertReqDeclined"); - } - } - - private static void AddTestCase(IList testSuite, TlsTestConfig config, String name) - { - testSuite.Add(new TestCaseData(config).SetName(name)); - } - - private static TlsTestConfig CreateDtlsTestConfig(ProtocolVersion version) - { - TlsTestConfig c = new TlsTestConfig(); - c.clientMinimumVersion = ProtocolVersion.DTLSv10; - c.clientOfferVersion = ProtocolVersion.DTLSv12; - c.serverMaximumVersion = version; - c.serverMinimumVersion = ProtocolVersion.DTLSv10; - return c; - } - - public static void RunTests() - { - foreach (TestCaseData data in Suite()) - { - Console.WriteLine(data.TestName); - new DtlsTestCase().RunTest((TlsTestConfig)data.Arguments[0]); - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/LoggingDatagramTransport.cs b/crypto/test/src/crypto/tls/test/LoggingDatagramTransport.cs deleted file mode 100644 index a26c5bdbf..000000000 --- a/crypto/test/src/crypto/tls/test/LoggingDatagramTransport.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.IO; -using System.Text; - -using Org.BouncyCastle.Utilities.Date; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class LoggingDatagramTransport - : DatagramTransport - { - private static readonly string HEX_CHARS = "0123456789ABCDEF"; - - private readonly DatagramTransport transport; - private readonly TextWriter output; - private readonly long launchTimestamp; - - public LoggingDatagramTransport(DatagramTransport transport, TextWriter output) - { - this.transport = transport; - this.output = output; - this.launchTimestamp = DateTimeUtilities.CurrentUnixMs(); - } - - public virtual int GetReceiveLimit() - { - return transport.GetReceiveLimit(); - } - - public virtual int GetSendLimit() - { - return transport.GetSendLimit(); - } - - public virtual int Receive(byte[] buf, int off, int len, int waitMillis) - { - int length = transport.Receive(buf, off, len, waitMillis); - if (length >= 0) - { - DumpDatagram("Received", buf, off, length); - } - return length; - } - - public virtual void Send(byte[] buf, int off, int len) - { - DumpDatagram("Sending", buf, off, len); - transport.Send(buf, off, len); - } - - public virtual void Close() - { - } - - private void DumpDatagram(string verb, byte[] buf, int off, int len) - { - long timestamp = DateTimeUtilities.CurrentUnixMs() - launchTimestamp; - StringBuilder sb = new StringBuilder("(+" + timestamp + "ms) " + verb + " " + len + " byte datagram:"); - for (int pos = 0; pos < len; ++pos) - { - if (pos % 16 == 0) - { - sb.Append(Environment.NewLine); - sb.Append(" "); - } - else if (pos % 16 == 8) - { - sb.Append('-'); - } - else - { - sb.Append(' '); - } - int val = buf[off + pos] & 0xFF; - sb.Append(HEX_CHARS[val >> 4]); - sb.Append(HEX_CHARS[val & 0xF]); - } - Dump(sb.ToString()); - } - - private void Dump(string s) - { - lock (this) output.WriteLine(s); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/MockDatagramAssociation.cs b/crypto/test/src/crypto/tls/test/MockDatagramAssociation.cs deleted file mode 100644 index 48df36ca9..000000000 --- a/crypto/test/src/crypto/tls/test/MockDatagramAssociation.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections; -using System.IO; -using System.Net; -using System.Threading; - -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class MockDatagramAssociation - { - private int mtu; - private MockDatagramTransport client, server; - - public MockDatagramAssociation(int mtu) - { - this.mtu = mtu; - - IList clientQueue = new ArrayList(); - IList serverQueue = new ArrayList(); - - this.client = new MockDatagramTransport(this, clientQueue, serverQueue); - this.server = new MockDatagramTransport(this, serverQueue, clientQueue); - } - - public virtual DatagramTransport Client - { - get { return client; } - } - - public virtual DatagramTransport Server - { - get { return server; } - } - - private class MockDatagramTransport - : DatagramTransport - { - private readonly MockDatagramAssociation mOuter; - - private IList receiveQueue, sendQueue; - - internal MockDatagramTransport(MockDatagramAssociation outer, IList receiveQueue, IList sendQueue) - { - this.mOuter = outer; - this.receiveQueue = receiveQueue; - this.sendQueue = sendQueue; - } - - public virtual int GetReceiveLimit() - { - return mOuter.mtu; - } - - public virtual int GetSendLimit() - { - return mOuter.mtu; - } - - public virtual int Receive(byte[] buf, int off, int len, int waitMillis) - { - lock (receiveQueue) - { - if (receiveQueue.Count < 1) - { - try - { - Monitor.Wait(receiveQueue, waitMillis); - } - catch (ThreadInterruptedException) - { - // TODO Keep waiting until full wait expired? - } - if (receiveQueue.Count < 1) - { - return -1; - } - } - byte[] packet = (byte[])receiveQueue[0]; - receiveQueue.RemoveAt(0); - int copyLength = System.Math.Min(len, packet.Length); - Array.Copy(packet, 0, buf, off, copyLength); - return copyLength; - } - } - - public virtual void Send(byte[] buf, int off, int len) - { - if (len > mOuter.mtu) - { - // TODO Simulate rejection? - } - - byte[] packet = Arrays.CopyOfRange(buf, off, off + len); - - lock (sendQueue) - { - sendQueue.Add(packet); - Monitor.PulseAll(sendQueue); - } - } - - public virtual void Close() - { - // TODO? - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/MockDtlsClient.cs b/crypto/test/src/crypto/tls/test/MockDtlsClient.cs deleted file mode 100644 index 43b987cc1..000000000 --- a/crypto/test/src/crypto/tls/test/MockDtlsClient.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.Encoders; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class MockDtlsClient - : DefaultTlsClient - { - protected TlsSession mSession; - - public MockDtlsClient(TlsSession session) - { - this.mSession = session; - } - - public override TlsSession GetSessionToResume() - { - return this.mSession; - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("DTLS client raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("DTLS client received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - public override ProtocolVersion ClientVersion - { - get { return ProtocolVersion.DTLSv12; } - } - - public override ProtocolVersion MinimumVersion - { - get { return ProtocolVersion.DTLSv10; } - } - - //public override int[] GetCipherSuites() - //{ - // return Arrays.Concatenate(base.GetCipherSuites(), - // new int[] - // { - // CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - // }); - //} - - public override IDictionary GetClientExtensions() - { - IDictionary clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(base.GetClientExtensions()); - TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions); - { - /* - * NOTE: If you are copying test code, do not blindly set these extensions in your own client. - */ - TlsExtensionsUtilities.AddMaxFragmentLengthExtension(clientExtensions, MaxFragmentLength.pow2_9); - TlsExtensionsUtilities.AddPaddingExtension(clientExtensions, mContext.SecureRandom.Next(16)); - TlsExtensionsUtilities.AddTruncatedHMacExtension(clientExtensions); - } - return clientExtensions; - } - - public override void NotifyServerVersion(ProtocolVersion serverVersion) - { - base.NotifyServerVersion(serverVersion); - - Console.WriteLine("Negotiated " + serverVersion); - } - - public override TlsAuthentication GetAuthentication() - { - return new MyTlsAuthentication(mContext); - } - - public override void NotifyHandshakeComplete() - { - base.NotifyHandshakeComplete(); - - TlsSession newSession = mContext.ResumableSession; - if (newSession != null) - { - byte[] newSessionID = newSession.SessionID; - string hex = Hex.ToHexString(newSessionID); - - if (this.mSession != null && Arrays.AreEqual(this.mSession.SessionID, newSessionID)) - { - Console.WriteLine("Resumed session: " + hex); - } - else - { - Console.WriteLine("Established session: " + hex); - } - - this.mSession = newSession; - } - } - - internal class MyTlsAuthentication - : TlsAuthentication - { - private readonly TlsContext mContext; - - internal MyTlsAuthentication(TlsContext context) - { - this.mContext = context; - } - - public virtual void NotifyServerCertificate(Certificate serverCertificate) - { - X509CertificateStructure[] chain = serverCertificate.GetCertificateList(); - Console.WriteLine("DTLS client received server certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - - public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) - { - byte[] certificateTypes = certificateRequest.CertificateTypes; - if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign)) - return null; - - return TlsTestUtilities.LoadSignerCredentials(mContext, - certificateRequest.SupportedSignatureAlgorithms, SignatureAlgorithm.rsa, - new string[]{ "x509-client-rsa.pem", "x509-ca-rsa.pem" }, "x509-client-key-rsa.pem"); - } - }; - } -} diff --git a/crypto/test/src/crypto/tls/test/MockDtlsServer.cs b/crypto/test/src/crypto/tls/test/MockDtlsServer.cs deleted file mode 100644 index 842cbba58..000000000 --- a/crypto/test/src/crypto/tls/test/MockDtlsServer.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class MockDtlsServer - : DefaultTlsServer - { - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("DTLS server raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("DTLS server received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - protected override int[] GetCipherSuites() - { - return Arrays.Concatenate(base.GetCipherSuites(), - new int[] - { - CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - }); - } - - public override CertificateRequest GetCertificateRequest() - { - byte[] certificateTypes = new byte[]{ ClientCertificateType.rsa_sign, - ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign }; - - IList serverSigAlgs = null; - if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(mServerVersion)) - { - serverSigAlgs = TlsUtilities.GetDefaultSupportedSignatureAlgorithms(); - } - - IList certificateAuthorities = new ArrayList(); - certificateAuthorities.Add(TlsTestUtilities.LoadCertificateResource("x509-ca-rsa.pem").Subject); - - return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities); - } - - public override void NotifyClientCertificate(Certificate clientCertificate) - { - X509CertificateStructure[] chain = clientCertificate.GetCertificateList(); - Console.WriteLine("DTLS server received client certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - - protected override ProtocolVersion MaximumVersion - { - get { return ProtocolVersion.DTLSv12; } - } - - protected override ProtocolVersion MinimumVersion - { - get { return ProtocolVersion.DTLSv10; } - } - - protected override TlsEncryptionCredentials GetRsaEncryptionCredentials() - { - return TlsTestUtilities.LoadEncryptionCredentials(mContext, - new string[] { "x509-server-rsa-enc.pem", "x509-ca-rsa.pem" }, "x509-server-key-rsa-enc.pem"); - } - - protected override TlsSignerCredentials GetRsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, mSupportedSignatureAlgorithms, - SignatureAlgorithm.rsa, new string[]{ "x509-server-rsa-sign.pem", "x509-ca-rsa.pem" }, - "x509-server-key-rsa-sign.pem"); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/MockPskTlsClient.cs b/crypto/test/src/crypto/tls/test/MockPskTlsClient.cs deleted file mode 100644 index 80ebb4dbb..000000000 --- a/crypto/test/src/crypto/tls/test/MockPskTlsClient.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.Encoders; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class MockPskTlsClient - : PskTlsClient - { - internal TlsSession mSession; - - internal MockPskTlsClient(TlsSession session) - : this(session, new BasicTlsPskIdentity("client", Strings.ToUtf8ByteArray("TLS_TEST_PSK"))) - { - } - - internal MockPskTlsClient(TlsSession session, TlsPskIdentity pskIdentity) - : base(pskIdentity) - { - this.mSession = session; - } - - public override TlsSession GetSessionToResume() - { - return this.mSession; - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-PSK client raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-PSK client received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - public override void NotifyHandshakeComplete() - { - base.NotifyHandshakeComplete(); - - TlsSession newSession = mContext.ResumableSession; - if (newSession != null) - { - byte[] newSessionID = newSession.SessionID; - string hex = Hex.ToHexString(newSessionID); - - if (this.mSession != null && Arrays.AreEqual(this.mSession.SessionID, newSessionID)) - { - Console.WriteLine("Resumed session: " + hex); - } - else - { - Console.WriteLine("Established session: " + hex); - } - - this.mSession = newSession; - } - } - - public override int[] GetCipherSuites() - { - return new int[]{ CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, - CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, - CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA }; - } - - public override ProtocolVersion MinimumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - public override IDictionary GetClientExtensions() - { - IDictionary clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(base.GetClientExtensions()); - TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions); - return clientExtensions; - } - - public override void NotifyServerVersion(ProtocolVersion serverVersion) - { - base.NotifyServerVersion(serverVersion); - - Console.WriteLine("TLS-PSK client negotiated " + serverVersion); - } - - public override TlsAuthentication GetAuthentication() - { - return new MyTlsAuthentication(mContext); - } - - internal class MyTlsAuthentication - : ServerOnlyTlsAuthentication - { - private readonly TlsContext mContext; - - internal MyTlsAuthentication(TlsContext context) - { - this.mContext = context; - } - - public override void NotifyServerCertificate(Certificate serverCertificate) - { - X509CertificateStructure[] chain = serverCertificate.GetCertificateList(); - Console.WriteLine("TLS-PSK client received server certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - }; - } -} diff --git a/crypto/test/src/crypto/tls/test/MockPskTlsServer.cs b/crypto/test/src/crypto/tls/test/MockPskTlsServer.cs deleted file mode 100644 index 3a6860280..000000000 --- a/crypto/test/src/crypto/tls/test/MockPskTlsServer.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class MockPskTlsServer - : PskTlsServer - { - internal MockPskTlsServer() - : base(new MyIdentityManager()) - { - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-PSK server raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-PSK server received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - public override void NotifyHandshakeComplete() - { - base.NotifyHandshakeComplete(); - - byte[] pskIdentity = mContext.SecurityParameters.PskIdentity; - if (pskIdentity != null) - { - string name = Strings.FromUtf8ByteArray(pskIdentity); - Console.WriteLine("TLS-PSK server completed handshake for PSK identity: " + name); - } - } - - protected override int[] GetCipherSuites() - { - return new int[]{ CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, - CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, - CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA }; - } - - protected override ProtocolVersion MaximumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - protected override ProtocolVersion MinimumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - public override ProtocolVersion GetServerVersion() - { - ProtocolVersion serverVersion = base.GetServerVersion(); - - Console.WriteLine("TLS-PSK server negotiated " + serverVersion); - - return serverVersion; - } - - protected override TlsEncryptionCredentials GetRsaEncryptionCredentials() - { - return TlsTestUtilities.LoadEncryptionCredentials(mContext, - new string[]{ "x509-server-rsa-enc.pem", "x509-ca-rsa.pem"}, "x509-server-key-rsa-enc.pem"); - } - - internal class MyIdentityManager - : TlsPskIdentityManager - { - public virtual byte[] GetHint() - { - return Strings.ToUtf8ByteArray("hint"); - } - - public virtual byte[] GetPsk(byte[] identity) - { - if (identity != null) - { - string name = Strings.FromUtf8ByteArray(identity); - if (name.Equals("client")) - { - return Strings.ToUtf8ByteArray("TLS_TEST_PSK"); - } - } - return null; - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/MockSrpTlsClient.cs b/crypto/test/src/crypto/tls/test/MockSrpTlsClient.cs deleted file mode 100644 index 8a6b9f496..000000000 --- a/crypto/test/src/crypto/tls/test/MockSrpTlsClient.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.Encoders; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class MockSrpTlsClient - : SrpTlsClient - { - internal TlsSession mSession; - - internal MockSrpTlsClient(TlsSession session, byte[] identity, byte[] password) - : base(identity, password) - { - this.mSession = session; - } - - public override TlsSession GetSessionToResume() - { - return this.mSession; - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-SRP client raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-SRP client received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - public override void NotifyHandshakeComplete() - { - base.NotifyHandshakeComplete(); - - TlsSession newSession = mContext.ResumableSession; - if (newSession != null) - { - byte[] newSessionID = newSession.SessionID; - string hex = Hex.ToHexString(newSessionID); - - if (this.mSession != null && Arrays.AreEqual(this.mSession.SessionID, newSessionID)) - { - Console.WriteLine("Resumed session: " + hex); - } - else - { - Console.WriteLine("Established session: " + hex); - } - - this.mSession = newSession; - } - } - - public override ProtocolVersion MinimumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - public override IDictionary GetClientExtensions() - { - IDictionary clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(base.GetClientExtensions()); - TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions); - return clientExtensions; - } - - public override void NotifyServerVersion(ProtocolVersion serverVersion) - { - base.NotifyServerVersion(serverVersion); - - Console.WriteLine("TLS-SRP client negotiated " + serverVersion); - } - - public override TlsAuthentication GetAuthentication() - { - return new MyTlsAuthentication(mContext); - } - - internal class MyTlsAuthentication - : ServerOnlyTlsAuthentication - { - private readonly TlsContext mContext; - - internal MyTlsAuthentication(TlsContext context) - { - this.mContext = context; - } - - public override void NotifyServerCertificate(Certificate serverCertificate) - { - X509CertificateStructure[] chain = serverCertificate.GetCertificateList(); - Console.WriteLine("TLS-SRP client received server certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - }; - } -} diff --git a/crypto/test/src/crypto/tls/test/MockSrpTlsServer.cs b/crypto/test/src/crypto/tls/test/MockSrpTlsServer.cs deleted file mode 100644 index 61a86d34e..000000000 --- a/crypto/test/src/crypto/tls/test/MockSrpTlsServer.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Crypto.Agreement.Srp; -using Org.BouncyCastle.Crypto.Parameters; -using Org.BouncyCastle.Math; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class MockSrpTlsServer - : SrpTlsServer - { - internal static readonly Srp6GroupParameters TEST_GROUP = Srp6StandardGroups.rfc5054_1024; - internal static readonly byte[] TEST_IDENTITY = Strings.ToUtf8ByteArray("client"); - internal static readonly byte[] TEST_PASSWORD = Strings.ToUtf8ByteArray("password"); - internal static readonly byte[] TEST_SALT = Strings.ToUtf8ByteArray("salt"); - internal static readonly byte[] TEST_SEED_KEY = Strings.ToUtf8ByteArray("seed_key"); - - internal MockSrpTlsServer() - : base(new MyIdentityManager()) - { - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-SRP server raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS-SRP server received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - public override void NotifyHandshakeComplete() - { - base.NotifyHandshakeComplete(); - - byte[] srpIdentity = mContext.SecurityParameters.SrpIdentity; - if (srpIdentity != null) - { - string name = Strings.FromUtf8ByteArray(srpIdentity); - Console.WriteLine("TLS-SRP server completed handshake for SRP identity: " + name); - } - } - - protected override ProtocolVersion MaximumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - protected override ProtocolVersion MinimumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - public override ProtocolVersion GetServerVersion() - { - ProtocolVersion serverVersion = base.GetServerVersion(); - - Console.WriteLine("TLS-SRP server negotiated " + serverVersion); - - return serverVersion; - } - - protected override TlsSignerCredentials GetDsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, mSupportedSignatureAlgorithms, - SignatureAlgorithm.dsa, new string[] { "x509-server-dsa.pem", "x509-ca-dsa.pem" }, - "x509-server-key-dsa.pem"); - } - - protected override TlsSignerCredentials GetRsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, mSupportedSignatureAlgorithms, - SignatureAlgorithm.rsa, new string[] { "x509-server-rsa-sign.pem", "x509-ca-rsa.pem" }, - "x509-server-key-rsa-sign.pem"); - } - - internal class MyIdentityManager - : TlsSrpIdentityManager - { - protected SimulatedTlsSrpIdentityManager unknownIdentityManager = SimulatedTlsSrpIdentityManager.GetRfc5054Default( - TEST_GROUP, TEST_SEED_KEY); - - public virtual TlsSrpLoginParameters GetLoginParameters(byte[] identity) - { - if (Arrays.AreEqual(TEST_IDENTITY, identity)) - { - Srp6VerifierGenerator verifierGenerator = new Srp6VerifierGenerator(); - verifierGenerator.Init(TEST_GROUP, TlsUtilities.CreateHash(HashAlgorithm.sha1)); - - BigInteger verifier = verifierGenerator.GenerateVerifier(TEST_SALT, identity, TEST_PASSWORD); - - return new TlsSrpLoginParameters(TEST_GROUP, verifier, TEST_SALT); - } - - return unknownIdentityManager.GetLoginParameters(identity); - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/MockTlsClient.cs b/crypto/test/src/crypto/tls/test/MockTlsClient.cs deleted file mode 100644 index cdf727cc9..000000000 --- a/crypto/test/src/crypto/tls/test/MockTlsClient.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.Encoders; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class MockTlsClient - : DefaultTlsClient - { - internal TlsSession mSession; - - internal MockTlsClient(TlsSession session) - { - this.mSession = session; - } - - public override TlsSession GetSessionToResume() - { - return this.mSession; - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS client raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS client received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - //public override int[] GetCipherSuites() - //{ - // return Arrays.Concatenate(base.GetCipherSuites(), - // new int[] - // { - // CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - // }); - //} - - public override IDictionary GetClientExtensions() - { - IDictionary clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(base.GetClientExtensions()); - TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions); - { - /* - * NOTE: If you are copying test code, do not blindly set these extensions in your own client. - */ - TlsExtensionsUtilities.AddMaxFragmentLengthExtension(clientExtensions, MaxFragmentLength.pow2_9); - TlsExtensionsUtilities.AddPaddingExtension(clientExtensions, mContext.SecureRandom.Next(16)); - TlsExtensionsUtilities.AddTruncatedHMacExtension(clientExtensions); - } - return clientExtensions; - } - - public override void NotifyServerVersion(ProtocolVersion serverVersion) - { - base.NotifyServerVersion(serverVersion); - - Console.WriteLine("TLS client negotiated " + serverVersion); - } - - public override TlsAuthentication GetAuthentication() - { - return new MyTlsAuthentication(mContext); - } - - public override void NotifyHandshakeComplete() - { - base.NotifyHandshakeComplete(); - - TlsSession newSession = mContext.ResumableSession; - if (newSession != null) - { - byte[] newSessionID = newSession.SessionID; - string hex = Hex.ToHexString(newSessionID); - - if (this.mSession != null && Arrays.AreEqual(this.mSession.SessionID, newSessionID)) - { - Console.WriteLine("Resumed session: " + hex); - } - else - { - Console.WriteLine("Established session: " + hex); - } - - this.mSession = newSession; - } - } - - internal class MyTlsAuthentication - : TlsAuthentication - { - private readonly TlsContext mContext; - - internal MyTlsAuthentication(TlsContext context) - { - this.mContext = context; - } - - public virtual void NotifyServerCertificate(Certificate serverCertificate) - { - X509CertificateStructure[] chain = serverCertificate.GetCertificateList(); - Console.WriteLine("TLS client received server certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - - public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) - { - byte[] certificateTypes = certificateRequest.CertificateTypes; - if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign)) - return null; - - return TlsTestUtilities.LoadSignerCredentials(mContext, - certificateRequest.SupportedSignatureAlgorithms, SignatureAlgorithm.rsa, - new string[]{ "x509-client-rsa.pem", "x509-ca-rsa.pem" }, "x509-client-key-rsa.pem"); - } - }; - } -} diff --git a/crypto/test/src/crypto/tls/test/MockTlsServer.cs b/crypto/test/src/crypto/tls/test/MockTlsServer.cs deleted file mode 100644 index 5911607bc..000000000 --- a/crypto/test/src/crypto/tls/test/MockTlsServer.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class MockTlsServer - : DefaultTlsServer - { - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS server raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS server received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - - protected override int[] GetCipherSuites() - { - return Arrays.Concatenate(base.GetCipherSuites(), - new int[] - { - CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, - }); - } - - protected override ProtocolVersion MaximumVersion - { - get { return ProtocolVersion.TLSv12; } - } - - public override ProtocolVersion GetServerVersion() - { - ProtocolVersion serverVersion = base.GetServerVersion(); - - Console.WriteLine("TLS server negotiated " + serverVersion); - - return serverVersion; - } - - public override CertificateRequest GetCertificateRequest() - { - byte[] certificateTypes = new byte[]{ ClientCertificateType.rsa_sign, - ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign }; - - IList serverSigAlgs = null; - if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(mServerVersion)) - { - serverSigAlgs = TlsUtilities.GetDefaultSupportedSignatureAlgorithms(); - } - - IList certificateAuthorities = new ArrayList(); - certificateAuthorities.Add(TlsTestUtilities.LoadCertificateResource("x509-ca-rsa.pem").Subject); - - return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities); - } - - public override void NotifyClientCertificate(Certificate clientCertificate) - { - X509CertificateStructure[] chain = clientCertificate.GetCertificateList(); - Console.WriteLine("TLS server received client certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - - protected override TlsEncryptionCredentials GetRsaEncryptionCredentials() - { - return TlsTestUtilities.LoadEncryptionCredentials(mContext, - new string[]{ "x509-server-rsa-enc.pem", "x509-ca-rsa.pem" }, "x509-server-key-rsa-enc.pem"); - } - - protected override TlsSignerCredentials GetRsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, mSupportedSignatureAlgorithms, - SignatureAlgorithm.rsa, new string[]{ "x509-server-rsa-sign.pem", "x509-ca-rsa.pem" }, - "x509-server-key-rsa-sign.pem"); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/NetworkStream.cs b/crypto/test/src/crypto/tls/test/NetworkStream.cs deleted file mode 100644 index c20101c8f..000000000 --- a/crypto/test/src/crypto/tls/test/NetworkStream.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.IO; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class NetworkStream - : Stream - { - private readonly Stream mInner; - private bool mClosed = false; - - internal NetworkStream(Stream inner) - { - this.mInner = inner; - } - - internal virtual bool IsClosed - { - get { lock (this) return mClosed; } - } - - public override bool CanRead - { - get { return mInner.CanRead; } - } - - public override bool CanSeek - { - get { return mInner.CanSeek; } - } - - public override bool CanWrite - { - get { return mInner.CanWrite; } - } - - public override void Close() - { - lock (this) mClosed = true; - } - - public override void Flush() - { - mInner.Flush(); - } - - public override long Length - { - get { return mInner.Length; } - } - - public override long Position - { - get { return mInner.Position; } - set { mInner.Position = value; } - } - - public override long Seek(long offset, SeekOrigin origin) - { - return mInner.Seek(offset, origin); - } - - public override void SetLength(long value) - { - mInner.SetLength(value); - } - - public override int Read(byte[] buffer, int offset, int count) - { - CheckNotClosed(); - return mInner.Read(buffer, offset, count); - } - - public override int ReadByte() - { - CheckNotClosed(); - return mInner.ReadByte(); - } - - public override void Write(byte[] buf, int off, int len) - { - CheckNotClosed(); - mInner.Write(buf, off, len); - } - - public override void WriteByte(byte value) - { - CheckNotClosed(); - mInner.WriteByte(value); - } - - private void CheckNotClosed() - { - lock (this) - { - if (mClosed) - throw new ObjectDisposedException(this.GetType().Name); - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/PipedStream.cs b/crypto/test/src/crypto/tls/test/PipedStream.cs deleted file mode 100644 index cfff4b840..000000000 --- a/crypto/test/src/crypto/tls/test/PipedStream.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class PipedStream - : Stream - { - private readonly MemoryStream mBuf = new MemoryStream(); - private bool mClosed = false; - - private PipedStream mOther = null; - private long mReadPos = 0; - - internal PipedStream() - { - } - - internal PipedStream(PipedStream other) - { - lock (other) - { - this.mOther = other; - other.mOther = this; - } - } - - public override bool CanRead - { - get { return true; } - } - - public override bool CanSeek - { - get { return false; } - } - - public override bool CanWrite - { - get { return true; } - } - - public override void Close() - { - lock (this) - { - mClosed = true; - Monitor.PulseAll(this); - } - } - - public override void Flush() - { - } - - public override long Length - { - get { throw new NotImplementedException(); } - } - - public override long Position - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotImplementedException(); - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - lock (mOther) - { - WaitForData(); - int len = (int)System.Math.Min(count, mOther.mBuf.Position - mReadPos); - Array.Copy(mOther.mBuf.GetBuffer(), mReadPos, buffer, offset, len); - mReadPos += len; - return len; - } - } - - public override int ReadByte() - { - lock (mOther) - { - WaitForData(); - bool eof = (mReadPos >= mOther.mBuf.Position); - return eof ? -1 : mOther.mBuf.GetBuffer()[mReadPos++]; - } - } - - public override void Write(byte[] buf, int off, int len) - { - lock (this) - { - CheckOpen(); - mBuf.Write(buf, off, len); - Monitor.PulseAll(this); - } - } - - public override void WriteByte(byte value) - { - lock (this) - { - CheckOpen(); - mBuf.WriteByte(value); - Monitor.PulseAll(mBuf); - } - } - - private void CheckOpen() - { - if (mClosed) - throw new ObjectDisposedException(this.GetType().Name); - } - - private void WaitForData() - { - while (mReadPos >= mOther.mBuf.Position && !mOther.mClosed) - { - Monitor.Wait(mOther); - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/PskTlsClientTest.cs b/crypto/test/src/crypto/tls/test/PskTlsClientTest.cs deleted file mode 100644 index a8c5b470a..000000000 --- a/crypto/test/src/crypto/tls/test/PskTlsClientTest.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.IO; -using System.Net.Sockets; -using System.Text; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - /** - * A simple test designed to conduct a TLS handshake with an external TLS server. - * <p> - * Please refer to GnuTLSSetup.html or OpenSSLSetup.html (under 'docs'), and x509-*.pem files in - * this package (under 'src/test/resources') for help configuring an external TLS server. - * </p><p> - * In both cases, extra options are required to enable PSK ciphersuites and configure identities/keys. - * </p> - */ - public class PskTlsClientTest - { - private static readonly SecureRandom secureRandom = new SecureRandom(); - - public static void Main(string[] args) - { - string hostname = "localhost"; - int port = 5556; - - long time1 = DateTime.UtcNow.Ticks; - - /* - * Note: This is the default PSK identity for 'openssl s_server' testing, the server must be - * started with "-psk 6161616161" to make the keys match, and possibly the "-psk_hint" - * option should be present. - */ - //string psk_identity = "Client_identity"; - //byte[] psk = new byte[]{ 0x61, 0x61, 0x61, 0x61, 0x61 }; - - // These correspond to the configuration of MockPskTlsServer - string psk_identity = "client"; - byte[] psk = Strings.ToUtf8ByteArray("TLS_TEST_PSK"); - - BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(psk_identity, psk); - - MockPskTlsClient client = new MockPskTlsClient(null, pskIdentity); - TlsClientProtocol protocol = OpenTlsConnection(hostname, port, client); - protocol.Close(); - - long time2 = DateTime.UtcNow.Ticks; - Console.WriteLine("Elapsed 1: " + (time2 - time1)/TimeSpan.TicksPerMillisecond + "ms"); - - client = new MockPskTlsClient(client.GetSessionToResume(), pskIdentity); - protocol = OpenTlsConnection(hostname, port, client); - - long time3 = DateTime.UtcNow.Ticks; - Console.WriteLine("Elapsed 2: " + (time3 - time2)/TimeSpan.TicksPerMillisecond + "ms"); - - byte[] req = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n"); - - Stream tlsStream = protocol.Stream; - tlsStream.Write(req, 0, req.Length); - tlsStream.Flush(); - - StreamReader reader = new StreamReader(tlsStream); - - String line; - while ((line = reader.ReadLine()) != null) - { - Console.WriteLine(">>> " + line); - } - - protocol.Close(); - } - - internal static TlsClientProtocol OpenTlsConnection(string hostname, int port, TlsClient client) - { - TcpClient tcp = new TcpClient(hostname, port); - - TlsClientProtocol protocol = new TlsClientProtocol(tcp.GetStream(), secureRandom); - protocol.Connect(client); - return protocol; - } - } -} diff --git a/crypto/test/src/crypto/tls/test/PskTlsServerTest.cs b/crypto/test/src/crypto/tls/test/PskTlsServerTest.cs deleted file mode 100644 index 15766f0a4..000000000 --- a/crypto/test/src/crypto/tls/test/PskTlsServerTest.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities.IO; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - /** - * A simple test designed to conduct a TLS handshake with an external TLS client. - * <p/> - * Please refer to GnuTLSSetup.html or OpenSSLSetup.html (under 'docs'), and x509-*.pem files in - * this package (under 'src/test/resources') for help configuring an external TLS client. - */ - public class PskTlsServerTest - { - private static readonly SecureRandom secureRandom = new SecureRandom(); - - public static void Main(string[] args) - { - int port = 5556; - - TcpListener ss = new TcpListener(IPAddress.Any, port); - ss.Start(); - Stream stdout = Console.OpenStandardOutput(); - try - { - while (true) - { - TcpClient s = ss.AcceptTcpClient(); - Console.WriteLine("--------------------------------------------------------------------------------"); - Console.WriteLine("Accepted " + s); - ServerThread st = new ServerThread(s, stdout); - Thread t = new Thread(new ThreadStart(st.Run)); - t.Start(); - } - } - finally - { - ss.Stop(); - } - } - - internal class ServerThread - { - private readonly TcpClient s; - private readonly Stream stdout; - - internal ServerThread(TcpClient s, Stream stdout) - { - this.s = s; - this.stdout = stdout; - } - - public void Run() - { - try - { - MockPskTlsServer server = new MockPskTlsServer(); - TlsServerProtocol serverProtocol = new TlsServerProtocol(s.GetStream(), secureRandom); - serverProtocol.Accept(server); - Stream log = new TeeOutputStream(serverProtocol.Stream, stdout); - Streams.PipeAll(serverProtocol.Stream, log); - serverProtocol.Close(); - } - finally - { - try - { - s.Close(); - } - catch (IOException) - { - } - finally - { - } - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsClientTest.cs b/crypto/test/src/crypto/tls/test/TlsClientTest.cs deleted file mode 100644 index c9a5ef9ad..000000000 --- a/crypto/test/src/crypto/tls/test/TlsClientTest.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.IO; -using System.Net.Sockets; -using System.Text; - -using Org.BouncyCastle.Security; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - /** - * A simple test designed to conduct a TLS handshake with an external TLS server. - * <p/> - * Please refer to GnuTLSSetup.html or OpenSSLSetup.html (under 'docs'), and x509-*.pem files in - * this package (under 'src/test/resources') for help configuring an external TLS server. - */ - public class TlsClientTest - { - private static readonly SecureRandom secureRandom = new SecureRandom(); - - public static void Main(string[] args) - { - string hostname = "localhost"; - int port = 5556; - - long time1 = DateTime.UtcNow.Ticks; - - MockTlsClient client = new MockTlsClient(null); - TlsClientProtocol protocol = OpenTlsConnection(hostname, port, client); - protocol.Close(); - - long time2 = DateTime.UtcNow.Ticks; - Console.WriteLine("Elapsed 1: " + (time2 - time1)/TimeSpan.TicksPerMillisecond + "ms"); - - client = new MockTlsClient(client.GetSessionToResume()); - protocol = OpenTlsConnection(hostname, port, client); - - long time3 = DateTime.UtcNow.Ticks; - Console.WriteLine("Elapsed 2: " + (time3 - time2)/TimeSpan.TicksPerMillisecond + "ms"); - - byte[] req = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n"); - - Stream tlsStream = protocol.Stream; - tlsStream.Write(req, 0, req.Length); - tlsStream.Flush(); - - StreamReader reader = new StreamReader(tlsStream); - - String line; - while ((line = reader.ReadLine()) != null) - { - Console.WriteLine(">>> " + line); - } - - protocol.Close(); - } - - internal static TlsClientProtocol OpenTlsConnection(string hostname, int port, TlsClient client) - { - TcpClient tcp = new TcpClient(hostname, port); - - TlsClientProtocol protocol = new TlsClientProtocol(tcp.GetStream(), secureRandom); - protocol.Connect(client); - return protocol; - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsProtocolNonBlockingTest.cs b/crypto/test/src/crypto/tls/test/TlsProtocolNonBlockingTest.cs deleted file mode 100644 index 219a65af7..000000000 --- a/crypto/test/src/crypto/tls/test/TlsProtocolNonBlockingTest.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; -using System.IO; - -using NUnit.Framework; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class TlsProtocolNonBlockingTest - { - [Test] - public void TestClientServerFragmented() - { - // tests if it's really non-blocking when partial records arrive - DoTestClientServer(true); - } - - [Test] - public void TestClientServerNonFragmented() - { - DoTestClientServer(false); - } - - private static void DoTestClientServer(bool fragment) - { - SecureRandom secureRandom = new SecureRandom(); - - TlsClientProtocol clientProtocol = new TlsClientProtocol(secureRandom); - TlsServerProtocol serverProtocol = new TlsServerProtocol(secureRandom); - - clientProtocol.Connect(new MockTlsClient(null)); - serverProtocol.Accept(new MockTlsServer()); - - // pump handshake - bool hadDataFromServer = true; - bool hadDataFromClient = true; - while (hadDataFromServer || hadDataFromClient) - { - hadDataFromServer = PumpData(serverProtocol, clientProtocol, fragment); - hadDataFromClient = PumpData(clientProtocol, serverProtocol, fragment); - } - - // send data in both directions - byte[] data = new byte[1024]; - secureRandom.NextBytes(data); - WriteAndRead(clientProtocol, serverProtocol, data, fragment); - WriteAndRead(serverProtocol, clientProtocol, data, fragment); - - // close the connection - clientProtocol.Close(); - PumpData(clientProtocol, serverProtocol, fragment); - serverProtocol.CloseInput(); - CheckClosed(serverProtocol); - CheckClosed(clientProtocol); - } - - private static void WriteAndRead(TlsProtocol writer, TlsProtocol reader, byte[] data, bool fragment) - { - int dataSize = data.Length; - writer.OfferOutput(data, 0, dataSize); - PumpData(writer, reader, fragment); - - Assert.AreEqual(dataSize, reader.GetAvailableInputBytes()); - byte[] readData = new byte[dataSize]; - reader.ReadInput(readData, 0, dataSize); - AssertArrayEquals(data, readData); - } - - private static bool PumpData(TlsProtocol from, TlsProtocol to, bool fragment) - { - int byteCount = from.GetAvailableOutputBytes(); - if (byteCount == 0) - { - return false; - } - - if (fragment) - { - byte[] buffer = new byte[1]; - while (from.GetAvailableOutputBytes() > 0) - { - from.ReadOutput(buffer, 0, 1); - to.OfferInput(buffer); - } - } - else - { - byte[] buffer = new byte[byteCount]; - from.ReadOutput(buffer, 0, buffer.Length); - to.OfferInput(buffer); - } - - return true; - } - - private static void CheckClosed(TlsProtocol protocol) - { - Assert.IsTrue(protocol.IsClosed); - - try - { - protocol.OfferInput(new byte[10]); - Assert.Fail("Input was accepted after close"); - } - catch (IOException) - { - } - - try - { - protocol.OfferOutput(new byte[10], 0, 10); - Assert.Fail("Output was accepted after close"); - } - catch (IOException) - { - } - } - - private static void AssertArrayEquals(byte[] a, byte[] b) - { - Assert.IsTrue(Arrays.AreEqual(a, b)); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsProtocolTest.cs b/crypto/test/src/crypto/tls/test/TlsProtocolTest.cs deleted file mode 100644 index ba5b90c75..000000000 --- a/crypto/test/src/crypto/tls/test/TlsProtocolTest.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.IO; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class TlsProtocolTest - { - [Test] - public void TestClientServer() - { - SecureRandom secureRandom = new SecureRandom(); - - PipedStream clientPipe = new PipedStream(); - PipedStream serverPipe = new PipedStream(clientPipe); - - TlsClientProtocol clientProtocol = new TlsClientProtocol(clientPipe, secureRandom); - TlsServerProtocol serverProtocol = new TlsServerProtocol(serverPipe, secureRandom); - - Server server = new Server(serverProtocol); - - Thread serverThread = new Thread(new ThreadStart(server.Run)); - serverThread.Start(); - - MockTlsClient client = new MockTlsClient(null); - clientProtocol.Connect(client); - - // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity - int length = 1000; - - byte[] data = new byte[length]; - secureRandom.NextBytes(data); - - Stream output = clientProtocol.Stream; - output.Write(data, 0, data.Length); - - byte[] echo = new byte[data.Length]; - int count = Streams.ReadFully(clientProtocol.Stream, echo); - - Assert.AreEqual(count, data.Length); - Assert.IsTrue(Arrays.AreEqual(data, echo)); - - output.Close(); - - serverThread.Join(); - } - - internal class Server - { - private readonly TlsServerProtocol mServerProtocol; - - internal Server(TlsServerProtocol serverProtocol) - { - this.mServerProtocol = serverProtocol; - } - - public void Run() - { - try - { - MockTlsServer server = new MockTlsServer(); - mServerProtocol.Accept(server); - Streams.PipeAll(mServerProtocol.Stream, mServerProtocol.Stream); - mServerProtocol.Close(); - } - catch (Exception) - { - //throw new RuntimeException(e); - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsPskProtocolTest.cs b/crypto/test/src/crypto/tls/test/TlsPskProtocolTest.cs deleted file mode 100644 index b059bb2cb..000000000 --- a/crypto/test/src/crypto/tls/test/TlsPskProtocolTest.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.IO; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class TlsPskProtocolTest - { - [Test] - public void TestClientServer() - { - SecureRandom secureRandom = new SecureRandom(); - - PipedStream clientPipe = new PipedStream(); - PipedStream serverPipe = new PipedStream(clientPipe); - - TlsClientProtocol clientProtocol = new TlsClientProtocol(clientPipe, secureRandom); - TlsServerProtocol serverProtocol = new TlsServerProtocol(serverPipe, secureRandom); - - Server server = new Server(serverProtocol); - - Thread serverThread = new Thread(new ThreadStart(server.Run)); - serverThread.Start(); - - MockPskTlsClient client = new MockPskTlsClient(null); - clientProtocol.Connect(client); - - // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity - int length = 1000; - - byte[] data = new byte[length]; - secureRandom.NextBytes(data); - - Stream output = clientProtocol.Stream; - output.Write(data, 0, data.Length); - - byte[] echo = new byte[data.Length]; - int count = Streams.ReadFully(clientProtocol.Stream, echo); - - Assert.AreEqual(count, data.Length); - Assert.IsTrue(Arrays.AreEqual(data, echo)); - - output.Close(); - - serverThread.Join(); - } - - internal class Server - { - private readonly TlsServerProtocol mServerProtocol; - - internal Server(TlsServerProtocol serverProtocol) - { - this.mServerProtocol = serverProtocol; - } - - public void Run() - { - try - { - MockPskTlsServer server = new MockPskTlsServer(); - mServerProtocol.Accept(server); - Streams.PipeAll(mServerProtocol.Stream, mServerProtocol.Stream); - mServerProtocol.Close(); - } - catch (Exception) - { - //throw new RuntimeException(e); - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsServerTest.cs b/crypto/test/src/crypto/tls/test/TlsServerTest.cs deleted file mode 100644 index 7920cb59a..000000000 --- a/crypto/test/src/crypto/tls/test/TlsServerTest.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities.IO; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - /** - * A simple test designed to conduct a TLS handshake with an external TLS client. - * <p/> - * Please refer to GnuTLSSetup.html or OpenSSLSetup.html (under 'docs'), and x509-*.pem files in - * this package (under 'src/test/resources') for help configuring an external TLS client. - */ - public class TlsServerTest - { - private static readonly SecureRandom secureRandom = new SecureRandom(); - - public static void Main(string[] args) - { - int port = 5556; - - TcpListener ss = new TcpListener(IPAddress.Any, port); - ss.Start(); - Stream stdout = Console.OpenStandardOutput(); - try - { - while (true) - { - TcpClient s = ss.AcceptTcpClient(); - Console.WriteLine("--------------------------------------------------------------------------------"); - Console.WriteLine("Accepted " + s); - ServerThread st = new ServerThread(s, stdout); - Thread t = new Thread(new ThreadStart(st.Run)); - t.Start(); - } - } - finally - { - ss.Stop(); - } - } - - internal class ServerThread - { - private readonly TcpClient s; - private readonly Stream stdout; - - internal ServerThread(TcpClient s, Stream stdout) - { - this.s = s; - this.stdout = stdout; - } - - public void Run() - { - try - { - MockTlsServer server = new MockTlsServer(); - TlsServerProtocol serverProtocol = new TlsServerProtocol(s.GetStream(), secureRandom); - serverProtocol.Accept(server); - Stream log = new TeeOutputStream(serverProtocol.Stream, stdout); - Streams.PipeAll(serverProtocol.Stream, log); - serverProtocol.Close(); - } - finally - { - try - { - s.Close(); - } - catch (IOException) - { - } - finally - { - } - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsSrpProtocolTest.cs b/crypto/test/src/crypto/tls/test/TlsSrpProtocolTest.cs deleted file mode 100644 index 32e126ff2..000000000 --- a/crypto/test/src/crypto/tls/test/TlsSrpProtocolTest.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.IO; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class TlsSrpProtocolTest - { - [Test] - public void TestClientServer() - { - SecureRandom secureRandom = new SecureRandom(); - - PipedStream clientPipe = new PipedStream(); - PipedStream serverPipe = new PipedStream(clientPipe); - - TlsClientProtocol clientProtocol = new TlsClientProtocol(clientPipe, secureRandom); - TlsServerProtocol serverProtocol = new TlsServerProtocol(serverPipe, secureRandom); - - Server server = new Server(serverProtocol); - - Thread serverThread = new Thread(new ThreadStart(server.Run)); - serverThread.Start(); - - MockSrpTlsClient client = new MockSrpTlsClient(null, MockSrpTlsServer.TEST_IDENTITY, MockSrpTlsServer.TEST_PASSWORD); - clientProtocol.Connect(client); - - // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity - int length = 1000; - - byte[] data = new byte[length]; - secureRandom.NextBytes(data); - - Stream output = clientProtocol.Stream; - output.Write(data, 0, data.Length); - - byte[] echo = new byte[data.Length]; - int count = Streams.ReadFully(clientProtocol.Stream, echo); - - Assert.AreEqual(count, data.Length); - Assert.IsTrue(Arrays.AreEqual(data, echo)); - - output.Close(); - - serverThread.Join(); - } - - internal class Server - { - private readonly TlsServerProtocol mServerProtocol; - - internal Server(TlsServerProtocol serverProtocol) - { - this.mServerProtocol = serverProtocol; - } - - public void Run() - { - try - { - MockSrpTlsServer server = new MockSrpTlsServer(); - mServerProtocol.Accept(server); - Streams.PipeAll(mServerProtocol.Stream, mServerProtocol.Stream); - mServerProtocol.Close(); - } - catch (Exception) - { - //throw new RuntimeException(e); - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestCase.cs b/crypto/test/src/crypto/tls/test/TlsTestCase.cs deleted file mode 100644 index 7fb5db6ce..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestCase.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.IO; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - [TestFixture] - public class TlsTestCase - { - private static void CheckTlsVersion(ProtocolVersion version) - { - if (version != null && !version.IsTls) - throw new InvalidOperationException("Non-TLS version"); - } - - [Test, TestCaseSource(typeof(TlsTestSuite), "Suite")] - public void RunTest(TlsTestConfig config) - { - CheckTlsVersion(config.clientMinimumVersion); - CheckTlsVersion(config.clientOfferVersion); - CheckTlsVersion(config.serverMaximumVersion); - CheckTlsVersion(config.serverMinimumVersion); - - SecureRandom secureRandom = new SecureRandom(); - - PipedStream clientPipe = new PipedStream(); - PipedStream serverPipe = new PipedStream(clientPipe); - - NetworkStream clientNet = new NetworkStream(clientPipe); - NetworkStream serverNet = new NetworkStream(serverPipe); - - TlsTestClientProtocol clientProtocol = new TlsTestClientProtocol(clientNet, secureRandom, config); - TlsTestServerProtocol serverProtocol = new TlsTestServerProtocol(serverNet, secureRandom, config); - - TlsTestClientImpl clientImpl = new TlsTestClientImpl(config); - TlsTestServerImpl serverImpl = new TlsTestServerImpl(config); - - Server server = new Server(this, serverProtocol, serverImpl); - - Thread serverThread = new Thread(new ThreadStart(server.Run)); - serverThread.Start(); - - Exception caught = null; - try - { - clientProtocol.Connect(clientImpl); - - // NOTE: Because we write-all before we read-any, this length can't be more than the pipe capacity - int length = 1000; - - byte[] data = new byte[length]; - secureRandom.NextBytes(data); - - Stream output = clientProtocol.Stream; - output.Write(data, 0, data.Length); - - byte[] echo = new byte[data.Length]; - int count = Streams.ReadFully(clientProtocol.Stream, echo); - - Assert.AreEqual(count, data.Length); - Assert.IsTrue(Arrays.AreEqual(data, echo)); - - output.Close(); - } - catch (Exception e) - { - caught = e; - LogException(caught); - } - - server.AllowExit(); - serverThread.Join(); - - Assert.IsTrue(clientNet.IsClosed, "Client Stream not closed"); - Assert.IsTrue(serverNet.IsClosed, "Server Stream not closed"); - - Assert.AreEqual(config.expectFatalAlertConnectionEnd, clientImpl.FirstFatalAlertConnectionEnd, "Client fatal alert connection end"); - Assert.AreEqual(config.expectFatalAlertConnectionEnd, serverImpl.FirstFatalAlertConnectionEnd, "Server fatal alert connection end"); - - Assert.AreEqual(config.expectFatalAlertDescription, clientImpl.FirstFatalAlertDescription, "Client fatal alert description"); - Assert.AreEqual(config.expectFatalAlertDescription, serverImpl.FirstFatalAlertDescription, "Server fatal alert description"); - - if (config.expectFatalAlertConnectionEnd == -1) - { - Assert.IsNull(caught, "Unexpected client exception"); - Assert.IsNull(server.mCaught, "Unexpected server exception"); - } - } - - protected virtual void LogException(Exception e) - { - if (TlsTestConfig.DEBUG) - { - Console.Error.WriteLine(e); - } - } - - internal class Server - { - protected readonly TlsTestCase mOuter; - protected readonly TlsTestServerProtocol mServerProtocol; - protected readonly TlsTestServerImpl mServerImpl; - - internal bool mCanExit = false; - internal Exception mCaught = null; - - internal Server(TlsTestCase outer, TlsTestServerProtocol serverProtocol, TlsTestServerImpl serverImpl) - { - this.mOuter = outer; - this.mServerProtocol = serverProtocol; - this.mServerImpl = serverImpl; - } - - internal void AllowExit() - { - lock (this) - { - mCanExit = true; - Monitor.PulseAll(this); - } - } - - public void Run() - { - try - { - mServerProtocol.Accept(mServerImpl); - Streams.PipeAll(mServerProtocol.Stream, mServerProtocol.Stream); - mServerProtocol.Close(); - } - catch (Exception e) - { - mCaught = e; - mOuter.LogException(mCaught); - } - - WaitExit(); - } - - protected void WaitExit() - { - lock (this) - { - while (!mCanExit) - { - try - { - Monitor.Wait(this); - } - catch (ThreadInterruptedException) - { - } - } - } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestClientImpl.cs b/crypto/test/src/crypto/tls/test/TlsTestClientImpl.cs deleted file mode 100644 index ae1f632ba..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestClientImpl.cs +++ /dev/null @@ -1,284 +0,0 @@ -using System; -using System.Collections; -using System.IO; - -using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class TlsTestClientImpl - : DefaultTlsClient - { - protected readonly TlsTestConfig mConfig; - - protected int firstFatalAlertConnectionEnd = -1; - protected int firstFatalAlertDescription = -1; - - internal TlsTestClientImpl(TlsTestConfig config) - { - this.mConfig = config; - } - - internal int FirstFatalAlertConnectionEnd - { - get { return firstFatalAlertConnectionEnd; } - } - - internal int FirstFatalAlertDescription - { - get { return firstFatalAlertDescription; } - } - - public override ProtocolVersion ClientVersion - { - get - { - if (mConfig.clientOfferVersion != null) - { - return mConfig.clientOfferVersion; - } - - return base.ClientVersion; - } - } - - public override ProtocolVersion MinimumVersion - { - get - { - if (mConfig.clientMinimumVersion != null) - { - return mConfig.clientMinimumVersion; - } - - return base.MinimumVersion; - } - } - - public override IDictionary GetClientExtensions() - { - IDictionary clientExtensions = base.GetClientExtensions(); - if (clientExtensions != null && !mConfig.clientSendSignatureAlgorithms) - { - clientExtensions.Remove(ExtensionType.signature_algorithms); - this.mSupportedSignatureAlgorithms = null; - } - return clientExtensions; - } - - public override bool IsFallback - { - get { return mConfig.clientFallback; } - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - if (alertLevel == AlertLevel.fatal && firstFatalAlertConnectionEnd == -1) - { - firstFatalAlertConnectionEnd = ConnectionEnd.client; - firstFatalAlertDescription = alertDescription; - } - - if (TlsTestConfig.DEBUG) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS client raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - output.WriteLine("> " + message); - } - if (cause != null) - { - output.WriteLine(cause); - } - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - if (alertLevel == AlertLevel.fatal && firstFatalAlertConnectionEnd == -1) - { - firstFatalAlertConnectionEnd = ConnectionEnd.server; - firstFatalAlertDescription = alertDescription; - } - - if (TlsTestConfig.DEBUG) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS client received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - } - - public override void NotifyServerVersion(ProtocolVersion serverVersion) - { - base.NotifyServerVersion(serverVersion); - - if (TlsTestConfig.DEBUG) - { - Console.WriteLine("TLS client negotiated " + serverVersion); - } - } - - public override TlsAuthentication GetAuthentication() - { - return new MyTlsAuthentication(this, mContext); - } - - protected virtual Certificate CorruptCertificate(Certificate cert) - { - X509CertificateStructure[] certList = cert.GetCertificateList(); - certList[0] = CorruptCertificateSignature(certList[0]); - return new Certificate(certList); - } - - protected virtual X509CertificateStructure CorruptCertificateSignature(X509CertificateStructure cert) - { - Asn1EncodableVector v = new Asn1EncodableVector(); - v.Add(cert.TbsCertificate); - v.Add(cert.SignatureAlgorithm); - v.Add(CorruptSignature(cert.Signature)); - - return X509CertificateStructure.GetInstance(new DerSequence(v)); - } - - protected virtual DerBitString CorruptSignature(DerBitString bs) - { - return new DerBitString(CorruptBit(bs.GetOctets())); - } - - protected virtual byte[] CorruptBit(byte[] bs) - { - bs = Arrays.Clone(bs); - - // Flip a random bit - int bit = mContext.SecureRandom.Next(bs.Length << 3); - bs[bit >> 3] ^= (byte)(1 << (bit & 7)); - - return bs; - } - - internal class MyTlsAuthentication - : TlsAuthentication - { - private readonly TlsTestClientImpl mOuter; - private readonly TlsContext mContext; - - internal MyTlsAuthentication(TlsTestClientImpl outer, TlsContext context) - { - this.mOuter = outer; - this.mContext = context; - } - - public virtual void NotifyServerCertificate(Certificate serverCertificate) - { - bool isEmpty = serverCertificate == null || serverCertificate.IsEmpty; - - X509CertificateStructure[] chain = serverCertificate.GetCertificateList(); - - // TODO Cache test resources? - if (isEmpty || !( - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-server-dsa.pem")) || - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-server-ecdsa.pem")) || - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-server-rsa-enc.pem")) || - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-server-rsa-sign.pem")) - )) - { - throw new TlsFatalAlert(AlertDescription.bad_certificate); - } - - if (TlsTestConfig.DEBUG) - { - Console.WriteLine("TLS client received server certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - } - - public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) - { - if (mOuter.mConfig.serverCertReq == TlsTestConfig.SERVER_CERT_REQ_NONE) - throw new InvalidOperationException(); - if (mOuter.mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_NONE) - return null; - - byte[] certificateTypes = certificateRequest.CertificateTypes; - if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign)) - { - return null; - } - - IList supportedSigAlgs = certificateRequest.SupportedSignatureAlgorithms; - if (supportedSigAlgs != null && mOuter.mConfig.clientAuthSigAlg != null) - { - supportedSigAlgs = new ArrayList(1); - supportedSigAlgs.Add(mOuter.mConfig.clientAuthSigAlg); - } - - TlsSignerCredentials signerCredentials = TlsTestUtilities.LoadSignerCredentials(mContext, - supportedSigAlgs, SignatureAlgorithm.rsa, new string[]{ "x509-client-rsa.pem", "x509-ca-rsa.pem" }, - "x509-client-key-rsa.pem"); - - if (mOuter.mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_VALID) - { - return signerCredentials; - } - - return new MyTlsSignerCredentials(mOuter, signerCredentials); - } - }; - - internal class MyTlsSignerCredentials - : TlsSignerCredentials - { - private readonly TlsTestClientImpl mOuter; - private readonly TlsSignerCredentials mInner; - - internal MyTlsSignerCredentials(TlsTestClientImpl outer, TlsSignerCredentials inner) - { - this.mOuter = outer; - this.mInner = inner; - } - - public virtual byte[] GenerateCertificateSignature(byte[] hash) - { - byte[] sig = mInner.GenerateCertificateSignature(hash); - - if (mOuter.mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_INVALID_VERIFY) - { - sig = mOuter.CorruptBit(sig); - } - - return sig; - } - - public virtual Certificate Certificate - { - get - { - Certificate cert = mInner.Certificate; - - if (mOuter.mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_INVALID_CERT) - { - cert = mOuter.CorruptCertificate(cert); - } - - return cert; - } - } - - public virtual SignatureAndHashAlgorithm SignatureAndHashAlgorithm - { - get { return mInner.SignatureAndHashAlgorithm; } - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestClientProtocol.cs b/crypto/test/src/crypto/tls/test/TlsTestClientProtocol.cs deleted file mode 100644 index 97b7c91bc..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestClientProtocol.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.IO; - -using Org.BouncyCastle.Security; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class TlsTestClientProtocol - : TlsClientProtocol - { - protected readonly TlsTestConfig config; - - public TlsTestClientProtocol(Stream stream, SecureRandom secureRandom, TlsTestConfig config) - : base(stream, secureRandom) - { - this.config = config; - } - - protected override void SendCertificateVerifyMessage(DigitallySigned certificateVerify) - { - if (certificateVerify.Algorithm != null && config.clientAuthSigAlgClaimed != null) - { - certificateVerify = new DigitallySigned(config.clientAuthSigAlgClaimed, certificateVerify.Signature); - } - - base.SendCertificateVerifyMessage(certificateVerify); - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestConfig.cs b/crypto/test/src/crypto/tls/test/TlsTestConfig.cs deleted file mode 100644 index ccbb919d2..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestConfig.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Collections; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class TlsTestConfig - { - public static readonly bool DEBUG = false; - - /** - * Client does not authenticate, ignores any certificate request - */ - public const int CLIENT_AUTH_NONE = 0; - - /** - * Client will authenticate if it receives a certificate request - */ - public const int CLIENT_AUTH_VALID = 1; - - /** - * Client will authenticate if it receives a certificate request, with an invalid certificate - */ - public const int CLIENT_AUTH_INVALID_CERT = 2; - - /** - * Client will authenticate if it receives a certificate request, with an invalid CertificateVerify signature - */ - public const int CLIENT_AUTH_INVALID_VERIFY = 3; - - /** - * Server will not request a client certificate - */ - public const int SERVER_CERT_REQ_NONE = 0; - - /** - * Server will request a client certificate but receiving one is optional - */ - public const int SERVER_CERT_REQ_OPTIONAL = 1; - - /** - * Server will request a client certificate and receiving one is mandatory - */ - public const int SERVER_CERT_REQ_MANDATORY = 2; - - /** - * Configures the client authentication behaviour of the test client. Use CLIENT_AUTH_* constants. - */ - public int clientAuth = CLIENT_AUTH_VALID; - - /** - * If not null, and TLS 1.2 or higher is negotiated, selects a fixed signature/hash algorithm to - * be used for the CertificateVerify signature (if one is sent). - */ - public SignatureAndHashAlgorithm clientAuthSigAlg = null; - - /** - * If not null, and TLS 1.2 or higher is negotiated, selects a fixed signature/hash algorithm to - * be _claimed_ in the CertificateVerify (if one is sent), independently of what was actually used. - */ - public SignatureAndHashAlgorithm clientAuthSigAlgClaimed = null; - - /** - * Configures the minimum protocol version the client will accept. If null, uses the library's default. - */ - public ProtocolVersion clientMinimumVersion = null; - - /** - * Configures the protocol version the client will offer. If null, uses the library's default. - */ - public ProtocolVersion clientOfferVersion = null; - - /** - * Configures whether the client will indicate version fallback via TLS_FALLBACK_SCSV. - */ - public bool clientFallback = false; - - /** - * Configures whether a (TLS 1.2+) client will send the signature_algorithms extension in ClientHello. - */ - public bool clientSendSignatureAlgorithms = true; - - /** - * If not null, and TLS 1.2 or higher is negotiated, selects a fixed signature/hash algorithm to - * be used for the ServerKeyExchange signature (if one is sent). - */ - public SignatureAndHashAlgorithm serverAuthSigAlg = null; - - /** - * Configures whether the test server will send a certificate request. - */ - public int serverCertReq = SERVER_CERT_REQ_OPTIONAL; - - /** - * If TLS 1.2 or higher is negotiated, configures the set of supported signature algorithms in the - * CertificateRequest (if one is sent). If null, uses a default set. - */ - public IList serverCertReqSigAlgs = null; - - /** - * Configures the maximum protocol version the server will accept. If null, uses the library's default. - */ - public ProtocolVersion serverMaximumVersion = null; - - /** - * Configures the minimum protocol version the server will accept. If null, uses the library's default. - */ - public ProtocolVersion serverMinimumVersion = null; - - /** - * Configures the connection end that a fatal alert is expected to be raised. Use ConnectionEnd.* constants. - */ - public int expectFatalAlertConnectionEnd = -1; - - /** - * Configures the type of fatal alert expected to be raised. Use AlertDescription.* constants. - */ - public int expectFatalAlertDescription = -1; - - public void ExpectClientFatalAlert(byte alertDescription) - { - this.expectFatalAlertConnectionEnd = ConnectionEnd.client; - this.expectFatalAlertDescription = alertDescription; - } - - public void ExpectServerFatalAlert(byte alertDescription) - { - this.expectFatalAlertConnectionEnd = ConnectionEnd.server; - this.expectFatalAlertDescription = alertDescription; - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestServerImpl.cs b/crypto/test/src/crypto/tls/test/TlsTestServerImpl.cs deleted file mode 100644 index 2587181a5..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestServerImpl.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System; -using System.Collections; -using System.IO; -using System.Threading; - -using Org.BouncyCastle.Asn1; -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Utilities; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class TlsTestServerImpl - : DefaultTlsServer - { - protected readonly TlsTestConfig mConfig; - - protected int firstFatalAlertConnectionEnd = -1; - protected int firstFatalAlertDescription = -1; - - internal TlsTestServerImpl(TlsTestConfig config) - { - this.mConfig = config; - } - - internal int FirstFatalAlertConnectionEnd - { - get { return firstFatalAlertConnectionEnd; } - } - - internal int FirstFatalAlertDescription - { - get { return firstFatalAlertDescription; } - } - - protected override ProtocolVersion MaximumVersion - { - get - { - if (mConfig.serverMaximumVersion != null) - { - return mConfig.serverMaximumVersion; - } - - return base.MaximumVersion; - } - } - - protected override ProtocolVersion MinimumVersion - { - get - { - if (mConfig.serverMinimumVersion != null) - { - return mConfig.serverMinimumVersion; - } - - return base.MinimumVersion; - } - } - - public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause) - { - if (alertLevel == AlertLevel.fatal && firstFatalAlertConnectionEnd == -1) - { - firstFatalAlertConnectionEnd = ConnectionEnd.server; - firstFatalAlertDescription = alertDescription; - } - - if (TlsTestConfig.DEBUG) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - output.WriteLine("TLS server raised alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - if (message != null) - { - SafeWriteLine(output, "> " + message); - } - if (cause != null) - { - SafeWriteLine(output, cause); - } - } - } - - public override void NotifyAlertReceived(byte alertLevel, byte alertDescription) - { - if (alertLevel == AlertLevel.fatal && firstFatalAlertConnectionEnd == -1) - { - firstFatalAlertConnectionEnd = ConnectionEnd.client; - firstFatalAlertDescription = alertDescription; - } - - if (TlsTestConfig.DEBUG) - { - TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out; - SafeWriteLine(output, "TLS server received alert: " + AlertLevel.GetText(alertLevel) - + ", " + AlertDescription.GetText(alertDescription)); - } - } - - public override ProtocolVersion GetServerVersion() - { - ProtocolVersion serverVersion = base.GetServerVersion(); - - if (TlsTestConfig.DEBUG) - { - Console.WriteLine("TLS server negotiated " + serverVersion); - } - - return serverVersion; - } - - public override CertificateRequest GetCertificateRequest() - { - if (mConfig.serverCertReq == TlsTestConfig.SERVER_CERT_REQ_NONE) - { - return null; - } - - byte[] certificateTypes = new byte[]{ ClientCertificateType.rsa_sign, - ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign }; - - IList serverSigAlgs = null; - if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(mServerVersion)) - { - serverSigAlgs = mConfig.serverCertReqSigAlgs; - if (serverSigAlgs == null) - { - serverSigAlgs = TlsUtilities.GetDefaultSupportedSignatureAlgorithms(); - } - } - - IList certificateAuthorities = new ArrayList(); - certificateAuthorities.Add(TlsTestUtilities.LoadCertificateResource("x509-ca-rsa.pem").Subject); - - return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities); - } - - public override void NotifyClientCertificate(Certificate clientCertificate) - { - bool isEmpty = (clientCertificate == null || clientCertificate.IsEmpty); - - if (isEmpty != (mConfig.clientAuth == TlsTestConfig.CLIENT_AUTH_NONE)) - { - throw new InvalidOperationException(); - } - if (isEmpty && (mConfig.serverCertReq == TlsTestConfig.SERVER_CERT_REQ_MANDATORY)) - { - throw new TlsFatalAlert(AlertDescription.handshake_failure); - } - - X509CertificateStructure[] chain = clientCertificate.GetCertificateList(); - - // TODO Cache test resources? - if (!isEmpty && !( - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-client-dsa.pem")) || - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-client-ecdsa.pem")) || - chain[0].Equals(TlsTestUtilities.LoadCertificateResource("x509-client-rsa.pem")) - )) - { - throw new TlsFatalAlert(AlertDescription.bad_certificate); - } - - if (TlsTestConfig.DEBUG) - { - Console.WriteLine("TLS server received client certificate chain of length " + chain.Length); - for (int i = 0; i != chain.Length; i++) - { - X509CertificateStructure entry = chain[i]; - // TODO Create fingerprint based on certificate signature algorithm digest - Console.WriteLine(" fingerprint:SHA-256 " + TlsTestUtilities.Fingerprint(entry) + " (" - + entry.Subject + ")"); - } - } - } - - protected virtual IList GetSupportedSignatureAlgorithms() - { - if (TlsUtilities.IsTlsV12(mContext) && mConfig.serverAuthSigAlg != null) - { - IList signatureAlgorithms = new ArrayList(1); - signatureAlgorithms.Add(mConfig.serverAuthSigAlg); - return signatureAlgorithms; - } - - return mSupportedSignatureAlgorithms; - } - - protected override TlsSignerCredentials GetDsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, GetSupportedSignatureAlgorithms(), - SignatureAlgorithm.dsa, new string[]{ "x509-server-dsa.pem", "x509-ca-dsa.pem" }, - "x509-server-key-dsa.pem"); - } - - protected override TlsSignerCredentials GetECDsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, GetSupportedSignatureAlgorithms(), - SignatureAlgorithm.ecdsa, new string[]{ "x509-server-ecdsa.pem", "x509-ca-ecdsa.pem" }, - "x509-server-key-ecdsa.pem"); - } - - protected override TlsEncryptionCredentials GetRsaEncryptionCredentials() - { - return TlsTestUtilities.LoadEncryptionCredentials(mContext, - new string[]{ "x509-server-rsa-enc.pem", "x509-ca-rsa.pem" }, "x509-server-key-rsa-enc.pem"); - } - - protected override TlsSignerCredentials GetRsaSignerCredentials() - { - return TlsTestUtilities.LoadSignerCredentials(mContext, GetSupportedSignatureAlgorithms(), - SignatureAlgorithm.rsa, new string[]{ "x509-server-rsa-sign.pem", "x509-ca-rsa.pem" }, - "x509-server-key-rsa-sign.pem"); - } - - private static void SafeWriteLine(TextWriter output, object line) - { - try - { - output.WriteLine(line); - } - catch (ThreadInterruptedException) - { - /* - * For some reason the NUnit plugin in Visual Studio started throwing these during alert logging - */ - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestServerProtocol.cs b/crypto/test/src/crypto/tls/test/TlsTestServerProtocol.cs deleted file mode 100644 index 845b7f0b9..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestServerProtocol.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.IO; - -using Org.BouncyCastle.Security; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - internal class TlsTestServerProtocol - : TlsServerProtocol - { - protected readonly TlsTestConfig config; - - public TlsTestServerProtocol(Stream stream, SecureRandom secureRandom, TlsTestConfig config) - : base(stream, secureRandom) - { - this.config = config; - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestSuite.cs b/crypto/test/src/crypto/tls/test/TlsTestSuite.cs deleted file mode 100644 index 849e738af..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestSuite.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using System.Collections; - -using NUnit.Framework; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class TlsTestSuite - { - // Make the access to constants less verbose - internal class C : TlsTestConfig {} - - public TlsTestSuite() - { - } - - public static IEnumerable Suite() - { - IList testSuite = new ArrayList(); - - AddFallbackTests(testSuite); - AddVersionTests(testSuite, ProtocolVersion.SSLv3); - AddVersionTests(testSuite, ProtocolVersion.TLSv10); - AddVersionTests(testSuite, ProtocolVersion.TLSv11); - AddVersionTests(testSuite, ProtocolVersion.TLSv12); - - return testSuite; - } - - private static void AddFallbackTests(IList testSuite) - { - { - TlsTestConfig c = CreateTlsTestConfig(ProtocolVersion.TLSv12); - c.clientFallback = true; - - AddTestCase(testSuite, c, "FallbackGood"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(ProtocolVersion.TLSv12); - c.clientOfferVersion = ProtocolVersion.TLSv11; - c.clientFallback = true; - c.ExpectServerFatalAlert(AlertDescription.inappropriate_fallback); - - AddTestCase(testSuite, c, "FallbackBad"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(ProtocolVersion.TLSv12); - c.clientOfferVersion = ProtocolVersion.TLSv11; - - AddTestCase(testSuite, c, "FallbackNone"); - } - } - - private static void AddVersionTests(IList testSuite, ProtocolVersion version) - { - string prefix = version.ToString() - .Replace(" ", "") - .Replace("\\", "") - .Replace(".", "") - + "_"; - - { - TlsTestConfig c = CreateTlsTestConfig(version); - - AddTestCase(testSuite, c, prefix + "GoodDefault"); - } - - /* - * Server only declares support for SHA1/RSA, client selects MD5/RSA. Since the client is - * NOT actually tracking MD5 over the handshake, we expect fatal alert from the client. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_VALID; - c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa); - c.serverCertReqSigAlgs = TlsUtilities.GetDefaultRsaSignatureAlgorithms(); - c.ExpectClientFatalAlert(AlertDescription.internal_error); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifyHashAlg"); - } - - /* - * Server only declares support for SHA1/ECDSA, client selects SHA1/RSA. Since the client is - * actually tracking SHA1 over the handshake, we expect fatal alert to come from the server - * when it verifies the selected algorithm against the CertificateRequest supported - * algorithms. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_VALID; - c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa); - c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms(); - c.ExpectServerFatalAlert(AlertDescription.illegal_parameter); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlg"); - } - - /* - * Server only declares support for SHA1/ECDSA, client signs with SHA1/RSA, but sends - * SHA1/ECDSA in the CertificateVerify. Since the client is actually tracking SHA1 over the - * handshake, and the claimed algorithm is in the CertificateRequest supported algorithms, - * we expect fatal alert to come from the server when it finds the claimed algorithm - * doesn't match the client certificate. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_VALID; - c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa); - c.clientAuthSigAlgClaimed = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa); - c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms(); - c.ExpectServerFatalAlert(AlertDescription.decrypt_error); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlgMismatch"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY; - c.ExpectServerFatalAlert(AlertDescription.decrypt_error); - - AddTestCase(testSuite, c, prefix + "BadCertificateVerifySignature"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_INVALID_CERT; - c.ExpectServerFatalAlert(AlertDescription.bad_certificate); - - AddTestCase(testSuite, c, prefix + "BadClientCertificate"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_NONE; - c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY; - c.ExpectServerFatalAlert(AlertDescription.handshake_failure); - - AddTestCase(testSuite, c, prefix + "BadMandatoryCertReqDeclined"); - } - - /* - * Server selects MD5/RSA for ServerKeyExchange signature, which is not in the default - * supported signature algorithms that the client sent. We expect fatal alert from the - * client when it verifies the selected algorithm against the supported algorithms. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa); - c.ExpectClientFatalAlert(AlertDescription.illegal_parameter); - - AddTestCase(testSuite, c, prefix + "BadServerKeyExchangeSigAlg"); - } - - /* - * Server selects MD5/RSA for ServerKeyExchange signature, which is not the default {sha1,rsa} - * implied by the absent signature_algorithms extension. We expect fatal alert from the - * client when it verifies the selected algorithm against the implicit default. - */ - if (TlsUtilities.IsTlsV12(version)) - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientSendSignatureAlgorithms = false; - c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa); - c.ExpectClientFatalAlert(AlertDescription.illegal_parameter); - - AddTestCase(testSuite, c, prefix + "BadServerKeyExchangeSigAlg2"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.serverCertReq = C.SERVER_CERT_REQ_NONE; - - AddTestCase(testSuite, c, prefix + "GoodNoCertReq"); - } - - { - TlsTestConfig c = CreateTlsTestConfig(version); - c.clientAuth = C.CLIENT_AUTH_NONE; - - AddTestCase(testSuite, c, prefix + "GoodOptionalCertReqDeclined"); - } - } - - private static void AddTestCase(IList testSuite, TlsTestConfig config, string name) - { - testSuite.Add(new TestCaseData(config).SetName(name)); - } - - private static TlsTestConfig CreateTlsTestConfig(ProtocolVersion version) - { - TlsTestConfig c = new TlsTestConfig(); - c.clientMinimumVersion = ProtocolVersion.SSLv3; - c.clientOfferVersion = ProtocolVersion.TLSv12; - c.serverMaximumVersion = version; - c.serverMinimumVersion = ProtocolVersion.SSLv3; - return c; - } - - public static void RunTests() - { - foreach (TestCaseData data in Suite()) - { - Console.WriteLine(data.TestName); - new TlsTestCase().RunTest((TlsTestConfig)data.Arguments[0]); - } - } - } -} diff --git a/crypto/test/src/crypto/tls/test/TlsTestUtilities.cs b/crypto/test/src/crypto/tls/test/TlsTestUtilities.cs deleted file mode 100644 index 27d7c913a..000000000 --- a/crypto/test/src/crypto/tls/test/TlsTestUtilities.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections; -using System.Globalization; -using System.IO; -using System.Text; - -using Org.BouncyCastle.Asn1.Pkcs; -using Org.BouncyCastle.Asn1.X509; -using Org.BouncyCastle.Crypto.Digests; -using Org.BouncyCastle.Crypto.Parameters; -using Org.BouncyCastle.Security; -using Org.BouncyCastle.Utilities; -using Org.BouncyCastle.Utilities.Encoders; -using Org.BouncyCastle.Utilities.IO.Pem; -using Org.BouncyCastle.Utilities.Test; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public abstract class TlsTestUtilities - { - internal static readonly byte[] RsaCertData = Base64 - .Decode("MIICUzCCAf2gAwIBAgIBATANBgkqhkiG9w0BAQQFADCBjzELMAkGA1UEBhMCQVUxKDAmBgNVBAoMH1RoZSBMZWdpb2" - + "4gb2YgdGhlIEJvdW5jeSBDYXN0bGUxEjAQBgNVBAcMCU1lbGJvdXJuZTERMA8GA1UECAwIVmljdG9yaWExLzAtBgkq" - + "hkiG9w0BCQEWIGZlZWRiYWNrLWNyeXB0b0Bib3VuY3ljYXN0bGUub3JnMB4XDTEzMDIyNTA2MDIwNVoXDTEzMDIyNT" - + "A2MDM0NVowgY8xCzAJBgNVBAYTAkFVMSgwJgYDVQQKDB9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIw" - + "EAYDVQQHDAlNZWxib3VybmUxETAPBgNVBAgMCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWVkYmFjay1jcnlwdG" - + "9AYm91bmN5Y2FzdGxlLm9yZzBaMA0GCSqGSIb3DQEBAQUAA0kAMEYCQQC0p+RhcFdPFqlwgrIr5YtqKmKXmEGb4Shy" - + "pL26Ymz66ZAPdqv7EhOdzl3lZWT6srZUMWWgQMYGiHQg4z2R7X7XAgERo0QwQjAOBgNVHQ8BAf8EBAMCBSAwEgYDVR" - + "0lAQH/BAgwBgYEVR0lADAcBgNVHREBAf8EEjAQgQ50ZXN0QHRlc3QudGVzdDANBgkqhkiG9w0BAQQFAANBAHU55Ncz" - + "eglREcTg54YLUlGWu2WOYWhit/iM1eeq8Kivro7q98eW52jTuMI3CI5ulqd0hYzshQKQaZ5GDzErMyM="); - - internal static readonly byte[] DudRsaCertData = Base64 - .Decode("MIICUzCCAf2gAwIBAgIBATANBgkqhkiG9w0BAQQFADCBjzELMAkGA1UEBhMCQVUxKDAmBgNVBAoMH1RoZSBMZWdpb2" - + "4gb2YgdGhlIEJvdW5jeSBDYXN0bGUxEjAQBgNVBAcMCU1lbGJvdXJuZTERMA8GA1UECAwIVmljdG9yaWExLzAtBgkq" - + "hkiG9w0BCQEWIGZlZWRiYWNrLWNyeXB0b0Bib3VuY3ljYXN0bGUub3JnMB4XDTEzMDIyNTA1NDcyOFoXDTEzMDIyNT" - + "A1NDkwOFowgY8xCzAJBgNVBAYTAkFVMSgwJgYDVQQKDB9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIw" - + "EAYDVQQHDAlNZWxib3VybmUxETAPBgNVBAgMCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWVkYmFjay1jcnlwdG" - + "9AYm91bmN5Y2FzdGxlLm9yZzBaMA0GCSqGSIb3DQEBAQUAA0kAMEYCQQC0p+RhcFdPFqlwgrIr5YtqKmKXmEGb4Shy" - + "pL26Ymz66ZAPdqv7EhOdzl3lZWT6srZUMWWgQMYGiHQg4z2R7X7XAgERo0QwQjAOBgNVHQ8BAf8EBAMCAAEwEgYDVR" - + "0lAQH/BAgwBgYEVR0lADAcBgNVHREBAf8EEjAQgQ50ZXN0QHRlc3QudGVzdDANBgkqhkiG9w0BAQQFAANBAJg55PBS" - + "weg6obRUKF4FF6fCrWFi6oCYSQ99LWcAeupc5BofW5MstFMhCOaEucuGVqunwT5G7/DweazzCIrSzB0="); - - internal static string Fingerprint(X509CertificateStructure c) - { - byte[] der = c.GetEncoded(); - byte[] sha1 = Sha256DigestOf(der); - byte[] hexBytes = Hex.Encode(sha1); - - string hex = Encoding.ASCII.GetString(hexBytes); -#if PORTABLE - string upper = hex.ToUpperInvariant(); -#else - string upper = hex.ToUpper(CultureInfo.InvariantCulture); -#endif - - StringBuilder fp = new StringBuilder(); - int i = 0; - fp.Append(upper.Substring(i, 2)); - while ((i += 2) < upper.Length) - { - fp.Append(':'); - fp.Append(upper.Substring(i, 2)); - } - return fp.ToString(); - } - - internal static byte[] Sha256DigestOf(byte[] input) - { - return DigestUtilities.CalculateDigest("SHA256", input); - } - - internal static TlsAgreementCredentials LoadAgreementCredentials(TlsContext context, - string[] certResources, string keyResource) - { - Certificate certificate = LoadCertificateChain(certResources); - AsymmetricKeyParameter privateKey = LoadPrivateKeyResource(keyResource); - - return new DefaultTlsAgreementCredentials(certificate, privateKey); - } - - internal static TlsEncryptionCredentials LoadEncryptionCredentials(TlsContext context, - string[] certResources, string keyResource) - { - Certificate certificate = LoadCertificateChain(certResources); - AsymmetricKeyParameter privateKey = LoadPrivateKeyResource(keyResource); - - return new DefaultTlsEncryptionCredentials(context, certificate, privateKey); - } - - internal static TlsSignerCredentials LoadSignerCredentials(TlsContext context, string[] certResources, - string keyResource, SignatureAndHashAlgorithm signatureAndHashAlgorithm) - { - Certificate certificate = LoadCertificateChain(certResources); - AsymmetricKeyParameter privateKey = LoadPrivateKeyResource(keyResource); - - return new DefaultTlsSignerCredentials(context, certificate, privateKey, signatureAndHashAlgorithm); - } - - internal static TlsSignerCredentials LoadSignerCredentials(TlsContext context, IList supportedSignatureAlgorithms, - byte signatureAlgorithm, string[] certResources, string keyResource) - { - /* - * TODO Note that this code fails to provide default value for the client supported - * algorithms if it wasn't sent. - */ - - SignatureAndHashAlgorithm signatureAndHashAlgorithm = null; - if (supportedSignatureAlgorithms != null) - { - foreach (SignatureAndHashAlgorithm alg in supportedSignatureAlgorithms) - { - if (alg.Signature == signatureAlgorithm) - { - signatureAndHashAlgorithm = alg; - break; - } - } - - if (signatureAndHashAlgorithm == null) - return null; - } - - return LoadSignerCredentials(context, certResources, keyResource, signatureAndHashAlgorithm); - } - - internal static Certificate LoadCertificateChain(string[] resources) - { - X509CertificateStructure[] chain = new X509CertificateStructure[resources.Length]; - for (int i = 0; i < resources.Length; ++i) - { - chain[i] = LoadCertificateResource(resources[i]); - } - return new Certificate(chain); - } - - internal static X509CertificateStructure LoadCertificateResource(string resource) - { - PemObject pem = LoadPemResource(resource); - if (pem.Type.EndsWith("CERTIFICATE")) - { - return X509CertificateStructure.GetInstance(pem.Content); - } - throw new ArgumentException("doesn't specify a valid certificate", "resource"); - } - - internal static AsymmetricKeyParameter LoadPrivateKeyResource(string resource) - { - PemObject pem = LoadPemResource(resource); - if (pem.Type.EndsWith("RSA PRIVATE KEY")) - { - RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(pem.Content); - return new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, - rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, - rsa.Exponent2, rsa.Coefficient); - } - if (pem.Type.EndsWith("PRIVATE KEY")) - { - return PrivateKeyFactory.CreateKey(pem.Content); - } - throw new ArgumentException("doesn't specify a valid private key", "resource"); - } - - internal static PemObject LoadPemResource(string resource) - { - Stream s = SimpleTest.GetTestDataAsStream("tls." + resource); - PemReader p = new PemReader(new StreamReader(s)); - PemObject o = p.ReadPemObject(); - p.Reader.Close(); - return o; - } - } -} diff --git a/crypto/test/src/crypto/tls/test/UnreliableDatagramTransport.cs b/crypto/test/src/crypto/tls/test/UnreliableDatagramTransport.cs deleted file mode 100644 index b771ab7cf..000000000 --- a/crypto/test/src/crypto/tls/test/UnreliableDatagramTransport.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.IO; - -using Org.BouncyCastle.Utilities.Date; - -namespace Org.BouncyCastle.Crypto.Tls.Tests -{ - public class UnreliableDatagramTransport - : DatagramTransport - { - private readonly DatagramTransport transport; - private readonly Random random; - private readonly int percentPacketLossReceiving, percentPacketLossSending; - - public UnreliableDatagramTransport(DatagramTransport transport, Random random, - int percentPacketLossReceiving, int percentPacketLossSending) - { - if (percentPacketLossReceiving < 0 || percentPacketLossReceiving > 100) - throw new ArgumentException("out of range", "percentPacketLossReceiving"); - if (percentPacketLossSending < 0 || percentPacketLossSending > 100) - throw new ArgumentException("out of range", "percentPacketLossSending"); - - this.transport = transport; - this.random = random; - this.percentPacketLossReceiving = percentPacketLossReceiving; - this.percentPacketLossSending = percentPacketLossSending; - } - - public virtual int GetReceiveLimit() - { - return transport.GetReceiveLimit(); - } - - public virtual int GetSendLimit() - { - return transport.GetSendLimit(); - } - - public virtual int Receive(byte[] buf, int off, int len, int waitMillis) - { - long endMillis = DateTimeUtilities.CurrentUnixMs() + waitMillis; - for (;;) - { - int length = transport.Receive(buf, off, len, waitMillis); - if (length < 0 || !LostPacket(percentPacketLossReceiving)) - { - return length; - } - - Console.WriteLine("PACKET LOSS (" + length + " byte packet not received)"); - - long now = DateTimeUtilities.CurrentUnixMs(); - if (now >= endMillis) - { - return -1; - } - - waitMillis = (int)(endMillis - now); - } - } - - public virtual void Send(byte[] buf, int off, int len) - { - if (LostPacket(percentPacketLossSending)) - { - Console.WriteLine("PACKET LOSS (" + len + " byte packet not sent)"); - } - else - { - transport.Send(buf, off, len); - } - } - - public virtual void Close() - { - transport.Close(); - } - - private bool LostPacket(int percentPacketLoss) - { - return percentPacketLoss > 0 && random.Next(100) < percentPacketLoss; - } - } -} |