tags:

views:

40

answers:

0

I am developing an application that implements a TCP client. It needs to be able to talk to a server with or without TLS, either via a NetworkStream or an SslStream. When I connect I don't know which settings the server uses. My code works fine from non-secure to non-secure and from secure to secure.

However when I set my client to use a secure connection where the server is set to use a non-secure connection, my application hangs on the SslStream.BeginAuthenticateAsClient call.

My questions are:

  • Can I detect if the server supports secure settings before I call SslStream.BeginAuthenticateAsClient?

  • If not, can I set a timeout on BeginAuthenticateAsClient?

The relevant code from the callback given to TcpClient.BeginConnect:

    private void OnConnected(IAsyncResult asyncResult)
    {
        try
        {
            mTcpClient.EndConnect(asyncResult);

            if (SecureAuthentication)
            {
                var leaveStreamOpen = !EncryptDataTransfer;
                if (leaveStreamOpen)
                {
                    mNetworkStream = mTcpClient.GetStream();
                }
                mSslStream = new SslStream(
                    mTcpClient.GetStream(),
                    leaveStreamOpen, OnValidateServerCertificate);
                try
                {
                    mSslStream.BeginAuthenticateAsClient(
                        mRemoteHostName,
                        ClientCertificates,
                        SslProtocols.Tls,
                        false,
                        OnAuthenticateAsClient,
                        mSslStream);
                    // Still not done: only after OnAuthenticateAsClient is called do we know
                    // if a connection is successfully set up

After this the callback OnAuthenticateAsClient never gets called.