Beispiel #1
0
 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
         {
         }
     }
 }
 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
         {
         }
     }
 }
        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);
            CheckClosed(serverProtocol);
            CheckClosed(clientProtocol);
        }
        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);
        }
Beispiel #5
0
        protected void Disposing(bool dispose)
        {
            if (dispose & !disposed)
            {
                disposed = true;
                if (!(State == ChannelState.Closed || State == ChannelState.ClosedReceived))
                {
                    try
                    {
                        CloseAsync().GetAwaiter();
                        //Task task = CloseAsync();
                        //Task.WaitAll(task);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception Dispose/Closing TCP Server 2 {0}", ex.Message);
                        Console.WriteLine("***** Inner Exception {0} *****", ex.InnerException);
                        Console.WriteLine("***** Stack Trace {0} *****", ex.InnerException.StackTrace);
                    }
                }

                protocol        = null;
                client          = null;
                readConnection  = null;
                writeConnection = null;
            }
        }
Beispiel #6
0
        public override async Task OpenAsync()
        {
            State = ChannelState.Connecting;

            readConnection  = new SemaphoreSlim(1);
            writeConnection = new SemaphoreSlim(1);

            try
            {
                localStream = client.GetStream();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fault opening TCP Channel 2  - {0}", ex.Message);
                OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex));
            }

            if (pskManager != null)
            {
                try
                {
                    protocol    = client.ConnectPskTlsServer(pskManager, localStream);
                    stream      = protocol.Stream;
                    IsEncrypted = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Fault opening TLS connection {0}", ex.Message);
                    State = ChannelState.Aborted;
                    Trace.TraceError(ex.Message);
                    OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex));
                    return;
                }
            }
            else if (certificate != null)
            {
                try
                {
                    stream      = new SslStream(localStream, true, new RemoteCertificateValidationCallback(ValidateCertificate));
                    IsEncrypted = true;
                    await((SslStream)stream).AuthenticateAsServerAsync(certificate, clientAuth, SslProtocols.Tls12, true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Fault opening TCP Channel 2  via Cert - {0}", ex.Message);
                    State = ChannelState.Aborted;
                    Trace.TraceError(ex.Message);
                    OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex));
                    return;
                }
            }
            else
            {
                stream = localStream;
            }

            State = ChannelState.Open;
            OnOpen?.Invoke(this, new ChannelOpenEventArgs(Id, null));
        }
Beispiel #7
0
        public override async Task CloseAsync()
        {
            Console.WriteLine("Starting TCP Channel 2 close action");

            if (State == ChannelState.Closed || State == ChannelState.ClosedReceived)
            {
                Console.WriteLine("TCP channel 2 is already closed...returning");
                return;
            }

            State = ChannelState.ClosedReceived;

            try
            {
                if (protocol != null)
                {
                    protocol.Close();
                }
            }
            catch { }

            protocol = null;

            if (client != null && client.Client != null && (client.Client.Connected && client.Client.Poll(10, SelectMode.SelectRead)))
            {
                if (client.Client.UseOnlyOverlappedIO)
                {
                    client.Client.DuplicateAndClose(Process.GetCurrentProcess().Id);
                }
                else
                {
                    client.Close();
                }
            }

            client = null;

            if (readConnection != null)
            {
                readConnection.Dispose();
            }

            if (writeConnection != null)
            {
                writeConnection.Dispose();
            }

            State = ChannelState.Closed;
            OnClose?.Invoke(this, new ChannelCloseEventArgs(Id));

            await Task.CompletedTask;
        }
        public async Task OnConnectionAsync(ConnectionContext context)
        {
            var inputStream  = context.Transport.Input.AsStream();
            var outputStream = context.Transport.Output.AsStream();
            var protocol     = new TlsServerProtocol(inputStream, outputStream, new Org.BouncyCastle.Security.SecureRandom());

            protocol.Accept(new BlazeTlsServer(_options));
            var sslStream = protocol.Stream;


            var memoryPool = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool;

            var inputPipeOptions = new StreamPipeReaderOptions
                                   (
                pool: memoryPool,
                bufferSize: memoryPool.GetMinimumSegmentSize(),
                minimumReadSize: memoryPool.GetMinimumAllocSize(),
                leaveOpen: true
                                   );


            var outputPipeOptions = new StreamPipeWriterOptions
                                    (
                pool: memoryPool,
                leaveOpen: true
                                    );

            var sslDuplexPipe = new DuplexPipeStreamAdapter <Stream>(context.Transport, inputPipeOptions, outputPipeOptions, sslStream);

            var originalTransport = context.Transport;

            try
            {
                context.Transport = sslDuplexPipe;

                // Disposing the stream will dispose the sslDuplexPipe
                await using (sslStream)
                    await using (sslDuplexPipe)
                    {
                        await _next(context).ConfigureAwait(false);

                        // Dispose the inner stream (SslDuplexPipe) before disposing the SslStream
                        // as the duplex pipe can hit an ODE as it still may be writing.
                    }
            }
            finally
            {
                context.Transport = originalTransport;
            }
        }
Beispiel #9
0
 public static TlsServerProtocol ConnectPskTlsServer(TlsPskIdentityManager pskManager, Stream stream)
 {
     try
     {
         PskTlsServer      server   = new PskTlsServer2(pskManager);
         TlsServerProtocol protocol = new TlsServerProtocol(stream, new SecureRandom());
         protocol.Accept(server);
         return(protocol);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Exception in TLS protocol connnection '{0}'", ex.Message);
         throw ex;
     }
 }
Beispiel #10
0
        /// <summary>
        /// Start up a session on the server side
        /// </summary>
        public void Accept()
        {
            TlsServerProtocol serverProtocol = new TlsServerProtocol(new SecureRandom());

            TlsServer server = new TlsServer(_signingKeys, _clientKeys);

            //  Make sure we do not startup a listing thread as the correct call is always made
            //  byt the DTLS accept protocol.

            _stm = _client.GetStream();
            serverProtocol.Accept(server);

            bool sleep = true;

            while (!server.HandshakeComplete)
            {
                sleep = true;

                if (_stm.DataAvailable)
                {
                    byte[] data   = new byte[1024];
                    int    cbRead = _stm.Read(data, 0, data.Length);
                    Array.Resize(ref data, cbRead);
                    serverProtocol.OfferInput(data);
                    sleep = false;
                }

                int cbToRead = serverProtocol.GetAvailableOutputBytes();
                if (cbToRead != 0)
                {
                    byte[] data   = new byte[cbToRead];
                    int    cbRead = serverProtocol.ReadOutput(data, 0, cbToRead);
                    _stm.Write(data, 0, cbRead);
                    sleep = false;
                }


                if (sleep)
                {
                    Thread.Sleep(100);
                }
            }

            _tlsServer = serverProtocol;
            _authKey   = server.AuthenticationKey;

            _stm.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, this);
        }
Beispiel #11
0
        public static TlsServerProtocol ConnectPskTlsServerNonBlocking(Dictionary <string, byte[]> psks)
        {
            try
            {
                TlsPskIdentityManager pskTlsManager = new PskIdentityManager(psks);
                PskTlsServer2         server        = new PskTlsServer2(pskTlsManager);
                TlsServerProtocol     protocol      = new TlsServerProtocol(new SecureRandom());
                protocol.Accept(server);

                return(protocol);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in TLS protocol connnection '{0}'", ex.Message);
                throw ex;
            }
        }
 public static TlsServerProtocol ConnectPskTlsServer(this TcpClient client, TlsPskIdentityManager pskManager, Stream stream)
 {
     try
     {
         PskTlsServer      server   = new PskTlsServer2(pskManager);
         TlsServerProtocol protocol = new TlsServerProtocol(stream, new SecureRandom());
         protocol.Accept(server);
         return(protocol);
     }
     catch (AggregateException ae)
     {
         string msg = String.Format("AggregateException in TLS protocol connnection '{0}'", ae.Flatten().InnerException.Message);
         Console.WriteLine(msg);
         throw new Exception(msg, ae.Flatten().InnerException);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Exception in TLS protocol connnection '{0}'", ex.Message);
         throw ex;
     }
 }
Beispiel #13
0
        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();
        }
        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();
        }
Beispiel #15
0
        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);

            TlsClientProtocol clientProtocol = new TlsClientProtocol(clientNet, secureRandom);
            TlsServerProtocol serverProtocol = new TlsServerProtocol(serverNet, secureRandom);

            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");
            }
        }
 internal Server(TlsServerProtocol serverProtocol)
 {
     this.mServerProtocol = serverProtocol;
 }
Beispiel #17
0
 internal Server(TlsServerProtocol serverProtocol)
 {
     this.mServerProtocol = serverProtocol;
 }
        private IDataAdapter ConnectServerBC(IDataAdapter adapter, Logger logger, PropertyBag properties)
        {
            X509Certificate cert = null;

            // If server certificate not specified try and auto generate one
            if (!_config.SpecifyServerCert)
            {
                if (_remoteCert != null)
                {
                    cert = _remoteCert;
                }
                else
                {
                    cert = CertManager.GetCertificate("CN=localhost");
                }
            }
            else if (_config.ServerCertificate != null)
            {
                cert = _config.ServerCertificate.Certificate;
            }
            else
            {
                // Ideally shouldn't get here, but not necessarily consistent :)
                cert = CertManager.GetCertificate("CN=localhost");
            }

            DataAdapterToStream stm = new DataAdapterToStream(adapter);

            TlsServerProtocol server = new TlsServerProtocol(stm, stm, new SecureRandom());


            bool setReadTimeout = false;
            int  oldTimeout     = -1;

            try
            {
                oldTimeout      = stm.ReadTimeout;
                stm.ReadTimeout = _config.Timeout;
                setReadTimeout  = true;
            }
            catch (InvalidOperationException)
            {
            }

            X509Certificate[] certs;

            // If we have a remote chain then duplicate all certificates
            if (_remoteChain.Count > 0)
            {
                certs = _remoteChain.ToArray();
            }
            else
            {
                certs = new X509Certificate[] { cert };
            }

            // Accept with our CA key, doesn't really matter what it is but no point generating each time
            server.Accept(new CustomTlsServer(certs, CertManager.GetRootCert().PrivateKey, logger));

            if (setReadTimeout)
            {
                stm.ReadTimeout = oldTimeout;
            }

            // Return re-adapted layer
            return(new StreamDataAdapter(server.Stream, adapter.Description));
        }
Beispiel #19
0
 internal Server(TlsTestCase outer, TlsServerProtocol serverProtocol, TlsTestServerImpl serverImpl)
 {
     this.mOuter          = outer;
     this.mServerProtocol = serverProtocol;
     this.mServerImpl     = serverImpl;
 }
        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);

            TlsClientProtocol clientProtocol = new TlsClientProtocol(clientNet, secureRandom);
            TlsServerProtocol serverProtocol = new TlsServerProtocol(serverNet, secureRandom);

            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");
            }
        }
 internal Server(TlsTestCase outer, TlsServerProtocol serverProtocol, TlsTestServerImpl serverImpl)
 {
     this.mOuter = outer;
     this.mServerProtocol = serverProtocol;
     this.mServerImpl = serverImpl;
 }