runtime icon indicating copy to clipboard operation
runtime copied to clipboard

SocketsHttpHandler rejects certificate with RemoteCertificateNameMismatch

Open tmds opened this issue 8 years ago • 33 comments

Reported by @ydekova in https://github.com/dotnet/corefx/issues/29942#issuecomment-397006087

The following code throws on .NET Core 2.1, and does not throw on .NET Core 2.0:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace console2
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync("https://outlook.office.com");
                System.Console.WriteLine(response.StatusCode);
            }
        }
    }
}
Unhandled Exception: System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
   at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Security.SslState.ThrowIfExceptional()
   at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result)
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
   at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__47_1(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at console2.Program.Main(String[] args) in /tmp/console2/Program.cs:line 13
   at console2.Program.<Main>(String[] args)

@ydekova's comment https://github.com/dotnet/corefx/issues/29942#issuecomment-397200251:

The SslPolicyError (errors param in the above code) is RemoteCertificateNameMismatch

When using the curlhandler on 2.1 (DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0), the code works.

tmds avatar Jun 14 '18 11:06 tmds

The outlook.office.com certificate has as CN and in alternative names: 'Outlook.office.com'. So this may be due to the different casing:

Subject: C = US, ST = Washington, L = Redmond, O = Microsoft Corporation, CN = Outlook.office.com
X509v3 Subject Alternative Name: 
                DNS:Outlook.office.com, DNS:attachment.outlook.office.net, DNS:attachment.outlook.officeppe.net, DNS:bookings.office.com, DNS:delve.office.com, DNS:edge.outlook.office365.com, DNS:edgesdf.outlook.com, DNS:img.delve.office.com, DNS:outlook.live.com, DNS:outlook-sdf.live.com, DNS:outlook-sdf.office.com, DNS:sdfedge-pilot.outlook.com, DNS:substrate.office.com, DNS:substrate-sdf.office.com, DNS:afd-k-acdc-direct.office.com

tmds avatar Jun 14 '18 11:06 tmds

cc: @bartonjs

stephentoub avatar Jun 14 '18 12:06 stephentoub

Does this happen just on Linux or also on Windows?

davidsh avatar Jun 14 '18 14:06 davidsh

https://www.ssllabs.com/ssltest/analyze.html?d=outlook.office.com&s=13.107.18.11&hideResults=on

Subject: Outlook.office.com
Common names: Outlook.office.com
Alternative names:
Outlook.office.com
attachment.outlook.office.net
attachment.outlook.officeppe.net
bookings.office.com
delve.office.com
edge.outlook.office365.com
edgesdf.outlook.com 
img.delve.office.com
outlook.live.com
outlook-sdf.live.com
outlook-sdf.office.com
sdfedge-pilot.outlook.com
substrate.office.com
substrate-sdf.office.com
afd-k-acdc-direct.office.com

davidsh avatar Jun 14 '18 14:06 davidsh

If it works in Windows (or worked in cURL), everyone else must use strnicmp, and I used memcmp, because DNS names are "always" lowercase.

bartonjs avatar Jun 14 '18 14:06 bartonjs

because DNS names are "always" lowercase.

https://tools.ietf.org/html/rfc4343

Domain Name System (DNS) names are "case insensitive".

davidsh avatar Jun 14 '18 14:06 davidsh

We should consider fixing this for servicing release/2.1.x as well.

cc: @karelz

davidsh avatar Jun 14 '18 14:06 davidsh

While DNS is lowercase I thought that RFC3280/5280 had a constraint saying it needed to be in a normalized form. Unfortunately for me, it explicitly calls out that it's case-invariant. ::whistles innocently::

For master we should hold this work until dotnet/corefx#30376 is merged to avoid conflicts.

bartonjs avatar Jun 14 '18 14:06 bartonjs

It happens only on Linux, at least in my case.

I ended up with this workaround for now. Not sure if it's a viable one, I'd be thankful if you comment.

var httpClientHandler = new HttpClientHandler();

httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => {
    if (errors == SslPolicyErrors.None)
    {
        return true;
    }

    if (errors == SslPolicyErrors.RemoteCertificateNameMismatch)
    {
         // Try custom DNS name validation
         var isValidDns = MyCustomValidation(cert, message.RequestUri.Authority);

         if (!isValidDns)
         {
             throw new AuthenticationException($"Ssl certificate validation failed when trying to connect to {message.RequestUri}, Error: {SslPolicyErrors.RemoteCertificateNameMismatch}. Built-in validation failed and custom validation failed.");
         }

         return true;
    }

    throw new AuthenticationException($"Ssl certificate validation failed when trying to connect to {message.RequestUri}, Error: {errors}.");
}

var client = new HttpClient(httpClientHandler);

MyCustomValidation being mostly inspired by how it is implemented in mono.

More info here: https://github.com/mono/mono/blob/0bcbe39b148bb498742fc68416f8293ccd350fb6/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs

checkServerIdentity method.

I would prefer to use the built-in logic though. I'm not familiar with how releases are happening when it comes to patch update so can you point me to some roadmap where I can check for this?

ydekova avatar Jun 14 '18 15:06 ydekova

@ydekova what happens when you set DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0? How does your application behave? With the code above, that makes it work for me on Fedora.

tmds avatar Jun 14 '18 15:06 tmds

@tmds I set it in /etc/environment:

/etc$ cat environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
ASPNETCORE_ENVIRONMENT=Staging
DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0

I restarted the dot net application and there was no change. The same error as before.

ydekova avatar Jun 14 '18 15:06 ydekova

@ydekova that's unexpected - @tmds do you think there are differences in libcurl behavior here?

@davidsh I agree that we should fix it in 2.1.x. Where would the fix go? Networking layer or do we have to convince @bartonjs to relax comparison in Security layer?

karelz avatar Jun 14 '18 16:06 karelz

It's not really "relax" it's "match everyone else". ~4 line change in crypto native.

bartonjs avatar Jun 14 '18 17:06 bartonjs

Let's do it then. Thanks @bartonjs!

karelz avatar Jun 14 '18 17:06 karelz

@tmds do you think there are differences in libcurl behavior here?

curl does the case-insensitive compare.

I restarted the dot net application

@ydekova if you do this with /etc/environment you need to reboot your system. You can launch your app as DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0 dotnet myapp.dll.

tmds avatar Jun 14 '18 17:06 tmds

@tmds can you tell me what this setting (DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER) does exactly and how it will affect the app's behavior? Does it affect the SignalR support? Not sure if its OK to change it globally, we have quite a few net core apps running on this instance, all of them are now upgraded to 2.1

ydekova avatar Jun 16 '18 07:06 ydekova

@ydekova just change it locally and run the app with the setting. That should not be a problem, should it? The setting will disable our new networking stack implementation - see more here.

karelz avatar Jun 16 '18 08:06 karelz

@karelz 'locally' it's windows so the problem does not exist. Aside from this, testing this on a Linux machine is not a problem yes, it does fix the problem on our test machine.

What I was asking is are there some functionalities which rely on the new handler in 2.1. (i.e. SignalR) or is the difference only related to performance? We haven't implemented our socket server yet but we are planning to, this is why I need to know.

Thanks

ydekova avatar Jun 16 '18 09:06 ydekova

By locally I meant in env window, then run the app, so the env vars apply only "locally", not machine-wide.

There are subtle differences, but the main ones are performance and HTTP/2 support (which SocketsHttpHandler) does not have.

karelz avatar Jun 16 '18 19:06 karelz

@karelz I would prefer to use the new sockets handler because otherwise, we encounter the memory leak problem. In my code above this would mean using "new SocketsHttpHandler()" instead of "new HttpClientHandler()" right?

ydekova avatar Jun 17 '18 20:06 ydekova