BeginAuthenticateAsServer() 공개 메소드

public BeginAuthenticateAsServer ( X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState ) : IAsyncResult
serverCertificate System.Security.Cryptography.X509Certificates.X509Certificate
asyncCallback AsyncCallback
asyncState object
리턴 IAsyncResult
        public void assign_without_subscribing_on_MessageReceived_means_that_messages_can_get_lost()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = Substitute.For<IMessageEncoder>();
            var decoder = Substitute.For<IMessageDecoder>();
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut = CreateClientChannel(slice, encoder, decoder);
            Action actual = () => sut.Assign(_helper.Client);

            actual.ShouldThrow<InvalidOperationException>();
        }
        public void Assign_should_work_after_subscription()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = Substitute.For<IMessageEncoder>();
            var decoder = Substitute.For<IMessageDecoder>();
            object expected;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            sut.Assign(_helper.Client);

        }
예제 #3
0
        public Task Authenticate(X509Certificate2 certificate, SslProtocols enabledSslProtocols, Action callback, Action<Exception> error)
        {
            var ssl = new SslStream(_stream, false);
            _stream = new QueuedStream(ssl);
            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, enabledSslProtocols, false, cb, s);
                
            Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null);
            task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
                .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
            task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

            return task;
        }
        public void should_listen_on_the_decoder_event()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = Substitute.For<IMessageEncoder>();
            var decoder = new FakeDecoder();
            object expected = null;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            decoder.MessageReceived("Hello");

            expected.Should().Be("Hello");
        }
 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);
     }
 }
예제 #6
0
파일: Client.cs 프로젝트: vercas/vProto
        internal Client(BaseServer server, TcpClient client, X509Certificate certificate)
            : base(server)
        {
            this.client = client;
            Nstream = client.GetStream();

            cert = certificate;

            Sstream = new SslStream(Nstream, false);

            try
            {
                Sstream.BeginAuthenticateAsServer(certificate, false, SslProtocols.Default, true, FinishServerAuthentication, null);
            }
            catch (Exception x)
            {
                OnAuthFailed(new ClientAuthFailedEventArgs(x));

                _CheckIfStopped(x, true);
            }
        }
예제 #7
0
        private void InitServerSocket(Socket socket, X509Certificate certificate, bool verbose)
        {
            Ensure.NotNull(certificate, "certificate");

            InitConnectionBase(socket);
            if (verbose) Console.WriteLine("TcpConnectionSsl::InitClientSocket({0}, L{1})", RemoteEndPoint, LocalEndPoint);

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

                _sslStream = new SslStream(new NetworkStream(socket, true), false);
                try
                {
                    _sslStream.BeginAuthenticateAsServer(certificate, false, SslProtocols.Default, true, OnEndAuthenticateAsServer, _sslStream);
                }
                catch (AuthenticationException exc)
                {
                    Log.InfoException(exc, "[S{0}, L{1}]: Authentication exception on BeginAuthenticateAsServer.", RemoteEndPoint, LocalEndPoint);
                    CloseInternal(SocketError.SocketError, exc.Message);
                }
                catch (ObjectDisposedException)
                {
                    CloseInternal(SocketError.SocketError, "SslStream disposed.");
                }
                catch (Exception exc)
                {
                    Log.InfoException(exc, "[S{0}, L{1}]: Exception on BeginAuthenticateAsServer.", RemoteEndPoint, LocalEndPoint);
                    CloseInternal(SocketError.SocketError, exc.Message);
                }
            }
        }
        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));

              }

          }

        }
예제 #9
0
 public void BeginAuthenticationAsServer(X509Certificate2 certificate, SslProtocols protocols, AsyncCallback callback, object state)
 {
     SslStream sslStream = new SslStream(Stream, false);
     Stream = sslStream;
     sslStream.BeginAuthenticateAsServer(certificate, false, protocols, false, callback, state);
 }
예제 #10
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);
                }
            }
        }
        public void send_message()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = new StringEncoder();
            var decoder = new StringDecoder();
            object expected = null;

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => expected = message;
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);
            sut.Send("Hello world");

            var buf = new byte[65535];
            var tmp = stream.Read(buf, 0, 65535);
            var actual = Encoding.ASCII.GetString(buf, 4, tmp-4); // string encoder have a length header.
            actual.Should().Be("Hello world");
        }
예제 #12
0
            public connectionHandler(Socket socket, HttpServer server, bool secure)
            {
                Socket = socket;

                _requestId = Rnd.Next();
                _requestStart = DateTime.UtcNow;
                _server = server;
                _secure = secure;

                _server.Log.Info(4, "{0:X8} Incoming connection from {1}".Fmt(_requestId, socket.RemoteEndPoint));

                _buffer = new byte[1024];
                _bufferDataOffset = 0;
                _bufferDataLength = 0;

                _headersSoFar = "";

                lock (server._activeConnectionHandlers)
                    server._activeConnectionHandlers.Add(this);

                var stream = new NetworkStream(socket, ownsSocket: true);
                if (_secure)
                {
                    var secureStream = new SslStream(stream);
                    _stream = secureStream;
                    secureStream.BeginAuthenticateAsServer(new X509Certificate2(server.Options.CertificatePath, server.Options.CertificatePassword), false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true, ar =>
                    {
                        try
                        {
                            secureStream.EndAuthenticateAsServer(ar);
                        }
                        catch (Exception e)
                        {
                            Socket.Close();
                            cleanupIfDone();
                            if (_server.ResponseExceptionHandler != null)
                                _server.ResponseExceptionHandler(null, e, null);
                            return;
                        }
                        receiveMoreHeaderData();
                    }, null);
                }
                else
                {
                    _stream = stream;
                    receiveMoreHeaderData();
                }
            }
예제 #13
0
        private void AcceptConnections(string threadName)
        {
            try
            {
                Thread.CurrentThread.Name = threadName;

                logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " accept connections thread started.");

                while (!Closed)
                {
                    try
                    {
                        TcpClient tcpClient = m_tlsServerListener.AcceptTcpClient();
                        tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                        IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
                        logger.Debug("SIP TLS Channel connection accepted from " + remoteEndPoint + ".");

                        SslStream sslStream = new SslStream(tcpClient.GetStream(), false);

                        SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);

                        sslStream.BeginAuthenticateAsServer(m_serverCertificate, EndAuthenticateAsServer, sipTLSConnection);

                        //sslStream.AuthenticateAsServer(m_serverCertificate, false, SslProtocols.Tls, false);
                        //// Display the properties and settings for the authenticated stream.
                        ////DisplaySecurityLevel(sslStream);
                        ////DisplaySecurityServices(sslStream);
                        ////DisplayCertificateInformation(sslStream);
                        ////DisplayStreamProperties(sslStream);

                        //// Set timeouts for the read and write to 5 seconds.
                        //sslStream.ReadTimeout = 5000;
                        //sslStream.WriteTimeout = 5000;

                        ////SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
                        //m_connectedSockets.Add(remoteEndPoint.ToString(), sipTLSConnection);

                        //sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
                        //sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
                        ////byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
                        //sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
                    }
                    catch (Exception e)
                    {
                        logger.Error("SIPTLSChannel Accept Connection Exception. " + e);
                        //sslStream.Close();
                        //tcpClient.Close();
                    }
                }

                logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening halted.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPTLSChannel Listen. " + excp);
                //throw excp;
            }
        }
예제 #14
0
        void ProcessConnection(Socket listener, IAsyncResult ar)
        {
            Socket ns = listener.EndAccept (ar);
            ns.NoDelay = true;
            SslStream ssl = new SslStream (new NetworkStream (ns, true));

            ssl.BeginAuthenticateAsServer (cert, (IAsyncResult ar2) => {
                try {
                    ssl.EndAuthenticateAsServer (ar2);
                    Protocol p = new Protocol ();
                    p.OnMessage += (incoming) => {
                        var hdr = incoming.Header;
                        // TODO timeout handling
                        if (hdr ["type"].AsString(null) != "request") {
                            Logger.LogError ("received non-request");
                            incoming.Discard ();
                            return;
                        }
                        if (!hdr.ContainsKey ("request_id")) {
                            Logger.LogError ("Received request with no request_id");
                            incoming.Discard ();
                            return;
                        }
                        var id = hdr ["request_id"];
                        reqh (incoming, (reply) => {
                            reply.Header ["type"] = "reply";
                            reply.Header ["request_id"] = id;
                            p.SendMessage (reply);
                        });
                    };
                    p.OnClose += (error) => {
                        Logger.LogInfo ("scamp connection closed: {0}", error);
                    };
                    p.Start (ssl);
                } catch (Exception ex) {
                    Logger.LogError ("connection server authenticate: {0}", ex);
                }
            }, null);
        }
예제 #15
0
        private Stream NegotiateStream(Stream stream)
        {
            if (!_configuration.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.ErrorFormat("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].",
                            this, this.RemoteEndPoint, sslPolicyErrors);

                    return false;
                });

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

            var ar = sslStream.BeginAuthenticateAsServer(
                _configuration.SslServerCertificate, // The X509Certificate used to authenticate the server.
                _configuration.SslClientCertificateRequired, // A Boolean value that specifies whether the client must supply a certificate for authentication.
                _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();
                throw new TimeoutException(string.Format(
                    "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
            }

            // 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.DebugFormat(
                "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;
        }
        internal IAsyncResult BeginUpgradeToSSL(X509Certificate2 cert, bool requiresClientCert)
        {
            m_ssl = new SslStream(m_ns, true);

            return m_ssl.BeginAuthenticateAsServer(cert, requiresClientCert, System.Security.Authentication.SslProtocols.Tls, true, null, null);
        }
예제 #17
0
        public Task Authenticate(X509Certificate2 certificate)
        {
            var ssl = new SslStream(_stream, false);
            _stream = ssl;
            Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) =>
            {
                return ssl.BeginAuthenticateAsServer(certificate, false, SslProtocols.Tls, false, cb, s);
            };

            return Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null);
        }
예제 #18
0
파일: Server.cs 프로젝트: shz/pointy
        // These are just a bit too big to use as inline delegates
        void AcceptCallback(object sender, SocketAsyncEventArgs args)
        {
            // If there was an error, just bail out now and save ourselves the trouble
            if (args.SocketError != SocketError.Success) return;

            // Disable Nagle algorithm, which works around an issue where
            // we get up to a 200ms delay in some cases (delayed ACK).
            //args.AcceptSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            args.AcceptSocket.NoDelay = true;

            // Create the client
            NetworkStream client = new NetworkStream(args.AcceptSocket, true);

            // Non SSL servers can start handling data right away
            if (Certificate == null)
            {
                // Do the bootstrap
                AddClient(args.AcceptSocket, client);
            }
            // SSL servers need to authenticate first
            else
            {
                SslStream sslClient = new SslStream(client, false);
                sslClient.BeginAuthenticateAsServer(Certificate,
                    false,
                    System.Security.Authentication.SslProtocols.Tls,
                    false,
                    SSLAuthCallback,
                    sslClient);
            }

            // Listen for another connection
            args.AcceptSocket = null;
            var sock = args.UserToken as Socket;
            if (Disposed == 0)
                if (!sock.AcceptAsync(args))
                    AcceptCallback(sock, args);
        }
예제 #19
0
 void Authenticate()
 {
     sslStream = new SslStream(tcpClient.GetStream());
     sslStream.BeginAuthenticateAsServer(certificate, AuthenticateCallback, null);
 }
예제 #20
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner TCP session.</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_ServerSession owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pTcpSession = owner;

                SetState(AsyncOP_State.Active);

                try{
                    m_pSslStream = new SslStream(m_pTcpSession.TcpStream.SourceStream,true);
                    m_pSslStream.BeginAuthenticateAsServer(m_pTcpSession.m_pCertificate,this.BeginAuthenticateAsServerCompleted,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;
                }
            }
예제 #21
0
        protected void BeginAuthenticateAsServer(X509Certificate certificate, RemoteCertificateValidationCallback validationCallback, AsyncCallback callback, object asyncState)
        {
            Require.NotNull(certificate, "certificate");

            lock (SyncRoot)
            {
                Debug.Assert(_sslStream == null);
                Debug.Assert(IsAsync);

                _sslStream = new SslStream(_stream, false, validationCallback ?? DummyValidationCallback);

                _stream = null;

                _sslStream.BeginAuthenticateAsServer(
                    certificate,
                    false /* clientCertificateRequired */,
                    SslProtocols.Tls,
                    false /* checkCertificateRevocation */,
                    callback,
                    asyncState
                );
            }
        }
예제 #22
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);
            }
        }
예제 #23
0
        public void Authenticate(X509Certificate2 certificate, Fleck2Extensions.Action callback, Fleck2Extensions.Action<Exception> error)
        {
            var ssl = new SslStream(_stream, false);
            _stream = ssl;

            Fleck2Extensions.Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, SslProtocols.Tls, false, cb, s);

            _socketFactory.HandleAsyncVoid(begin, ssl.EndAuthenticateAsServer, result =>
                {
                    result.Success(callback);
                    result.Error(error);
                });
        }
        private IAsyncResult BeginInitStream(AsyncCallback asyncCallback)
        {
            IAsyncResult result = null;

            switch (SecureProtocol)
            {
                case (SslProtocols.Default):
                case (SslProtocols.Tls):
                case (SslProtocols.Ssl3):
                    SslStream sslStream = new SslStream(new NetworkStream(Client), false);
                    result = sslStream.BeginAuthenticateAsServer(AppSession.AppServer.Certificate, false, SslProtocols.Default, false, asyncCallback, sslStream);
                    break;
                case (SslProtocols.Ssl2):
                    SslStream ssl2Stream = new SslStream(new NetworkStream(Client), false);
                    result = ssl2Stream.BeginAuthenticateAsServer(AppSession.AppServer.Certificate, false, SslProtocols.Ssl2, false, asyncCallback, ssl2Stream);
                    break;
                default:
                    m_Stream = new NetworkStream(Client);
                    break;
            }

            return result;
        }
예제 #25
0
        public void AsyncInitialize(Action<ConnectionHandle> onSuccess, Action<ConnectionHandle> onFailure)
        {
            try
            {
                _networkStream = new NetworkStream(Socket, true);
            }
            catch (Exception)
            {
                onFailure(this);
                return;
            }

            if (Binding.Secure && Binding.Certificate != null)
            {
                try
                {
                    _tlsStream = new SslStream(_networkStream);
                    _tlsStream.BeginAuthenticateAsServer(Binding.Certificate, false, SslProtocols.Default, false,
                                                         InitializeCallback, onSuccess);
                }
                catch (Exception)
                {
                    onFailure(this);
                }
            }
            else
            {
                AddState(ClientState.Ready);
                onSuccess(this);
            }
        }
예제 #26
0
 /// <summary>
 /// Authenticates over the socket.
 /// </summary>
 /// <param name="certificate">An <see cref="X509Certificate2"/> that specifies authentication information.</param>
 public void Authenticate(X509Certificate2 certificate)
 {
     var ssl = new SslStream(this.stream, false);
     this.stream = ssl;
     ssl.BeginAuthenticateAsServer(certificate, false, SslProtocols.Tls, false, this.OnAuthenticate, ssl);
 }
        public void Receive_one_message()
        {
            var slice1 = new BufferSlice(new byte[65535], 0, 65535);
            var encoder1 = new StringEncoder();
            var decoder1 = new StringDecoder();
            var expected = "Hello".PadRight(5000);
            var outBuffer = new byte[expected.Length + 4];
            BitConverter2.GetBytes(expected.Length, outBuffer, 0);
            Encoding.UTF8.GetBytes(expected, 0, expected.Length, outBuffer, 4);
            object actual = null;
            var evt = new ManualResetEvent(false);
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);

            var sut1 = CreateClientChannel(slice1, encoder1, decoder1);
            sut1.MessageReceived = (channel, message) =>
            {
                actual = message;
                evt.Set();
            };
            sut1.Assign(_helper.Client);
            stream.Write(outBuffer);

            evt.WaitOne(500).Should().BeTrue();
            actual.Should().Be(expected);
        }
예제 #28
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;
        }
        public void send_close_message()
        {
            var slice = new BufferSlice(new byte[65535], 0, 65535);
            var encoder = new StringEncoder();
            var decoder = new StringDecoder();

            var sut = CreateClientChannel(slice, encoder, decoder);
            sut.MessageReceived += (channel, message) => { };
            var stream = new SslStream(new NetworkStream(_helper.Server));
            stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
            sut.Assign(_helper.Client);

            Assert.True(sut.IsConnected);

            sut.Close();

            Assert.False(sut.IsConnected);
        }