Пример #1
0
        private void onConnect(IAsyncResult res)
        {
            try
            {
                socket.EndConnect(res);
                stream = new NetworkStream(socket);

                if (usesSSL)
                {
                    sslStream = new SslStream(stream, false, onCertificateValidate);
                    sslStream.BeginAuthenticateAsClient(serverName, onAuthenticate, null);
                    stream = sslStream;
                }
                else
                {
                    OnConnect();
                    waitForData();
                }
            }
            catch (SocketException e)
            {
                OnConnectFailed(ConnectError.SocketError, e.ErrorCode);
            }
            catch (Exception e)
            {
                OnConnectFailed(ConnectError.SocketError, null);
                System.Diagnostics.Debug.WriteLine("Connect failed: " + e.Message);
                throw;
            }
        }
Пример #2
0
        private void InitClientSocket(Socket socket, string targetHost, bool validateServer)
        {
            Ensure.NotNull(targetHost, "targetHost");

            InitConnectionBase(socket);
            //_log.Info("TcpConnectionSsl::InitClientSocket({0}, L{1})", RemoteEndPoint, LocalEndPoint);

            _validateServer = validateServer;

            lock (_streamLock) {
                try {
                    socket.NoDelay = true;
                } catch (ObjectDisposedException) {
                    CloseInternal(SocketError.Shutdown, "Socket is disposed.");
                    return;
                }

                _sslStream = new SslStream(new NetworkStream(socket, true), false, ValidateServerCertificate, null);
                try {
                    _sslStream.BeginAuthenticateAsClient(targetHost, OnEndAuthenticateAsClient, _sslStream);
                } catch (AuthenticationException exc) {
                    _log.Info(exc, "[S{0}, L{1}]: Authentication exception on BeginAuthenticateAsClient.",
                              RemoteEndPoint, LocalEndPoint);
                    CloseInternal(SocketError.SocketError, exc.Message);
                } catch (ObjectDisposedException) {
                    CloseInternal(SocketError.SocketError, "SslStream disposed.");
                } catch (Exception exc) {
                    _log.Info(exc, "[S{0}, L{1}]: Exception on BeginAuthenticateAsClient.", RemoteEndPoint,
                              LocalEndPoint);
                    CloseInternal(SocketError.SocketError, exc.Message);
                }
            }
        }
Пример #3
0
 /// <summary>
 /// Ends a pending asynchronous connection request.
 /// </summary>
 /// <param name="ar">An IAsyncResult object that stores state information and any user-defined data for this asynchronous operation.</param>
 private void ConnectCallBack(IAsyncResult ar)
 {
     try
     {
         _socket.EndConnect(ar);
         _stream = CertificateValidationCallback == null ? new SslStream(new NetworkStream(_socket), LEAVE_INNER_STREAM_OPEN) : new SslStream(new NetworkStream(_socket), LEAVE_INNER_STREAM_OPEN, CertificateValidationCallback);
         _stream.BeginAuthenticateAsClient(RemoteHostName, ClientCertificates, SslProtocol, CheckCertificateRevocation, AuthenticateAsClientCallBack, null);
         OnConnected(new SocketEventArgs(_remoteEndPoint));
     }
     catch (SocketException e)
     {
         if (e.ErrorCode == 10053 || e.ErrorCode == 10054)
         {
             Disconnect();
         }
         else
         {
             OnSocketError(new SocketErrorEventArgs(_remoteEndPoint, e));
         }
     }
     catch (IOException e)
     {
         OnError(new ErrorEventArgs(_remoteEndPoint, e));
         Disconnect();
     }
     catch (Exception e)
     {
         OnError(new ErrorEventArgs(_remoteEndPoint, e));
     }
 }
Пример #4
0
        private void CheckSSLCertificate(Session session)
        {
            TcpClient client = new TcpClient(session.host, session.port);
            SslStream ssl    = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null);


            // first do cert validation checks for SSLv3 and TLS
            try
            {
                AsyncCallback callBack = new AsyncCallback(DoCertValidation);
                SSLstate      state    = new SSLstate(ssl, client, session);
                ssl.BeginAuthenticateAsClient(session.host, null, SslProtocols.Default, true, callBack, state);
            }
            catch (AuthenticationException e)
            {
                if (e.InnerException != null)
                {
                    error = e.InnerException.Message;
                }

                AddAlert(session, error);
            }

            catch (IOException)
            {
                // Something went wrong.  Silently continue.
                return;
            }
        }
Пример #5
0
        public void FailsUntilNet462ButPassesOnNewerNetFramework()
        {
            Exception exception = null;

            try
            {
                MemoryStream stream    = new MemoryStream();
                SslStream    sslStream = new SslStream(stream);

                // this throws SSLException on net451-net462, on net471 onwards it passes so we can use it to test that we target correctly
                sslStream.BeginAuthenticateAsClient("microsoft.com", null, SslProtocols.None, false, new AsyncCallback(ProcessInformation), null);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            switch (this.TargetFramework)
            {
            case "NET451":
            case "NET452":
            case "NET46":
            case "NET461":
            case "NET462":
                Assert.NotNull(exception);
                break;

            default:
                Assert.Null(exception);
                break;
            }
        }
Пример #6
0
 internal static Task AuthenticateAsClientAsync(this SslStream sslStream, SslClientAuthenticationOptions option,
                                                CancellationToken token)
 {
     return(Task.Factory.FromAsync((callback, state) =>
                                   sslStream.BeginAuthenticateAsClient(option.TargetHost, option.ClientCertificates, option.EnabledSslProtocols,
                                                                       option.CertificateRevocationCheckMode != X509RevocationMode.NoCheck, callback, state), sslStream.EndAuthenticateAsClient, null));
 }
Пример #7
0
        public bool Connect(string host, int port, int timeout = 5)
        {
            timeout *= 1000;

            client = new TcpClient()
            {
                NoDelay = true
            };
            var clientResult = client.BeginConnect(host, port, null, null);

            if (clientResult.AsyncWaitHandle.WaitOne(timeout))
            {
                client.EndConnect(clientResult);
            }
            if (!client.Connected)
            {
                return(false);
            }

            stream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );
            var streamResult = stream.BeginAuthenticateAsClient(host, null, null);

            if (streamResult.AsyncWaitHandle.WaitOne(timeout))
            {
                stream.EndAuthenticateAsClient(streamResult);
            }
            return(stream.IsAuthenticated);
        }
            private void OnConnectSink(IAsyncResult ar)
            {
                if (wsclient == null)
                {
                    return;
                }

                // Accept the connection
                try
                {
                    wsclient.EndConnect(ar);
                } catch (Exception ex) {
                    Debug("Websocket TCP failed to connect: " + ex.ToString());
                    Dispose();
                    return;
                }

                if (proxyInUse == true)
                {
                    // Send proxy connection request
                    wsrawstream = wsclient.GetStream();
                    byte[] proxyRequestBuf = UTF8Encoding.UTF8.GetBytes("CONNECT " + url.Host + ":" + url.Port + " HTTP/1.1\r\nHost: " + url.Host + ":" + url.Port + "\r\n\r\n");
                    wsrawstream.Write(proxyRequestBuf, 0, proxyRequestBuf.Length);
                    wsrawstream.BeginRead(readBuffer, readBufferLen, readBuffer.Length - readBufferLen, new AsyncCallback(OnProxyResponseSink), this);
                }
                else
                {
                    // Start TLS connection
                    Debug("Websocket TCP connected, doing TLS...");
                    wsstream = new SslStream(wsclient.GetStream(), false, VerifyServerCertificate, null);
                    wsstream.BeginAuthenticateAsClient(url.Host, null, System.Security.Authentication.SslProtocols.Tls12, false, new AsyncCallback(OnTlsSetupSink), this);
                }
            }
Пример #9
0
        private void ClientAsyncSslHelper(EncryptionPolicy encryptionPolicy, SslProtocols clientSslProtocols,
                                          SslProtocols serverSslProtocols)
        {
            _log.WriteLine("Server: " + serverSslProtocols + "; Client: " + clientSslProtocols);

            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);

            using (var server = new DummyTcpServer(endPoint, encryptionPolicy))
                using (var client = new TcpClient(AddressFamily.InterNetworkV6))
                {
                    server.SslProtocols = serverSslProtocols;
                    client.Connect(server.RemoteEndPoint);
                    using (SslStream sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
                    {
                        IAsyncResult async = sslStream.BeginAuthenticateAsClient("localhost", null, clientSslProtocols, false, null, null);
                        Assert.True(async.AsyncWaitHandle.WaitOne(TestConfiguration.TestTimeoutSeconds * 1000), "Timed Out");
                        sslStream.EndAuthenticateAsClient(async);

                        _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
                                       client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
                                       sslStream.CipherAlgorithm, sslStream.CipherStrength);
                        Assert.True(sslStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL");
                        Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0");
                    }
                }
        }
Пример #10
0
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                this.client.EndConnect(ar);
            }
            catch (Exception ex)
            {
                this.ConnectionError(ex);
                return;
            }

            if (this.tls)
            {
                this.State = MqttState.StartingEncryption;

                SslStream SslStream = new SslStream(this.client.GetStream(), false, this.RemoteCertificateValidationCallback);
                this.stream = SslStream;

                SslStream.BeginAuthenticateAsClient(this.host, null, SslProtocols.Tls, true, this.AuthenticateAsClientCallback, null);
            }
            else
            {
                this.stream = this.client.GetStream();
                this.CONNECT(KeepAliveTimeSeconds);
            }
        }
Пример #11
0
        /// <summary>
        /// This method is invoked when an asynchronous connect operation completes
        /// </summary>
        private void ProcessConnect(SocketAsyncEventArgs e)
        {
            IsConnecting = false;

            if (e.SocketError == SocketError.Success)
            {
                // Apply the option: keep alive
                if (OptionKeepAlive)
                {
                    Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                }
                // Apply the option: no delay
                if (OptionNoDelay)
                {
                    Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
                }

                // Prepare receive & send buffers
                _receiveBuffer.Reserve(OptionReceiveBufferSize);
                _sendBufferMain.Reserve(OptionSendBufferSize);
                _sendBufferFlush.Reserve(OptionSendBufferSize);

                // Reset statistic
                BytesPending  = 0;
                BytesSending  = 0;
                BytesSent     = 0;
                BytesReceived = 0;

                // Update the connected flag
                IsConnected = true;

                // Call the client connected handler
                OnConnected();

                try
                {
                    // Create SSL stream
                    _sslStreamId = Guid.NewGuid();
                    _sslStream   = (Context.CertificateValidationCallback != null) ? new SslStream(new NetworkStream(Socket, false), false, Context.CertificateValidationCallback) : new SslStream(new NetworkStream(Socket, false), false);

                    // Call the session handshaking handler
                    OnHandshaking();

                    // Begin the SSL handshake
                    IsHandshaking = true;
                    _sslStream.BeginAuthenticateAsClient(Address, Context.Certificates ?? new X509CertificateCollection(new[] { Context.Certificate }), Context.Protocols, true, ProcessHandshake, _sslStreamId);
                }
                catch (Exception)
                {
                    SendError(SocketError.NotConnected);
                    DisconnectAsync();
                }
            }
            else
            {
                // Call the client disconnected handler
                SendError(e.SocketError);
                OnDisconnected();
            }
        }
        protected override void OnGetSocket(SocketAsyncEventArgs e)
        {
            try
            {
#if SILVERLIGHT
                var sslStream = new SslStream(new NetworkStream(Client));
                sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
#else
                var securityOption = Security;

                if (securityOption == null)
                {
                    throw new Exception("securityOption was not configured");
                }

#if NETSTANDARD
                AuthenticateAsClientAsync(new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate), Security);
#else
                var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
                sslStream.BeginAuthenticateAsClient(HostName, securityOption.Certificates, securityOption.EnabledSslProtocols, false, OnAuthenticated, sslStream);
#endif
#endif
            }
            catch (Exception exc)
            {
                if (!IsIgnorableException(exc))
                {
                    OnError(exc);
                }
            }
        }
Пример #13
0
        private void ProcessSocketConnection(SocketAsyncEventArgs connectEventArgs)
        {
            // Double-check if the connection was successful
            if (connectEventArgs.SocketError != SocketError.Success)
            {
                Close(TcpConnectionCloseType.Unexpected, "Connection closed for no reason");
                throw new Exception("Connection closed for no reason");
            }

            // Try to establish a SSL connection
            try
            {
                _ssl             = new SslStream(new NetworkStream(_socket, false));
                ConnectionStatus = "AuthenticatingSSL";
                _ssl.BeginAuthenticateAsClient(_host, new X509CertificateCollection(), SslProtocols.Tls12, true, ar =>
                {
                    ((TcpConnection)ar.AsyncState).ProcessSslAuthentication(ar);
                }, this);
            }
            catch (Exception ex)
            {
                Close(TcpConnectionCloseType.Unexpected, "SSL authentication failed");
                throw new Exception("SSL authentication failed", ex);
            }
        }
Пример #14
0
        // guarantees to close the socket on error
        public static void TlsConnect(Socket sock, string host, RemoteCertificateValidationCallback rcvc, Action <Exception, SslStream> cb)
        {
            SslStream ssl = null;

            try {
                ssl = new SslStream(new NetworkStream(sock, true), false, rcvc);
                ssl.BeginAuthenticateAsClient(host, (ar) => {
                    try {
                        ssl.EndAuthenticateAsClient(ar);
                    } catch (Exception ex) {
                        ssl.Dispose();
                        sock.Dispose();
                        cb(ex, null);
                        return;
                    }
                    cb(null, ssl);
                }, null);
            } catch (Exception ex) {
                if (ssl != null)
                {
                    ssl.Dispose();
                }
                sock.Dispose();
                cb(ex, null);
            }
        }
Пример #15
0
        public static void AuthenticateAsClient(SslStream stream, string targetHost, Action <Exception> callback)
        {
            try
            {
                stream.BeginAuthenticateAsClient(targetHost, (result) =>
                {
                    try
                    {
                        stream.EndAuthenticateAsClient(result);

                        Loop.Post(() =>
                        {
                            callback(null);
                        });
                    }
                    catch (Exception exception)
                    {
                        Loop.Post(() =>
                        {
                            callback(exception);
                        });
                    }
                }, null);
            }
            catch (Exception exception)
            {
                callback(exception);
            }
        }
Пример #16
0
 private void InitializeSecureStreamAsync(DataCommunicator.State state)
 {
     if (this.dataStream == null)
     {
         return;
     }
     try
     {
         SslStream sslStream = new SslStream(this.dataStream, false, new RemoteCertificateValidationCallback(this.ValidateServerCertificate), null);
         state.DataStream = sslStream;
         this.dataStream  = sslStream;
         this.StartTimer();
         sslStream.BeginAuthenticateAsClient(this.serverName, new AsyncCallback(this.InitializeSecureStreamAsyncCallback), state);
     }
     catch (InvalidOperationException exception)
     {
         this.HandleException(exception);
     }
     catch (IOException ex)
     {
         this.HandleException(new ProtocolException(Strings.ErrorAuthenticationFailed(ex.Message) + Strings.InitializeServerResponse(string.IsNullOrEmpty(state.Response) ? string.Empty : state.Response), ex));
     }
     catch (AuthenticationException innerException)
     {
         this.HandleException(new ProtocolException(Strings.ErrorAuthenticationFailed(this.certificateError) + Strings.InitializeServerResponse(string.IsNullOrEmpty(state.Response) ? string.Empty : state.Response), innerException));
     }
 }
Пример #17
0
        private void EndConnect(IAsyncResult ar)
        {
            object[]   stateObj    = (object[])ar.AsyncState;
            TcpClient  tcpClient   = (TcpClient)stateObj[0];
            IPEndPoint dstEndPoint = (IPEndPoint)stateObj[1];

            byte[] buffer   = (byte[])stateObj[2];
            string serverCN = (string)stateObj[3];

            try
            {
                m_connectingSockets.Remove(dstEndPoint.ToString());

                tcpClient.EndConnect(ar);

                SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                //DisplayCertificateInformation(sslStream);

                SIPConnection callerConnection = new SIPConnection(this, tcpClient, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
                sslStream.BeginAuthenticateAsClient(serverCN, EndAuthenticateAsClient, new object[] { tcpClient, dstEndPoint, buffer, callerConnection });
                //sslStream.AuthenticateAsClient(serverCN);

                //if (tcpClient != null && tcpClient.Connected)
                //{
                //    SIPConnection callerConnection = new SIPConnection(this, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
                //    m_connectedSockets.Add(dstEndPoint.ToString(), callerConnection);

                //    callerConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
                //    callerConnection.SIPMessageReceived += SIPTLSMessageReceived;
                //    //byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
                //    callerConnection.SIPStream.BeginRead(callerConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), callerConnection);

                //    logger.Debug("Established TLS connection to " + dstEndPoint + ".");

                //    callerConnection.SIPStream.BeginWrite(buffer, 0, buffer.Length, EndSend, callerConnection);
                //}
                //else
                //{
                //    logger.Warn("Could not establish TLS connection to " + dstEndPoint + ".");
                //}
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPTLSChannel EndConnect. " + excp);

                if (tcpClient != null)
                {
                    try
                    {
                        tcpClient.Close();
                    }
                    catch (Exception closeExcp)
                    {
                        logger.Warn("Exception SIPTLSChannel EndConnect Close TCP Client. " + closeExcp);
                    }
                }
            }
        }
 protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
 {
     using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
     {
         Task t1 = Task.Factory.FromAsync(clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null), clientSslStream.EndAuthenticateAsClient);
         Task t2 = Task.Factory.FromAsync(serverSslStream.BeginAuthenticateAsServer(certificate, null, null), serverSslStream.EndAuthenticateAsServer);
         await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
     }
 }
Пример #19
0
        /// <summary>
        /// Extends BeginAuthenticateAsClient so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// sslstream.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsClient(this SslStream sslstream, String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation, AsyncCallback asyncCallback)
        {
            if (sslstream == null)
            {
                throw new ArgumentNullException("sslstream");
            }

            return(sslstream.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, asyncCallback, null));
        }
Пример #20
0
        /// <summary>
        /// Extends BeginAuthenticateAsClient so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// sslstream.BeginAuthenticateAsClient(targetHost, asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsClient(this SslStream sslstream, String targetHost, AsyncCallback asyncCallback)
        {
            if (sslstream == null)
            {
                throw new ArgumentNullException("sslstream");
            }

            return(sslstream.BeginAuthenticateAsClient(targetHost, asyncCallback, null));
        }
Пример #21
0
        public void TestNetworkStream()
        {
            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2021);

            var resetEvent = new AutoResetEvent(false);

            var args = new SocketAsyncEventArgs();

            args.RemoteEndPoint = serverAddress;
            args.Completed     += (sender, e) =>
            {
                resetEvent.Set();
            };

            Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);

            resetEvent.WaitOne();

            var encoding = new UTF8Encoding();

            using (Socket socket = args.ConnectSocket)
            {
                var socketStream = new SslStream(new NetworkStream(socket));
                socketStream.BeginAuthenticateAsClient("localhost", new AsyncCallback(r =>
                {
                    resetEvent.Set();
                }), null);

                resetEvent.WaitOne();

                using (var reader = new StreamReader(socketStream, encoding, true))
                    using (var writer = new StreamWriter(socketStream, encoding, 1024 * 8))
                    {
                        string welcomeString = reader.ReadLine();

                        Console.WriteLine("Welcome: " + welcomeString);

                        char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' };

                        Random rd = new Random(1);

                        StringBuilder sb = new StringBuilder();

                        for (int i = 0; i < 50; i++)
                        {
                            sb.Append(chars[rd.Next(0, chars.Length - 1)]);
                            string command = sb.ToString();
                            writer.WriteLine("ECHO " + command);
                            writer.Flush();
                            string echoMessage = reader.ReadLine();
                            Console.WriteLine("C:" + echoMessage);
                            Assert.AreEqual(command, echoMessage);
                        }
                    }
            }
        }
Пример #22
0
 public IAsyncResult BeginAuthenticateAsClient(AsyncCallback?asyncCallback, object?state)
 {
     return(_sslStream.BeginAuthenticateAsClient(
                _host,
                _clientCertificates,
                (SslProtocols)ServicePointManager.SecurityProtocol, // enums use same values
                ServicePointManager.CheckCertificateRevocationList,
                asyncCallback,
                state));
 }
Пример #23
0
        private void Secure(Action success, Action <Exception> error)
        {
            var networkStream = new NetworkStream(_client);

            _clientSslStream = new SslStream(networkStream, false, RemoteCertificateValidationCallback);
            var clientAuthentication = _clientSslStream.BeginAuthenticateAsClient("localhost", null, null);
            var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2("local.pfx", "local");

            _wrapper.Authenticate(cert, RemoteCertificateValidationCallback, success, error);
        }
Пример #24
0
        private Task <bool> ConnectSsl()
        {
            _logger.Verbose("Socket connected, starting SSL client authentication");
            //Stream mode: not the most performant but it has ssl support
            var targetHost = IPEndPoint.Address.ToString();

            //HostNameResolver is a sync operation but it can block
            //Use another thread
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    targetHost = SSLOptions.HostNameResolver(IPEndPoint.Address);
                }
                catch (Exception ex)
                {
                    _logger.Error(String.Format("SSL connection: Can not resolve host name for address {0}. Using the IP address instead of the host name. This may cause RemoteCertificateNameMismatch error during Cassandra host authentication. Note that the Cassandra node SSL certificate's CN(Common Name) must match the Cassandra node hostname.", targetHost), ex);
                }
                return true;
            }).Then(_ =>
            {
                _logger.Verbose("Starting SSL authentication");
                var tcs = TaskHelper.TaskCompletionSourceWithTimeout <bool>(Options.ConnectTimeoutMillis,
                                                                            () => new TimeoutException("The timeout period elapsed prior to completion of SSL authentication operation."));
                var sslStream = new SslStream(new NetworkStream(_socket), false, SSLOptions.RemoteCertValidationCallback, null);
                _socketStream = sslStream;
                try
                {
                    sslStream.BeginAuthenticateAsClient(targetHost, SSLOptions.CertificateCollection, SSLOptions.SslProtocol,
                                                        SSLOptions.CheckCertificateRevocation,
                                                        sslAsyncResult =>
                    {
                        try
                        {
                            sslStream.EndAuthenticateAsClient(sslAsyncResult);
                            tcs.TrySetResult(true);
                        }
                        catch (Exception ex)
                        {
                            tcs.TrySetException(ex);
                        }
                    }, null);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
                return tcs.Task;
            }).ContinueSync(_ =>
            {
                _logger.Verbose("SSL authentication successful");
                ReceiveAsync();
                return true;
            }));
        }
Пример #25
0
            protected override void AuthenticateAsClient(
                SslStream stream, bool waitForCompletion,
                string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
            {
                IAsyncResult iar = stream.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, null, null);

                if (waitForCompletion)
                {
                    stream.EndAuthenticateAsClient(iar);
                }
            }
            private void OnProxyResponseSink(IAsyncResult ar)
            {
                if (wsrawstream == null)
                {
                    return;
                }

                int len = 0;

                try { len = wsrawstream.EndRead(ar); } catch (Exception) { }
                if (len == 0)
                {
                    // Disconnect
                    Debug("Websocket proxy disconnected, length = 0.");
                    Dispose();
                    return;
                }

                readBufferLen += len;
                string proxyResponse = UTF8Encoding.UTF8.GetString(readBuffer, 0, readBufferLen);

                if (proxyResponse.IndexOf("\r\n\r\n") >= 0)
                {
                    // We get a full proxy response, we should get something like "HTTP/1.1 200 Connection established\r\n\r\n"
                    if (proxyResponse.StartsWith("HTTP/1.1 200 "))
                    {
                        // All good, start TLS setup.
                        readBufferLen = 0;
                        Debug("Websocket TCP connected, doing TLS...");
                        wsstream = new SslStream(wsrawstream, false, VerifyServerCertificate, null);
                        wsstream.BeginAuthenticateAsClient(url.Host, null, System.Security.Authentication.SslProtocols.Tls12, false, new AsyncCallback(OnTlsSetupSink), this);
                    }
                    else
                    {
                        // Invalid response
                        Debug("Proxy connection failed: " + proxyResponse);
                        Dispose();
                    }
                }
                else
                {
                    if (readBufferLen == readBuffer.Length)
                    {
                        // Buffer overflow
                        Debug("Proxy connection failed");
                        Dispose();
                    }
                    else
                    {
                        // Read more proxy data
                        wsrawstream.BeginRead(readBuffer, readBufferLen, readBuffer.Length - readBufferLen, new AsyncCallback(OnProxyResponseSink), this);
                    }
                }
            }
Пример #27
0
        // Token: 0x060008B5 RID: 2229 RVA: 0x0001DA6C File Offset: 0x0001BC6C
        protected override void StartAuthenticatedStream(Socket client)
        {
            SecurityOption security = base.Security;

            if (security == null)
            {
                throw new Exception("securityOption was not configured");
            }
            SslStream sslStream = new SslStream(new NetworkStream(client), false, new RemoteCertificateValidationCallback(this.ValidateRemoteCertificate));

            sslStream.BeginAuthenticateAsClient(base.HostName, security.Certificates, security.EnabledSslProtocols, false, new AsyncCallback(this.OnAuthenticated), sslStream);
        }
Пример #28
0
        protected override void StartAuthenticatedStream(Socket client)
        {
            SecurityOption security = base.Security;

            if (security == null)
            {
                throw new Exception("securityOption was not configured");
            }
            SslStream sslStream = new SslStream(new NetworkStream(client), leaveInnerStreamOpen: false, ValidateRemoteCertificate);

            sslStream.BeginAuthenticateAsClient(base.HostName, security.Certificates, security.EnabledSslProtocols, checkCertificateRevocation: false, OnAuthenticated, sslStream);
        }
 protected override void MyOnGetSocket(MySocketAsyncArgs e)
 {
     try {
         var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
         sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
     } catch (Exception exc) {
         if (!IsIgnorableException(exc))
         {
             OnError(exc);
         }
     }
 }
Пример #30
0
        private void ProcessConnect(IAsyncResult ar)
        {
            try {
                _socket.EndConnect(ar);

                if (_secureConnect)
                {
                    string targetAddress = ((IPEndPoint)_socket.RemoteEndPoint).Address.ToString();

                    if (_certificates != null)
                    {
                        _sslStream = new SslStream(new NetworkStream(_socket, true), false, _certValidationCallback);

                        _sslStream.BeginAuthenticateAsClient(targetAddress,
                                                             _certificates, SslProtocols.Tls, false, OnSslAuthenticated, this);
                    }
                    else
                    {
                        _sslStream = new SslStream(new NetworkStream(_socket, true), false, AcceptServerCertificate);

                        _sslStream.BeginAuthenticateAsClient(targetAddress,
                                                             null, SslProtocols.Tls, false, OnSslAuthenticated, this);
                    }
                }
                else
                {
                    _session = new TcpSession(_socket, new NetworkStream(_socket, true));

                    try {
                        if (OnSessionConnected != null)
                        {
                            OnSessionConnected(_session);
                        }
                    } catch (Exception) {
                        // ignored
                    }

                    _session.Start();
                }
            } catch (Exception e) {
                try {
                    if (OnConnectionError != null)
                    {
                        OnConnectionError(e);
                    }
                } catch (Exception) {
                    // ignored
                }

                Close();
            }
        }
        protected override void OnGetSocket(SocketAsyncEventArgs e)
        {
            try
            {
#if !SILVERLIGHT
                var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
#else
                var sslStream = new SslStream(new NetworkStream(Client));
#endif

                sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
            }
            catch (Exception exc)
            {
                if (!IsIgnorableException(exc))
                    OnError(exc);
            }
        }
Пример #32
0
			public void OnAsyncClientConnect(IAsyncResult ar) {
				try {
					client.EndConnect(ar);
				}
				catch (Exception) {
					Shutdown(false);
				}
				if (testName == "BasicAsyncClientTest") {
					sslStream = new SslStream(client.GetStream(), false);
					sslStream.BeginAuthenticateAsClient("localhost", new AsyncCallback(OnAsyncAuthenticateAsClient), null);
				}
				else if (testName == "IntermediateAsyncClientTest") {
					sslStream = new SslStream(client.GetStream(), false);
					sslStream.BeginAuthenticateAsClient("localhost", null, null, SslProtocols.Tls, SslStrength.Medium | SslStrength.High, false, new AsyncCallback(OnAsyncAuthenticateAsClient), null);
				}
				else if (testName == "AdvancedAsyncClientTest") {
					sslStream = new SslStream(client.GetStream(), false, clientRemoteCertificateValidationCallback, clientLocalCertificateSelectionCallback);
					sslStream.BeginAuthenticateAsClient("localhost", testServer.clientCertificateList, testServer.clientCAChain, SslProtocols.Tls, SslStrength.Medium | SslStrength.High, true, new AsyncCallback(OnAsyncAuthenticateAsClient), null);
				}
			}
 protected override void AuthenticateAsClient(
     SslStream stream, bool waitForCompletion,
     string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     IAsyncResult iar = stream.BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, null, null);
     if (waitForCompletion)
     {
         stream.EndAuthenticateAsClient(iar);
     }
 }
        private void ClientAsyncSslHelper(EncryptionPolicy encryptionPolicy, SslProtocols clientSslProtocols,
            SslProtocols serverSslProtocols)
        {
            _log.WriteLine("Server: " + serverSslProtocols + "; Client: " + clientSslProtocols);

            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);

            using (var server = new DummyTcpServer(endPoint, encryptionPolicy))
            using (var client = new TcpClient(AddressFamily.InterNetworkV6))
            {
                server.SslProtocols = serverSslProtocols;
                client.Connect(server.RemoteEndPoint);
                using (SslStream sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
                {
                    IAsyncResult async = sslStream.BeginAuthenticateAsClient("localhost", null, clientSslProtocols, false, null, null);
                    Assert.True(async.AsyncWaitHandle.WaitOne(TestConfiguration.TestTimeoutSeconds * 1000), "Timed Out");
                    sslStream.EndAuthenticateAsClient(async);

                    _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
                        client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
                        sslStream.CipherAlgorithm, sslStream.CipherStrength);
                    Assert.True(sslStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL");
                    Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0");
                }
            }
        }
Пример #35
0
		public void TestAsyncBasic()
		{
			var listener = new TcpListener(IPAddress.Loopback, 0);
			listener.Start(5);
			var ep = (IPEndPoint)listener.LocalEndpoint;

			Console.WriteLine("Server> waiting for accept");

			listener.BeginAcceptTcpClient((IAsyncResult ar) =>
			{
				var client = listener.EndAcceptTcpClient(ar);

				var sslStream = new SslStream(client.GetStream(), false);
				Console.WriteLine("Server> authenticate");

				sslStream.BeginAuthenticateAsServer(_ctx.ServerCertificate, async (ar2) =>
				{
					sslStream.EndAuthenticateAsServer(ar2);

					Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);

					var buf = new byte[256];
					await sslStream.ReadAsync(buf, 0, buf.Length);
					Assert.AreEqual(clientMessage.ToString(), buf.ToString());

					await sslStream.WriteAsync(serverMessage, 0, serverMessage.Length);

					sslStream.Close();
					client.Close();

					Console.WriteLine("Server> done");
				}, null);
			}, null);

			var evtDone = new AutoResetEvent(false);

			var tcp = new TcpClient(AddressFamily.InterNetwork);
			tcp.BeginConnect(ep.Address.ToString(), ep.Port, (IAsyncResult ar) =>
			{
				tcp.EndConnect(ar);

				var sslStream = new SslStream(tcp.GetStream());
				Console.WriteLine("Client> authenticate");

				sslStream.BeginAuthenticateAsClient("localhost", async (ar2) =>
				{
					sslStream.EndAuthenticateAsClient(ar2);

					Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
					Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);

					await sslStream.WriteAsync(clientMessage, 0, clientMessage.Length);

					var buf = new byte[256];
					await sslStream.ReadAsync(buf, 0, buf.Length);
					Assert.AreEqual(serverMessage.ToString(), buf.ToString());

					sslStream.Close();
					tcp.Close();

					Console.WriteLine("Client> done");

					evtDone.Set();
				}, null);
			}, null);

			evtDone.WaitOne();
		}
Пример #36
0
 protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
 {
     using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
     {
         IAsyncResult a1 = clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null);
         IAsyncResult a2 = serverSslStream.BeginAuthenticateAsServer(certificate, null, null);
         if (WaitHandle.WaitAll(new[] { a1.AsyncWaitHandle, a2.AsyncWaitHandle }, TestConfiguration.PassingTestTimeoutMilliseconds))
         {
             clientSslStream.EndAuthenticateAsClient(a1);
             serverSslStream.EndAuthenticateAsServer(a2);
             return true;
         }
         return false;
     }
 }