BeginAuthenticateAsClient() public method

public BeginAuthenticateAsClient ( string targetHost, AsyncCallback asyncCallback, object asyncState ) : IAsyncResult
targetHost string
asyncCallback AsyncCallback
asyncState object
return IAsyncResult
Ejemplo n.º 1
0
        public void ReconTest()
        {
            MonoCatConfig config = new MonoCatConfig()
            {
                Name = "monocat",
                Nick = "monocat",//"monocat" + DateTime.Now.Second,
                Server = "kornbluth.freenode.net",
                Port = 6697,
                Cipher = "blowfish",
                ChannelList = new String[] { "#shrew-dev", "#screenage" }
            };

            TcpClient tcpClient = new TcpClient(config.Server, config.Port);
            SslStream stream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));

            Boolean visited = false;
            var async = stream.BeginAuthenticateAsClient(config.Server, (result) =>
            {
                var s = (SslStream)result.AsyncState;
                s.EndAuthenticateAsClient(result);
                visited = true;
                Trace.TraceInformation("Auth req finished.");
            }, stream);
            Trace.TraceInformation("Sent auth req.");

            Thread.Sleep(1000);
            Assert.IsTrue(stream.IsAuthenticated);
            Assert.IsTrue(stream.IsEncrypted);
            Assert.IsTrue(visited);
        }
        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);
            }
        }
Ejemplo n.º 3
0
        public Task AuthenticateAsClient(X509Certificate2 certificate)
        {
            var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
            {
                if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    return true;
                }

                // if (errors == SslPolicyErrors.None)
                //return true;
                return true;
            }, null);

            var tempStream = new SslStreamWrapper(ssl);
            Stream = tempStream;

            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsClient(this.RemoteIpAddress,
                    new X509Certificate2Collection(certificate),SslProtocols.Tls, false, cb, s);

            var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);
           
            return task;
        }
 protected override void OnGetSocket(SocketAsyncEventArgs e)
 {
     try
     {
         var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
         sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
     }
     catch (Exception exc)
     {
         if (!IsIgnorableException(exc))
             OnError(exc);
     }
 }
 public void New(TcpClient c, bool isOutBound)
 {
     var stream = new SslStream(c.GetStream());
     var remote = ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
     var certs = new X509CertificateCollection();
     var state = new State { Client = c, Stream = stream };
     if (isOutBound)
     {
         certs.Add(clientCertificate);
         stream.BeginAuthenticateAsClient(remote, certs, SslProtocols.Tls, false, EndAuthenticateAsClient, state);
     }
     else
     {
         certs.Add(serverCertificate);
         stream.BeginAuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, false, EndAuthenticateAsServer, state);
     }
 }
Ejemplo n.º 6
0
        public Task AuthenticateAsClient()
        {
            var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
            {
                if (errors == SslPolicyErrors.None)
                    return true;

                return false;
            }, null);

            var tempStream = new SslStreamWrapper(ssl);
            Stream = tempStream;            
            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsClient(this._uri.Host, cb, s);

            var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);

            return task;            
        }
        protected override void OnGetSocket(SocketAsyncEventArgs e)
        {
            try
            {
#if !SILVERLIGHT
                var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
                sslStream.BeginAuthenticateAsClient(HostName, new X509CertificateCollection(), m_EnabledSslProtocols, false, OnAuthenticated, sslStream);
#else
                var sslStream = new SslStream(new NetworkStream(Client));
                sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
#endif


            }
            catch (Exception exc)
            {
                if (!IsIgnorableException(exc))
                    OnError(exc);
            }
        }
Ejemplo n.º 8
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);
			}
		}
        protected void InitializeCryptService(BaseSocketConnection connection)
        { 

          //----- None!
          if (connection.EncryptType == EncryptType.etNone || connection.EncryptType == EncryptType.etBase64)
          {
              FHost.FireOnConnected(connection);
          }

          //----- Symmetric!
          if (connection.EncryptType == EncryptType.etRijndael || connection.EncryptType == EncryptType.etTripleDES)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get RSA provider!
                  RSACryptoServiceProvider serverPublicKey;
                  RSACryptoServiceProvider clientPrivateKey = new RSACryptoServiceProvider();
                  byte[] signMessage;

                  FCryptoService.OnSymmetricAuthenticate(connection, out serverPublicKey, out signMessage);

                  //----- Generates symmetric algoritm!
                  SymmetricAlgorithm sa = CryptUtils.CreateSymmetricAlgoritm(connection.EncryptType);
                  sa.GenerateIV();
                  sa.GenerateKey();

                  //----- Adjust connection cryptors!
                  connection.Encryptor = sa.CreateEncryptor();
                  connection.Decryptor = sa.CreateDecryptor();

                  //----- Create authenticate structure!
                  AuthMessage am = new AuthMessage();
                  am.SessionIV = serverPublicKey.Encrypt(sa.IV, false);
                  am.SessionKey = serverPublicKey.Encrypt(sa.Key, false);
                  am.SourceKey = CryptUtils.EncryptDataForAuthenticate(sa, Encoding.UTF8.GetBytes(clientPrivateKey.ToXmlString(false)), PaddingMode.ISO10126);

                  //----- Sign message with am.SourceKey, am.SessionKey and signMessage!
                  //----- Need to use PaddingMode.PKCS7 in sign!
                  MemoryStream m = new MemoryStream();
                  m.Write(am.SourceKey, 0, am.SourceKey.Length);
                  m.Write(am.SessionKey, 0, am.SessionKey.Length);
                  m.Write(signMessage, 0, signMessage.Length);
                  
                  am.Sign = clientPrivateKey.SignData(CryptUtils.EncryptDataForAuthenticate(sa, m.ToArray(), PaddingMode.PKCS7), new SHA1CryptoServiceProvider());

                  //----- Serialize authentication message!
                  XmlSerializer xml = new XmlSerializer(typeof(AuthMessage));
                  m.SetLength(0);
                  xml.Serialize(m, am);

                  //----- Send structure!
                  MessageBuffer mb = new MessageBuffer(0);
                  mb.PacketBuffer = Encoding.GetEncoding(1252).GetBytes(Convert.ToBase64String(m.ToArray()));
                  connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionSendCallback), new CallbackData(connection, mb));

                  m.Close();
                  am.SessionIV.Initialize();
                  am.SessionKey.Initialize();
                  serverPublicKey.Clear();
                  clientPrivateKey.Clear();

              }
              else
              {

                  //----- Create empty authenticate structure!
                  MessageBuffer mb = new MessageBuffer(8192);

                  //----- Start receive structure!
                  connection.Socket.BeginReceive(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionReceiveCallback), new CallbackData(connection, mb));

              }

          }

          //----- Asymmetric!
          if (connection.EncryptType == EncryptType.etSSL)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get SSL items!
                  X509Certificate2Collection certs = null;
                  string serverName = null;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket), true, new RemoteCertificateValidationCallback(ValidateServerCertificateCallback)); 

                  if (certs == null)
                  {
                      ssl.BeginAuthenticateAsClient(serverName, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
                  }
                  else
                  {
                      ssl.BeginAuthenticateAsClient(serverName, certs, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));

                  }

              }
              else
              {

                  //----- Get SSL items!
                  X509Certificate2 cert = null;
                  bool clientAuthenticate = false;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket));
                  ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));

              }

          }

        }
Ejemplo n.º 10
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;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Starts the TLS procedure ONLY if it's the correct time to do so.
        /// This is dependent on several variables, such as the kPause flags, connected property, etc.
        /// 
        /// This method is NOT thread safe, and should only be invoked via thread safe methods.
        /// </summary>
        private void MaybeStartTLS()
        {
            Debug.Assert(socketStream != null, "Attempting to start tls without a connected socket");
            Trace.Assert(secureSocketStream == null, "Attempting to start tls after tls has already completed");

            // We can't start TLS until:
            // - Any queued reads prior to the user calling StartTLS are complete
            // - Any queued writes prior to the user calling StartTLS are complete

            if (((flags & kPauseReads) > 0) && ((flags & kPauseWrites) > 0))
            {
                try
                {
                    secureSocketStream = new SslStream(socketStream, true, tlsRemoteCallback, tlsLocalCallback);

                    if (isTLSClient)
                    {
                        secureSocketStream.BeginAuthenticateAsClient(tlsServerName,
                                                   new AsyncCallback(secureSocketStream_DidFinish), null);
                    }
                    else
                    {
                        secureSocketStream.BeginAuthenticateAsServer(localCertificate,
                                                   new AsyncCallback(secureSocketStream_DidFinish), null);
                    }
                }
                catch (Exception e)
                {
                    // The most likely cause of this exception is a null tlsServerName.
                    CloseWithException(e);
                }
            }
        }
Ejemplo n.º 12
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);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private bool beginAuthenticate(IceInternal.AsyncCallback callback, object state)
        {
            NetworkStream ns = new NetworkStream(_fd, true);
            _stream = new SslStream(ns, false, new RemoteCertificateValidationCallback(validationCallback), null);

            try
            {
                if(_adapterName == null)
                {
                    //
                    // Client authentication.
                    //
                    _writeResult = _stream.BeginAuthenticateAsClient(_host, _instance.certs(),
                                                                     _instance.protocols(),
                                                                     _instance.checkCRL() > 0,
                                                                     delegate(IAsyncResult result)
                                                                     {
                                                                         if(!result.CompletedSynchronously)
                                                                         {
                                                                             callback(result.AsyncState);
                                                                         }
                                                                     }, state);
                }
                else
                {
                    //
                    // Server authentication.
                    //
                    // Get the certificate collection and select the first one.
                    //
                    X509Certificate2Collection certs = _instance.certs();
                    X509Certificate2 cert = null;
                    if(certs.Count > 0)
                    {
                        cert = certs[0];
                    }

                    _writeResult = _stream.BeginAuthenticateAsServer(cert, _verifyPeer > 1, _instance.protocols(),
                                                                     _instance.checkCRL() > 0, 
                                                                     delegate(IAsyncResult result)
                                                                     {
                                                                         if(!result.CompletedSynchronously)
                                                                         {
                                                                             callback(result.AsyncState);
                                                                         }
                                                                     }, state);
                }
            }
            catch(IOException ex)
            {
                if(IceInternal.Network.connectionLost(ex))
                {
                    //
                    // This situation occurs when connectToSelf is called; the "remote" end
                    // closes the socket immediately.
                    //
                    throw new Ice.ConnectionLostException();
                }
                throw new Ice.SocketException(ex);
            }
            catch(AuthenticationException ex)
            {
                Ice.SecurityException e = new Ice.SecurityException(ex);
                e.reason = ex.Message;
                throw e;
            }
            catch(Exception ex)
            {
                throw new Ice.SyscallException(ex);
            }

            Debug.Assert(_writeResult != null);
            return _writeResult.CompletedSynchronously;
        }
Ejemplo n.º 14
0
        private void ConnectCallback( IAsyncResult ar )
        {
            bool retry = false;
            try {
                TcpClient.EndConnect( ar );
            }
            catch ( SocketException e ) {
                Debug.Print( "ServerConnector.ConnectCallback: TcpClient.EndConnect: caught SocketException, error code {0}:\n{1}", e.ErrorCode, e );
                OnConnectionAttemptFailed( CurrentEndPoint, e );
                retry = true;
            }
            catch ( Exception e ) {
                Debug.Print( "ServerConnector.ConnectCallback: TcpClient.EndConnect: caught exception:\n{0}", e );
                OnConnectionAttemptFailed( CurrentEndPoint, e );
                retry = true;
            }

            if ( retry ) {
                TryEstablishConnection( );
                return;
            }

            EndPointEnumerator.Dispose( );
            EndPoints = null;

            Debug.Print( "ServerConnector.ConnectCallback: Connected!" );
            SocketRegistry.Register( TcpClient.Client.LocalEndPoint as IPEndPoint, TcpClient.Client.RemoteEndPoint as IPEndPoint );

            Debug.Print( "ServerConnector.ConnectCallback: Constructing objects." );

            var selfUser = new SelfUser {
                NickName = Configuration.NickName,
                HostName = Configuration.LocalHostName,
                RealHostName = Configuration.LocalHostName,
                RealName = Configuration.RealName,
                UserName = Configuration.UserName,
                NickServUserName = Configuration.NickServUserName,
                NickServPassword = Configuration.NickServPassword,
            };

            _server = new Server {
                ServerEndPoint = CurrentEndPoint,
                SelfUser = selfUser,
                ServerHostName = Configuration.ServerHostName,
                ServerPassword = Configuration.Password,
            };
            _protocolHandler = new ProtocolHandler {
                TcpClient = TcpClient,
                SelfUser = selfUser,
                Server = _server,
            };
            _server.ProtocolHandler = _protocolHandler;

            selfUser.Server = _server;

            if ( CurrentEndPoint.UseSsl ) {
                Debug.Print( "ServerConnector.ConnectCallback: Starting SSL." );
                _sslStream = new SslStream( TcpClient.GetStream( ), true, ServerCertificateValidationCallback, LocalCertificateSelectionCallback, EncryptionPolicy.RequireEncryption );
                try {
                    _sslStream.BeginAuthenticateAsClient( Configuration.ServerHostName, CertificateCollection, SslProtocols.Default, true, AuthenticateAsClientCallback, null );
                }
                catch ( Exception e ) {
                    Debug.Print( "ServerConnector.ConnectCallback: Caught exception calling BeginAuthenticateAsClient:\n{0}", e );
                    throw;
                }
            } else {
                FinishConnection( TcpClient.GetStream( ) );
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes the connection
        /// </summary>
        /// <param name="connection"></param>
        internal void OnConnected(BaseSocketConnection connection)
        {
            if (Disposed || !connection.Active)
                return;

            try
            {
                switch (connection.Context.EventProcessing)
                {
                    case EventProcessing.epEncrypt:

                        switch (connection.Context.Creator.Context.EncryptType)
                        {
                            case EncryptType.etRijndael:

                                if (connection.Context.Host.Context.HostType == HostType.htClient)
                                {

                                    ISocketSecurityProvider socketSecurityProvider = new SocketRSACryptoProvider(connection, null);
                                    MemoryStream m = socketSecurityProvider.EcryptForClient();
                                    connection.BeginSend(m.ToArray());

                                }
                                else
                                {

                                    connection.BeginReceive();

                                }

                                break;

                            case EncryptType.etSSL:

                                if (connection.Context.Host.Context.HostType == HostType.htClient)
                                {

                                    //----- Get SSL items
                                    X509Certificate2Collection certs = null;
                                    string serverName = null;
                                    bool checkRevocation = true;

                                    connection.Context.Creator.Context.CryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);

                                    //----- Authenticate SSL!
                                    SslStream ssl = new SslStream(new NetworkStream(connection.Context.SocketHandle), true, new RemoteCertificateValidationCallback(connection.Context.Creator.ValidateServerCertificateCallback));

                                    if (certs == null)
                                    {
                                        ssl.BeginAuthenticateAsClient(serverName, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
                                    }
                                    else
                                    {
                                        ssl.BeginAuthenticateAsClient(serverName, certs, System.Security.Authentication.SslProtocols.Tls, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
                                    }

                                }
                                else
                                {

                                    //----- Get SSL items!
                                    X509Certificate2 cert = null;
                                    bool clientAuthenticate = false;
                                    bool checkRevocation = true;

                                    connection.Context.Creator.Context.CryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);

                                    //----- Authneticate SSL!
                                    SslStream ssl = new SslStream(new NetworkStream(connection.Context.SocketHandle));
                                    ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));

                                }

                                break;
                        }

                        break;

                    case EventProcessing.epProxy:

                        ProxyInfo proxyInfo = ((SocketConnector)connection.Context.Creator).ProxyInfo;
                        IPEndPoint endPoint = ((SocketConnector)connection.Context.Creator).Context.RemotEndPoint;
                        byte[] proxyBuffer = ProxyUtils.GetProxyRequestData(proxyInfo, endPoint);

                        connection.BeginSend(proxyBuffer);

                        break;
                }
            }
            catch (Exception ex)
            {
                FireOnException(connection, ex);
            }
        }
Ejemplo n.º 16
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner TCP client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(TCP_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pTcpClient = owner;

                SetState(AsyncOP_State.Active);

                try{
                    m_pSslStream = new SslStream(m_pTcpClient.m_pTcpStream.SourceStream,false,this.RemoteCertificateValidationCallback);
                    m_pSslStream.BeginAuthenticateAsClient("dummy",this.BeginAuthenticateAsClientCompleted,null);                  
                }
                catch(Exception x){
                    m_pException = x;
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Ejemplo n.º 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, 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);
                    }
                }
            }
        }
Ejemplo n.º 18
0
        private Stream NegotiateStream(Stream stream)
        {
            if (!_sslEnabled)
                return stream;

            var validateRemoteCertificate = new RemoteCertificateValidationCallback(
                (object sender,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
                =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                        return true;

                    if (_configuration.SslPolicyErrorsBypassed)
                        return true;
                    else
                        _log(string.Format("Error occurred when validating remote certificate: [{0}], [{1}].",
                            this.RemoteEndPoint, sslPolicyErrors));

                    return false;
                });

            var sslStream = new SslStream(
                stream,
                false,
                validateRemoteCertificate,
                null);

            IAsyncResult ar = null;
            if (_configuration.SslClientCertificates == null || _configuration.SslClientCertificates.Count == 0)
            {
                ar = sslStream.BeginAuthenticateAsClient( // No client certificates are used in the authentication. The certificate revocation list is not checked during authentication.
                    _configuration.SslTargetHost, // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
                    null, _tcpClient);
            }
            else
            {
                ar = sslStream.BeginAuthenticateAsClient(
                    _configuration.SslTargetHost, // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
                    _configuration.SslClientCertificates, // The X509CertificateCollection that contains client certificates.
                    _configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
                    _configuration.SslCheckCertificateRevocation, // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
                    null, _tcpClient);
            }
            if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
            {
                Close(WebSocketCloseCode.TlsHandshakeFailed, "SSL/TLS handshake timeout.");
                throw new TimeoutException(string.Format(
                    "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
            }
            sslStream.EndAuthenticateAsClient(ar);

            // When authentication succeeds, you must check the IsEncrypted and IsSigned properties 
            // to determine what security services are used by the SslStream. 
            // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
            _log(string.Format(
                "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
                + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
                sslStream.SslProtocol,
                sslStream.IsServer,
                sslStream.IsAuthenticated,
                sslStream.IsEncrypted,
                sslStream.IsSigned,
                sslStream.IsMutuallyAuthenticated,
                sslStream.HashAlgorithm,
                sslStream.HashStrength,
                sslStream.KeyExchangeAlgorithm,
                sslStream.KeyExchangeStrength,
                sslStream.CipherAlgorithm,
                sslStream.CipherStrength));

            return sslStream;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Runs when a successful TCP connection has been made.
        /// </summary>
        protected override void HandleTcpClientConnectionSuccess()
        {
            Sstream = new SslStream(Nstream, false, ValidateServerCertificate, null);

            try
            {
                Sstream.BeginAuthenticateAsClient(srvName, FinishClientAuthentication, null);
            }
            catch (Exception x)
            {
                OnAuthFailed(new ClientAuthFailedEventArgs(x));

                _CheckIfStopped(x, true);
            }
        }
Ejemplo n.º 20
0
        public void Connect(string user, string password, Region region, string clientVersion)
        {
            if (!isConnected)
            {
                Thread t = new Thread(() =>
                {
                    this.user = user;
                    this.password = password;
                    this.clientVersion = clientVersion;
                    //this.server = "127.0.0.1";
                    this.server = RegionInfo.GetServerValue(region);
                    this.loginQueue = RegionInfo.GetLoginQueueValue(region);
                    this.locale = RegionInfo.GetLocaleValue(region);
                    this.useGarena = RegionInfo.GetUseGarenaValue(region);

                    //Sets up our sslStream to riots servers
                    try
                    {
                        client = new TcpClient(server, 2099);
                    }
                    catch
                    {
                        Error("Riots servers are currently unavailable.", ErrorType.AuthKey);
                        Disconnect();
                        return;
                    }

                    //Check for riot webserver status
                    //along with gettin out Auth Key that we need for the login process.
                    if (useGarena)
                        if (!GetGarenaToken())
                            return;

                    if (!GetAuthKey())
                        return;

                    if (!GetIpAddress())
                        return;

                    sslStream = new SslStream(client.GetStream(), false, AcceptAllCertificates);
                    var ar = sslStream.BeginAuthenticateAsClient(server, null, null);
                    using (ar.AsyncWaitHandle)
                    {
                        if (ar.AsyncWaitHandle.WaitOne(-1))
                        {
                            sslStream.EndAuthenticateAsClient(ar);
                        }
                    }

                    if (!Handshake())
                        return;

                    BeginReceive();

                    if (!SendConnect())
                        return;

                    if (!Login())
                        return;

                    //StartHeartbeat();
                });
                t.IsBackground = true;
                t.Start();
            }
        }
Ejemplo n.º 21
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 = new TaskCompletionSource<bool>();
         var sslStream = new SslStream(new NetworkStream(_socket), false, SSLOptions.RemoteCertValidationCallback, null);
         _socketStream = sslStream;
         sslStream.BeginAuthenticateAsClient(targetHost, SSLOptions.CertificateCollection, SSLOptions.SslProtocol, SSLOptions.CheckCertificateRevocation, 
             sslAsyncResult =>
             {
                 try
                 {
                     sslStream.EndAuthenticateAsClient(sslAsyncResult);
                     tcs.TrySetResult(true);
                 }
                 catch (Exception ex)
                 {
                     tcs.TrySetException(ex);
                 }
             }, null);
         return tcs.Task;
     }).ContinueSync(_ =>
     {
         _logger.Verbose("SSL authentication successful");
         ReceiveAsync();
         return true;
     });
 }
Ejemplo n.º 22
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;

            using (_streamLock.Acquire())
            {
                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);
                }
            }
        }
Ejemplo n.º 23
0
        void connectHandler(IAsyncResult ar)
        {
            if (_closing || _disposed)
                return;

            try
            {
                _client.EndConnect(ar);
            }
            catch (SocketException ex)
            {
                shutdown("Faild connect to remote(" + ex.Message +  ")");
                return;
            }

            StringBuilder request = new StringBuilder();

            request.Append("GET / HTTP/1.1\r\n");
            request.Append("Connection: Upgrade\r\n");
            request.Append("Upgrade: " +  protocolVersion + "\r\n");
            request.Append("Host: " + ((Uri)ar.AsyncState).Host + "\r\n");
            request.Append("\r\n");

            byte[] data = Encoding.ASCII.GetBytes(request.ToString());

            Uri uri = (Uri)ar.AsyncState;

            if (uri.Scheme == "https") {
                SslStream sslStream = new SslStream(_client.GetStream(),
                                                    false,
                                                    _certCallback,
                                                    null);

                _stream = sslStream;

                AsyncCallback callback = new AsyncCallback(authHandler);
                sslStream.BeginAuthenticateAsClient(uri.Host,
                                                    callback,
                                                    data);
                return;
            }


            _stream = _client.GetStream();

            _stream.BeginWrite(data,
                               0,
                               data.Length,
                               new AsyncCallback(handshakeSendHandler),
                               null);
        }
Ejemplo n.º 24
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);
 }
Ejemplo n.º 25
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner TCP client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(TCP_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pTcpClient = owner;

                try{
                    m_pSslStream = new SslStream(m_pTcpClient.m_pTcpStream.SourceStream,false,this.RemoteCertificateValidationCallback);
                    m_pSslStream.BeginAuthenticateAsClient("dummy",this.BeginAuthenticateAsClientCompleted,null);                  
                }
                catch(Exception x){
                    m_pException = x;
                    SetState(AsyncOP_State.Completed);
                }

                // NOTE: If operation completed synchronously, then this.State is AsyncOP_State.Completed and we don't have pending operation.
                return this.State != AsyncOP_State.Completed;
            }
Ejemplo n.º 26
0
        internal void Run()
        {
            tcpClient = new TcpClient(config.Server, config.Port);
            stream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            stream.BeginAuthenticateAsClient(config.Server, new AsyncCallback(ProcessAuthenticate), this);

            // AsyncCallback(ProcessAuthenticate) will pick up work after SSL auth :)

            // now bring up the console for good .. everything else will happen async in the background
            while (keepRunning)
            {
                var command = Console.ReadLine();
                if (command == "quit")
                    break;
                if (command.StartsWith(".leadmerge"))
                {
                    new Command.CommandLeadMerge(this, command).Run();
                }
                else if (command.StartsWith(".leadcorrect"))
                {
                    new Command.CommandLeadCorrect(this, command).Run();
                }
                else
                {
                    send(command + "\r\n");
                }
            }

            try { stream.Close(); tcpClient.Close(); }
            catch { }
        }
Ejemplo n.º 27
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);
     }
 }