runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Kerberos GSSAPI operation failed when running in Linux container

Open undecided2013 opened this issue 6 years ago • 11 comments

I am creating a new issue per

https://github.com/dotnet/corefx/issues/32291#issuecomment-578281670

Attempting to use .net core 3.1 on linux container for which a valid krb5.conf configuration exists.

Code uses HttpClient like this:

            var handler = new HttpClientHandler
            {
                PreAuthenticate = true,
                Credentials = new NetworkCredential("[email protected]", Environment.GetEnvironmentVariable("SVC_PASSWORD")),
                AllowAutoRedirect = true
             };

   using (HttpClient client = new HttpClient(handler))
            {
 using (var response = client.GetAsync(@"http://someservice"))
                {
                    string apiResponse = response.Result.Content.ReadAsStringAsync().Result;
                    return apiResponse;
                }
            }

This results in an exception:

System.AggregateException: One or more errors occurred. (GSSAPI operation failed with error - Unspecified GSS failure.  Minor code may provide more information (KDC reply did not match expectations).)
 ---> System.ComponentModel.Win32Exception (0x80090020): GSSAPI operation failed with error - Unspecified GSS failure.  Minor code may provide more information (KDC reply did not match expectations).
   at System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle(String package, Boolean isServer, NetworkCredential credential) in /_/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs:line 510
   at System.Net.NTAuthentication.Initialize(Boolean isServer, String package, NetworkCredential credential, String spn, ContextFlagsPal requestedContextFlags, ChannelBinding channelBinding) in /_/src/Common/src/System/Net/NTAuthentication.Common.cs:line 125
   at System.Net.Http.AuthenticationHelper.SendWithNtAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean isProxyAuth, HttpConnection connection, HttpConnectionPool connectionPool, CancellationToken cancellationToken) in /_/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs:line 123
   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) in /_/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs:line 563
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) in /_/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs:line 537
   at System.Net.Http.AuthenticationHelper.SendWithAuthAsync(HttpRequestMessage request, Uri authUri, ICredentials credentials, Boolean preAuthenticate, Boolean isProxyAuth, Boolean doRequestAuth, HttpConnectionPool pool, CancellationToken cancellationToken) in /_/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.cs:line 240
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /_/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs:line 33
   at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /_/src/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs:line 60
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) in /_/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:line 521
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) in /_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs:line 491
   at System.Threading.Tasks.Task`1.get_Result() in /_/src/System.Private.CoreLib/shared/System/Threading/Tasks/Future.cs:line 461
   at Firm.IS.WireInstructionService.Controllers.KerberosTestController.Get() in /app/cam2wiregen/Firm.IS.WireInstructionService/Controllers/KerberosTestController.cs:line 69
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Thanks

undecided2013 avatar Jan 24 '20 22:01 undecided2013

To add some more information to this. I used curl from the terminal and it operated properly. I had to:

  1. kinit -V [principalname]
  2. Enter password Got response 'Authenticated to Kerberos v5'
  3. curl -v -k -i --anyauth -u : [url]

Looks like curl tried a bunch of things to get through: It got a 401, server was Microsoft-IIS/8.5 The authenticate headers said "Negotiate" and "NTLM" curl used "Negotiate", it sent the token and then I got the 200 response plus the expected data.

curl -V returns:

curl 7.29.0 (x86_64-redhat-linux-gnu) libcurl/7.61.1 OpenSSL/1.0.2k zlib/1.2.7 libssh2/1.8.0 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp Features: AsynchDNS IPv6 Largefile NTLM NTLM_WB SPNEGO SSL libz unix-sockets

[Edit] See below. curl works after kinit is done with username/pass OR keytab.

undecided2013 avatar Jan 27 '20 18:01 undecided2013

I had to re-open this because it seems that there is a bug lurking in there somewhere. So, found out that i had to call kinit to authenticate the default user prior to launching the dot net service using dotnet run.. So, I did this: kinit -V -t /opt/container/$SVC_USERNAME.keytab $SVC_USERNAME

Interestingly enough, the 1st call into my test controller fails with the above exception

System.AggregateException: One or more errors occurred. (GSSAPI operation failed with error - Unspecified GSS failure. Minor code may provide more information (KDC reply did not match expectations).)
---> System.ComponentModel.Win32Exception (0x80090020): GSSAPI operation failed with error - Unspecified GSS failure. Minor code may provide more information (KDC reply did not match expectations).

Subsequent calls to the same webapi controller method work fine. It's almost as if something is initialized after the 1st call and everything works as expected.

curl does not exhibit this behaviour.

The curl command

curl -v -k -i --anyauth -u : [url]

works fine right after the kinit

undecided2013 avatar Jan 27 '20 20:01 undecided2013

Closing issue. It was the way I was using the api. With Credentials = new NetworkCredential("[email protected]", Environment.GetEnvironmentVariable("SVC_PASSWORD")), it fails on the 1st call but then works on subsequent calls. With UseDefaultCredentials = true instead of NetworkCredential, it works fine.

Not sure if this is how it is meant to work.

undecided2013 avatar Jan 27 '20 21:01 undecided2013

I am experiencing this problem again and no code changes have been made. Basically, 1st HTTPClient call fails with 401 but subsequent ones work. Same instance of the app. The HTTPClient is constructed every time the call needs to be made.

undecided2013 avatar Jan 31 '20 18:01 undecided2013

With UseDefaultCredentials = true instead of NetworkCredential, it works fine.

Not sure if this is how it is meant to work.

If you set 'UseDefaultCredentials' to true, then it will ignore any explicit NetworkCredential object you set. And it will assume that the default credentials are something that you have set via 'kinit' on the Linux machine.

The HTTPClient is constructed every time the call needs to be made.

Also, we recommend that you do not re-create the HttpClient object for every request. You should be creating it once and re-using it for subsequent requests. This is important in order to be able to reuse TCP connections, especially since Kerberos authentication schemes require connection affinity and expect to be able to re-use connections.

davidsh avatar Feb 18 '20 18:02 davidsh

Basically, 1st HTTPClient call fails with 401 but subsequent ones work.

Not sure what is happening here. But you should turn on Kerberos tracing to get more details about the problem.

You should set this environment variable before running your repro.

export KRB5_TRACE=/dev/stdout

# Run the repro

davidsh avatar Feb 18 '20 18:02 davidsh

If you set 'UseDefaultCredentials' to true, then it will ignore any explicit NetworkCredential object you set. And it will assume that the default credentials are something that you have set via 'kinit' on the Linux machine.

Correct. I am setting the ticket up with kinit. Without the kinit, it did not work at all.

undecided2013 avatar Feb 18 '20 19:02 undecided2013

Without the kinit, it did not work at all.

It might be that your explicit NetworkCredential is not formatted correctly for your Linux Kerberos environment.

This:

new NetworkCredential(
    "[email protected]",
    Environment.GetEnvironmentVariable("SVC_PASSWORD"));

might need to be done as this:

new NetworkCredential(
    "someaccount",
    Environment.GetEnvironmentVariable("SVC_PASSWORD"),
    "somedomain");

There are many variables to consider here such as exactly what the KRB5.CONF file looks like and whether multiple Kerberos domains/realms and/or Windows Active Directory is being used.

The only way to diagnose the root cause is to see a KRB5_TRACE as well as the KRB5.CONF file and understand the deeper aspects of the network topology.

davidsh avatar Feb 18 '20 20:02 davidsh

Without the kinit, it did not work at all.

It might be that your explicit NetworkCredential is not formatted correctly for your Linux Kerberos environment.

This:

new NetworkCredential(
    "[email protected]",
    Environment.GetEnvironmentVariable("SVC_PASSWORD"));

might need to be done as this:

new NetworkCredential(
    "someaccount",
    Environment.GetEnvironmentVariable("SVC_PASSWORD"),
    "somedomain");

There are many variables to consider here such as exactly what the KRB5.CONF file looks like and whether multiple Kerberos domains/realms and/or Windows Active Directory is being used.

The only way to diagnose the root cause is to see a KRB5_TRACE as well as the KRB5.CONF file and understand the deeper aspects of the network topology.

Thanks but I am not using explicit credentials any more as that was failing. I am now using the kinit along with the default credentials and it works except for the fact that the 1st call returns a 401. I will trace that sometime this week or next when I get back to that project.

undecided2013 avatar Feb 18 '20 21:02 undecided2013

I will trace that sometime this week or next when I get back to that project.

Ok. Thanks. We will await your detailed traces, etc.

davidsh avatar Feb 18 '20 22:02 davidsh

Not actionable without traces, closing. Feel free to reopen once you have traces. Thanks!

karelz avatar Mar 12 '20 00:03 karelz