runtime icon indicating copy to clipboard operation
runtime copied to clipboard

HttpClient behavior difference between .Net 6 and .Net 5

Open raweibel opened this issue 5 years ago • 44 comments

Discussed in https://github.com/dotnet/runtime/discussions/62046

Originally posted by raweibel November 25, 2021 Hello everyone, we are working on an .Net 6 application that is run on a corproate network which requires proxy authentication using the windows credentials. As we were running into problems using HttpClient, we wrote a small test application and noticed that when running in .Net 5 things work as expected, but in .Net 6 they do not.

Our test code:

var handler = new HttpClientHandler();
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
var client = new HttpClient(handler);
var response = await client.GetAsync(requestedURL);
Console.WriteLine($"Response: {response.StatusCode}");

Expected result: Response: Ok

Result in .Net 5: Response: Ok

Result in .Net 6: Unhandled exception. System.ComponentModel.Win32Exception (0x80090308): The token supplied to the function is invalid at System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatusPal& statusCode)

Does anyone know if this is a known problem? Is there a way to fix this in .Net 6?


See the original question in the discussion above. After some further investigation of the error and compairing the logs of both programs (see attachments), it seems that the .NET 6 version fails to deal with the NTLM challenge send by the server, leading to the error. But that is just my interpretation of things.

Additional information:

Full Error message in .Net 6:

Unhandled exception. System.ComponentModel.Win32Exception (0x80090308): The token supplied to the function is invalid
   at System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatusPal& statusCode)
   at System.Net.NTAuthentication.GetOutgoingBlob(String incomingBlob)
   at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, Boolean async, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, Boolean async, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.EstablishProxyTunnelAsync(Boolean async, HttpRequestHeaders headers, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
   at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at OfficePulse.Test.Program.CurrentTry(String requestedURL) in C:\*REMOVED*\Program.cs:line 50
   at OfficePulse.Test.Program.Main(String[] args) in C:\*REMOVED*\Program.cs:line 34
   at OfficePulse.Test.Program.<Main>(String[] args)

Log files (some info removed) TraceDotNet5_redacted.txt TraceDotNet6_redacted.txt

raweibel avatar Nov 29 '21 12:11 raweibel

Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.

Issue Details

Discussed in https://github.com/dotnet/runtime/discussions/62046

Originally posted by raweibel November 25, 2021 Hello everyone, we are working on an .Net 6 application that is run on a corproate network which requires proxy authentication using the windows credentials. As we were running into problems using HttpClient, we wrote a small test application and noticed that when running in .Net 5 things work as expected, but in .Net 6 they do not.

Our test code:

var handler = new HttpClientHandler();
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
var client = new HttpClient(handler);
var response = await client.GetAsync(requestedURL);
Console.WriteLine($"Response: {response.StatusCode}");

Expected result: Response: Ok

Result in .Net 5: Response: Ok

Result in .Net 6: Unhandled exception. System.ComponentModel.Win32Exception (0x80090308): The token supplied to the function is invalid at System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatusPal& statusCode)

Does anyone know if this is a known problem? Is there a way to fix this in .Net 6?


See the original question in the discussion above. After some further investigation of the error and compairing the logs of both programs (see attachments), it seems that the .NET 6 version fails to deal with the NTLM challenge send by the server, leading to the error. But that is just my interpretation of things.

Additional information:

Full Error message in .Net 6:

Unhandled exception. System.ComponentModel.Win32Exception (0x80090308): The token supplied to the function is invalid
   at System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatusPal& statusCode)
   at System.Net.NTAuthentication.GetOutgoingBlob(String incomingBlob)
   at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, Boolean async, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, Boolean async, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.EstablishProxyTunnelAsync(Boolean async, HttpRequestHeaders headers, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)
   at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at OfficePulse.Test.Program.CurrentTry(String requestedURL) in C:\*REMOVED*\Program.cs:line 50
   at OfficePulse.Test.Program.Main(String[] args) in C:\*REMOVED*\Program.cs:line 34
   at OfficePulse.Test.Program.<Main>(String[] args)

Log files (some info removed) TraceDotNet5_redacted.txt TraceDotNet6_redacted.txt

Author: raweibel
Assignees: -
Labels:

area-System.Net.Http, untriaged

Milestone: -

ghost avatar Nov 29 '21 12:11 ghost

There is not enough details to make this actionable @raweibel. What platform are you running on? .NET generally uses underlying OS functions so the difference between 5 & 6 is surprising. You can try to set breakpoint in GetOutgoingBlob() and at least check if the incomingBlob looks right and it if was properly base64 decode e.g. string-> byte[] was OK. The handshake really does not have any sensitive information like credentials (since NTLM is challenge-response). If you don't want to make public post, send me details to my GH email.

wfurt avatar Nov 29 '21 18:11 wfurt

Let me provide you with more details:

The program is running on Windows 10 Enterprise 20H2 19042.1348 For the .NET 5 we used SDK 5.0.403-win-x64 and for .NET 6 SDK 6.0.100-win-x64

Here are the Trace files with the NTLM information: TraceDotNet6.txt TraceDotNet5.txt

I will have a look at what's happening with the incomingBlob tomorrow.

raweibel avatar Nov 29 '21 21:11 raweibel

ok. the exchange looks reasonable e.g. the last part looks like valid NTLM response. I don't have any theory why we would get SEC_E_INVALID_TOKEN.

wfurt avatar Nov 29 '21 22:11 wfurt

I check and there are no NTLM changes comparing to 5.0. Changes in connection management would be wisest suspect IMHO. It may be worth to check that all the attempts go out on the same connection @raweibel. (with Wireshark) cc: @geoffkizer

wfurt avatar Nov 30 '21 02:11 wfurt

@raweibel I'd be also curious if it fails always (aka 100% repro), or only sometimes.

karelz avatar Nov 30 '21 08:11 karelz

It happens everytime I run the test application mentioned above. I will see what I can find with Wireshark.

raweibel avatar Nov 30 '21 09:11 raweibel

Changes in connection management would be wisest suspect IMHO.

It certainly seems like this is possible, but I don't see any obvious change that would lead to this.

Wireshark trace would help.

geoffkizer avatar Nov 30 '21 22:11 geoffkizer

It could also be related to this change: https://github.com/dotnet/runtime/pull/50763

But again, I don't see specifically how...

geoffkizer avatar Nov 30 '21 22:11 geoffkizer

Managed to capture a trace (in nethsh as Wireshark is prohibited on the corporate network) and move it over to Wireshark. Never used it before, so I'm not sure what to look for. Here are screenshots of both the Net5 and Net6 traces. Feel free to tell me what else I can provide.

Net 6: NET6_Wireshark Net 5: NET5_Wireshark

raweibel avatar Dec 01 '21 13:12 raweibel

I don't see anything particularly weird in that trace. The connection is being reset eventually, but presumably that's because we are getting SEC_E_INVALID_TOKEN after the second 407.

So the question still remains, why are we getting SEC_E_INVALID_TOKEN in 6.0 but not in 5.0?

geoffkizer avatar Dec 01 '21 21:12 geoffkizer

agreed. It is the same connection, data looks reasonable and it simply fails in Windows PAL.

wfurt avatar Dec 01 '21 21:12 wfurt

Triage: We need to investigate more, it is unclear what is happening. Without a local repro it will be very challenging. @raweibel are you in position to debug into it in your environment?

Moving to Future for now, until we have more customers hitting it.

karelz avatar Dec 02 '21 17:12 karelz

I'm currently setting up an environment that allows me to debug it. Hopefully, this will allow me to pin point the source of the exception. I will get back to you with the results in the coming days.

raweibel avatar Dec 03 '21 15:12 raweibel

Hello @raweibel I have the same Issue. It's also on a corproate network which requires proxy authentication using the windows credentials. Any news from your side? Have you found a workaround?

mihael74 avatar Jan 13 '22 12:01 mihael74

Hi @mihael74 , I haven't been able to further invetigate the issue, as I'm an external working with a company (i.e. I have limited access to deploying development tools on their systems). Currently, trying find a solution with them. If you have the ability the futher investigate the issue, that would be great!

As for aworkaround, we resorted to downgrading to .NET 5 for now.

raweibel avatar Jan 13 '22 16:01 raweibel

Does it fail consistently or randomly @mihael74? Can you provide more information?

wfurt avatar Jan 13 '22 17:01 wfurt

Hello @raweibel and @wfurt It fails consistently (100%) with net6.0 and it does not fail at all with net5.0. I'm also an external with very limited capabilities. I'll contact the team responsible for the proxy and ask them about protocol information and whether they see anything useful on their side. Would any particular information be helpful?

mihael74 avatar Jan 14 '22 06:01 mihael74

It looks exactly same as raweibel's case. The challenge fails: net5.0: net5 net6.0: net6

mihael74 avatar Jan 14 '22 09:01 mihael74

I set up proxy with NTLM authentication and I cannot reproduce it. But I have simple app, perhaps can you try it as well @mihael74?

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

namespace http
{
    class Program
    {
        static async Task Main(string[] args)
        {

            AppDomain.CurrentDomain.FirstChanceException += (s, o) => { StackTrace st = new StackTrace(true); Console.WriteLine(o.Exception.StackTrace); Console.WriteLine(st); };

            var handler = new SocketsHttpHandler();
            handler.Proxy = new WebProxy("http://10.10.10.10:1010/");
            handler.DefaultProxyCredentials  = new NetworkCredential("user1", "PASSWORD", "DOMAIN");
            //handler.DefaultProxyCredentials  = CredentialCache.DefaultCredentials;
            using (var client = new HttpClient(handler))
            {
                for (int i = 0; i < 4; i++)
                {
                     try
                     {
                         var response = await client.GetStringAsync("https://www.microsoft.com");
                         Console.WriteLine(response);
                     } catch (HttpRequestException ex)
                     {
                             Console.WriteLine(ex);
                     }
                }
            }
        }
    }
}

You can try both versions, one with default credentials and one with explicit authentication to see if that makes any difference. Since this is simple app, can you also set break on GetOutgoingBlob and check _spn and _clientSpecifiedSpn. (or any observable differences) Logs & packet captures may be useful. If you don't want to post them here, send them to my GH email.

wfurt avatar Jan 14 '22 21:01 wfurt