wcf icon indicating copy to clipboard operation
wcf copied to clipboard

WCF 4.5.0 and .NET Core 2.1 - NTLM authentication fails with "Authentication failed because the connection could not be reused"

Open bregger opened this issue 8 years ago • 32 comments

Quick details

  • Consistently getting on the second request System.ServiceModel.CommunicationException: Authentication failed because the connection could not be reused. on windows and linux while using NTLM.
  • Client System.ServiceModel.Http version 4.5.0
  • Client System.ServiceModel.Security version 4.5.0
  • Client target framework netcoreapp2.1
  • Client Platform: Windows 10 desktop and stretch linux in docker (with gss-ntlmssp-dev)
  • Server Platform: Windows Server 2012 R2 - IIS 8.5 - WCF (not sure what version)
  • Both using BasicHttpBinding and client using generated service proxy classes
  • Both set to BasicHttpSecurityMode.TransportCredentialOnly and HttpClientCredentialType.Ntlm

The gist of this issue we're seeing is that making multiple service calls with NTLM will fail with the exception "Authentication failed because the connection could not be reused". Multiple calls seem to always fail - sometimes calls also fail the first time under some conditions. I've not had this issue with .NET core 2.1 HttpClient and manually coding SOAP requests. The client applications have been running without issues using .NET Core 2.0 and WCF 4.4.1 for a while now on windows and linux. I don't believe this is a gss related issue, but it could be an environment issue on our part with the service we're connecting to. The service we're calling is a WCF web service setup using Dynamics AX and running in IIS 8.5 on Windows Server 2012 R2. I will probably need to keep working and develop a code sample (two docker containers, hopefully, or be able to pinpoint some other platform specific interplay)

Below is a full stack trace. There's a lot of details to work through so I apologize for this hasty post and like I said I would like to add a code sample. But I just wanted to post this so if somebody saw it they could provide some context or insight so I can save some time when I am troubleshooting and trying to get down to a minimum viable code sample for posting here.

I have observed this behavior on both windows 10 (no container) and running in docker using the image microsoft/dotnet:2.1-aspnetcore-runtime-stretch-slim image with the gss-ntlmssp-dev package installed.

System.ServiceModel.CommunicationException: Authentication failed because the connection could not be reused. ---> System.Net.Http.HttpRequestException: Authentication failed because the connection could not be reused.
   at System.Net.Http.HttpConnection.DrainResponseAsync(HttpResponseMessage response)
   at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts,
Boolean disposeCts)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
   --- End of inner exception stack trace ---
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(HttpRequestException requestException, HttpRequestMessage request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
   at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.RequestAsyncInternal(Message message, TimeSpan timeout)
   at System.Runtime.TaskHelpers.WaitForCompletionNoSpin[TResult](Task`1 task)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(MethodCall methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(MethodInfo targetMethod, Object[] args)
--- End of stack trace from previous location where exception was thrown ---
   at System.Reflection.DispatchProxyGenerator.Invoke(Object[] args)
   at generatedProxy_2.Create(CustomerCreateServiceCreateRequest )

bregger avatar Jun 04 '18 23:06 bregger

Running in to the same issue after upgrading to WCF 4.5.0 and .NET Core 2.1. Pretty similar configuration, NTLM over a https connection, calling custom WCF services running on .Net 4.6.2. Temporarily resolved by rolling the WCF libraries back to 4.4.2, still on .Net Core 2.1.

neil-russell avatar Jun 06 '18 18:06 neil-russell

Facing the same problem. @neil-russell: thx for workaround - works like charm

azbest208 avatar Jun 14 '18 07:06 azbest208

Here's some background context as to what the issue is. With NTLM, you authenticate the socket and not the request. This makes socket reuse problematic as there's a potential security issue. If you make an initial request with credentials A, the server will return an authentication challenge and the socket will be authenticated with those credentials. If you make a second request with credentials B, the server won't return an authentication challenge as the socket has already been authenticated. That second request will be executed with the security context of credentials A. Because of this, the default behavior is to close a socket when an NTLM authentication request has been completed.
With the change to .Net Core 2.1, the underlying implementation was switched from multiple native implementations to SocketsHttpHandler which is a completely managed implementation. The issue is in that class somewhere and I'll follow up with the owners of that class to solve this problem. I understand that the problem goes away when rolling back to 4.4.2 but still running on .Net Core 2.1. WCF made a small change around authentication between 4.4.2 and 4.5.0. We started using CredentialCache which restricts credentials to only be used with the client expected authentication scheme. This is to prevent a service/client mismatch issue where the server for example asks for basic authentication and the client is expecting Negotiate (Windows auth). I believe there's a behavior difference in SocketsHttpHandler when this happens which is why the issue appears when moving to 4.5.0.
While I'm investigating I have a potential work around. I haven't tested this so I'm not 100% but with the nature of the problem, there's a good chance this will work. You can set KeepAliveEnabled to false on the HttpsTransportBindingElement/HttpTransportBindingElement. Here's some example code:

            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            customBinding = new CustomBinding(binding);
            var httpElement = customBinding.Elements.Find<HttpsTransportBindingElement>();
            httpElement.KeepAliveEnabled = false;

mconnew avatar Jun 29 '18 20:06 mconnew

Okay, that workaround won't work. The issue is we also enabled Expect100Continue in 4.5.0 and there's a bug in SocketsHttpHandler where if you use Expect100Continue in conjunction with authentication and request bodies larger than 1024 bytes, it throws this exception. Our testing didn't pick this up because we don't test authentication at the same time as large messages. I'll open an issue in corefx once I have a standalone repro and update here. For now, sticking with 4.4.2 is probably the best option.

mconnew avatar Jun 29 '18 21:06 mconnew

Issue opened dotnet/corefx#30760. I've narrowed down the exact scope of the issue. Expect100Continue is used with Windows authentication and a request body greater than 1024 bytes. @bregger, you likely only saw the issue on your second request as I suspect your first request was smaller than 1024 bytes. I suspect if you configure your binding to use StreamedRequest transfer mode that the problem will go away. They only close the connection when the request body size is known to be > 1024 bytes. With streamed mode, the request size is unknown as it uses chunked encoding. You only need to make the change on the client when using HTTP. The server can remain configured to use Buffered transfer mode with the client configured to use streamed (this is unique to HTTP transport).

mconnew avatar Jun 29 '18 22:06 mconnew

@mconnew Thanks for the background information. I did attempt trying to set KeepAliveEnabled = false as a workaround before posting the issue and it didn't have any effect when I tried it so I wasn't sure if it was even supported in .net core.

Edit: Nice job finding that! It turns out the first request in our regression tests that caused the issue was 500 bytes and the second request was 1100 bytes, hence the always happening on the second request but sometimes happening on the first request when I was trying to isolate the issue.

As a test I set our home grown soap client default request headers to ExpectContinue as well and our regressions still passed. I wonder why I'm able to use ExpectContinue and NTLM authentication with HttpClient above and beyond the 1024 mark but WCF isn't. Perhaps there's another factor involved that will cause us to run into the same issue eventually.

Edit 2: I just tried using TransferMode StreamedRequest and HttpChannelFactory won't allow it. System.ArgumentException: HTTP request streaming cannot be used in conjunction with HTTP authentication. Either disable request streaming or specify anonymous HTTP authentication.. (As a test I was ~~able to use every possible combination of the ConnectionClose, TransferEncodingChunked, and ExpectContinue headers using NTLM.~~) It seems not every combination worked.

bregger avatar Jun 29 '18 23:06 bregger

@bregger, are you using netcoreapp2.1 on your home grown implementation? Also is the content length set on the HttpContent? And you're right about the streamed transfer, I had forgotten about HttpChannelFactory not liking that. It's because with authentication you may need to send the request body multiple times and if it's streamed you either need to buffer it or hope and pray the Expect 100 Continue mechanism actually is used (there's a timeout which can cause it to be sent while waiting for the response).

mconnew avatar Jun 30 '18 01:06 mconnew

@mconnew Yes we're using netcoreapp2.1 for our implementation and setting ContentLength. It appears I actually made a mistake when testing HttpClient with NTLM

This means that for us we are able to use NTLM and set the headers ConnectionClose = false and ExpectContinue = false to eliminate the issue.

Here's what my tests showed:

  1. Using NTLM and ConnectionClose = true; header always causes failure. This makes sense.

  2. Using NTLM and setting ExpectContinue = true and TransferEncodingChunked = true caused a failure for any length request. I'm not sure if this is a valid combination as I'm not that familiar with HTTP.

  3. Using NTLM and setting ExpectContinue = true but instead setting TransferEncodingChunked = false causes a failure only for requests > 1024 bytes.

Sorry for the confusion! Hope this helps you with the issue you made in corefx

bregger avatar Jun 30 '18 03:06 bregger

@breggar, I added a new feature recently to WCF (on .Net Core only) which allows you to intercept all HttpClient requests and modify the request before it's sent. You can find a sample behavior which you can apply to your client here. While the implementation class InterceptingHttpMessageHandler is designed to provide a delegate to modify the request, you can strip that out and just do the modification in SendAsync.

mconnew avatar Jul 02 '18 19:07 mconnew

I had the same issue, the workarounds however didn't work for me but adding the following line in my .Net Core application did;

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

JWH89 avatar Jul 27 '18 07:07 JWH89

I'm running in this issue as well, and can workaround it via the AppContext.SetSwitch combined with the ExpectContinue = false fix mentioned here and in #3185.

But, if I'm understanding the implications of these workarounds correctly (large request bodies will be sent twice), I'll likely just roll back to to < 4.5. I wanted to upgrade because 4.5 fixed being able to deploy as a contained app (runtime win-x64), but that can wait for now.

eajhnsn1 avatar Nov 15 '18 16:11 eajhnsn1

@eajhnsn1, using earlier that 4.5 you would still sometimes get the request body sent extra times as it was just a best effort attempt by sending a HEAD request. This had the overhead of every request, even after authentication had happened would have an extra HEAD request so added a small extra latency to every request. So your options are using 4.5 with the AppContext switch and have the first request on a socket have the body sent more times but subsequent requests are quicker, or use <4.5 and have less data sent on the first request but every request has a small increased latency due to always sending a pre-request HEAD.

mconnew avatar Nov 19 '18 20:11 mconnew

Hi, Am also getting the same issue WCF 4.5.0 and .NET Core 2.1 - NTLM authentication fails with "Authentication failed because the connection could not be reused Is there any solution found for this issue .its open since Nov20 Could someone please respond on this issue.

Dhivyatej avatar Jan 07 '19 08:01 Dhivyatej

Hi, Am also getting the same issue WCF 4.5.0 and .NET Core 2.1 - NTLM authentication fails with "Authentication failed because the connection could not be reused Is there any solution found for this issue .its open since Nov20 Could someone please respond on this issue.

or could you please elaborate or give some code sample on how to use 4.5 with the AppContext switch and have the first request on a socket have the body sent more times but subsequent requests are quicker,

Dhivyatej avatar Jan 07 '19 09:01 Dhivyatej

@eajhnsn1, using earlier that 4.5 you would still sometimes get the request body sent extra times as it was just a best effort attempt by sending a HEAD request. This had the overhead of every request, even after authentication had happened would have an extra HEAD request so added a small extra latency to every request. So your options are using 4.5 with the AppContext switch and have the first request on a socket have the body sent more times but subsequent requests are quicker, or use <4.5 and have less data sent on the first request but every request has a small increased latency due to always sending a pre-request HEAD.

could you please elaborate or give some code sample on how to use 4.5 with the AppContext switch and have the first request on a socket have the body sent more times but subsequent requests are quicker

Dhivyatej avatar Jan 07 '19 09:01 Dhivyatej

We experience same issue with large request on .NET 2.2. For us is better workarround to switch to WinHttpHandler with usage of enviroment variable DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER.

McMlok avatar Jan 29 '19 07:01 McMlok

+1 vote for staying on this and getting it resolved. I upgraded all my application dependencies today (to 4.5.3 and Core 2.2) and was granted this unexpected reward. For now I'm functioning by stepping back to 4.4.2 of the communications packages but please do fix. Thank you.

TPucke avatar Feb 12 '19 01:02 TPucke

@TPucke, this is really out of our hands. The bug exists in HttpClientHandler and I opened issue dotnet/corefx#30760 over 6 months ago. Feel free to add a comment over on the corefx issue to encourage higher priority on a fix.

mconnew avatar Feb 12 '19 03:02 mconnew

thanks, will do

TPucke avatar Feb 12 '19 03:02 TPucke

Running in to the same issue after upgrading to WCF 4.5.0 and .NET Core 2.1. Pretty similar configuration, NTLM over a https connection, calling custom WCF services running on .Net 4.6.2. Temporarily resolved by rolling the WCF libraries back to 4.4.2, still on .Net Core 2.1.

Also rollback to "System.ServiceModel.Http" Version="4.4.4" and now it works!!! Thank you a lot for suggestion!!!

dimalyshev avatar Apr 08 '19 05:04 dimalyshev