Returning more verbose error messages from HttpCli

2019-08-28 12:47发布

I'm writing code against a web server that does client certificate authentication. I make a WebRequestHandler with my certificate chain, pass that into a HttpClient object and then call PostAsync on the HttpClient. This works fine with a valid certificate on the chain of trust that is not revoked. The HttpResponseMessage task faults when the certificate is revoked (as is expected) and Exception member contains this aggregate exception:

An error occurred while sending the request.

The request was aborted: Could not create SSL/TLS secure channel.

My problem is that I need a more verbose error. If I do the same thing (submit the same revoked client certificate) from Chrome I get this error:

ERR_BAD_SSL_CLIENT_AUTH_CERT

And from Internet Explorer:

ERROR_INTERNET_SEC_CERT_REVOKED

How can I get such an error? I need to tell the user not only that it didn't work but WHY. The fact that browsers get a more precise error seems to indicate that more information is coming back that just the fault exception. It doesn't seem to be because of intentional obfuscation.

Code sample:

WebRequestHandler handler = new WebRequestHandler();

if (certCol != null)
{
    foreach (X509Certificate2 cert in certCol)
    {
        handler.ClientCertificates.Add(cert);
    }
}
else
{
    sLastErr = "Could not find client certificate to communicate. Certificate collection is NULL.";
    LogHelper.LogGenericError(
        _logger,
        sLastErr
        );
    return false;
}

_HttpClient = new HttpClient(handler);

_HttpClient.PostAsync(uriCM, reqContent).ContinueWith(requestTask => 
{
    HttpResponseMessage httpRespContent = null;
    bool bSuccess = false;
    if (requestTask.IsCompleted)
    {
        if (requestTask.Status == TaskStatus.RanToCompletion)
        {
            httpRespContent = requestTask.Result;
            bSuccess = true;
        }
        else if(requestTask.Status == TaskStatus.Faulted)
        {
            if (requestTask.Exception != null)
            {
                LogHelper.LogErrorWithAggregateException(_logger, "PostAsync call faulted.", requestTask.Exception);
                //exception messages in aggregate exception:
                //An error occurred while sending the request.
                //The request was aborted: Could not create SSL/TLS secure channel.
            }
            else
                LogHelper.LogError(_logger, "PostAsync call faulted.");
        }
        else
        {
            LogHelper.LogError(_logger, "PostAsync call failed.");
        }
    }
    else
    {
        LogHelper.LogError(_logger, "PostAsync call never completed. Communication Failure.");
    }

    if (bSuccess)
    {
        //it worked, do stuff...        }
    }
});

标签: c# ssl tls1.2
1条回答
趁早两清
2楼-- · 2019-08-28 13:00

SslStream throws a Win32 exception that reports that the certificate is revoked if it is revoked. Like the browsers. Seems to be hitting Schannel or some un-managed code at a lower level and piping it up. If HttpClient returns a TLS error, I run my code to try to make a SslStream+TcpClient connection and report the exception. I guess HttpClient just buries the error details and SslStream exposes it in an inner exception. Solves my problem.

Sample code:

    public bool VerifyThatCanAuthenticateAsClient()
    {
        bool bSuccess = false;
        TcpClient tcpClient = null;
        SslStream sslStream = null;

        try
        {
            tcpClient = new TcpClient(
                _sHostname,
                _iPort
            );

            bSuccess = true;
        }
        catch(Exception ex)
        {
            //log exception
        }

        if(bSuccess)
        {
            bSuccess = false;

            try
            {
                sslStream = new SslStream(
                    tcpClient.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    new LocalCertificateSelectionCallback(SelectLocalCertificate),
                    EncryptionPolicy.RequireEncryption
                    );

                bSuccess = true;
            }
            catch (Exception ex)
            {
                //log exception
            }
        }

        if (bSuccess)
        {
            bSuccess = false;

            try
            {
                sslStream.AuthenticateAsClient(
                    _sHostname,
                    null,
                    System.Security.Authentication.SslProtocols.Tls12,
                    false
                    );

                bSuccess = true;
            }
            catch (Exception ex)
            {
                //log ex.message exception

                if(ex.InnerException != null)
                {
                    //log ex.innerexception.message
                    //this is what gives me the low level error that means its revoked if it is, or other specific tls error
                }
            }
        }

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

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

        return bSuccess;
    }
查看更多
登录 后发表回答