-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
NegotiateHandler.cs
433 lines (376 loc) · 17.9 KB
/
NegotiateHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Authentication.Negotiate
{
/// <summary>
/// Authenticates requests using Negotiate, Kerberos, or NTLM.
/// </summary>
public class NegotiateHandler : AuthenticationHandler<NegotiateOptions>, IAuthenticationRequestHandler
{
private const string AuthPersistenceKey = nameof(AuthPersistence);
private const string NegotiateVerb = "Negotiate";
private const string AuthHeaderPrefix = NegotiateVerb + " ";
private bool _requestProcessed;
private INegotiateState? _negotiateState;
/// <summary>
/// Creates a new <see cref="NegotiateHandler"/>
/// </summary>
/// <inheritdoc />
public NegotiateHandler(IOptionsMonitor<NegotiateOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{ }
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new NegotiateEvents Events
{
get => (NegotiateEvents)base.Events!;
set => base.Events = value;
}
/// <summary>
/// Creates the default events type.
/// </summary>
/// <returns></returns>
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new NegotiateEvents());
private bool IsSupportedProtocol => HttpProtocol.IsHttp11(Request.Protocol) || HttpProtocol.IsHttp10(Request.Protocol);
/// <summary>
/// Intercepts incomplete Negotiate authentication handshakes and continues or completes them.
/// </summary>
/// <returns><see langword="true" /> if a response was generated, otherwise <see langword="false"/>.</returns>
public async Task<bool> HandleRequestAsync()
{
AuthPersistence? persistence = null;
bool authFailedEventCalled = false;
try
{
if (_requestProcessed || Options.DeferToServer)
{
// This request was already processed but something is re-executing it like an exception handler.
// Don't re-run because we could corrupt the connection state, e.g. if this was a stage2 NTLM request
// that we've already completed the handshake for.
// Or we're in deferral mode where we let the server handle the authentication.
return false;
}
_requestProcessed = true;
if (!IsSupportedProtocol)
{
// HTTP/1.0 and HTTP/1.1 are supported. Do not throw because this may be running on a server that supports
// additional protocols.
return false;
}
var connectionItems = GetConnectionItems();
persistence = (AuthPersistence)connectionItems[AuthPersistenceKey]!;
_negotiateState = persistence?.State;
var authorizationHeader = Request.Headers.Authorization;
if (StringValues.IsNullOrEmpty(authorizationHeader))
{
if (_negotiateState?.IsCompleted == false)
{
throw new InvalidOperationException("An anonymous request was received in between authentication handshake requests.");
}
return false;
}
var authorization = authorizationHeader.ToString();
string? token = null;
if (authorization.StartsWith(AuthHeaderPrefix, StringComparison.OrdinalIgnoreCase))
{
token = authorization.Substring(AuthHeaderPrefix.Length).Trim();
}
else
{
if (_negotiateState?.IsCompleted == false)
{
throw new InvalidOperationException("Non-negotiate request was received in between authentication handshake requests.");
}
return false;
}
// WinHttpHandler re-authenticates an existing connection if it gets another challenge on subsequent requests.
if (_negotiateState?.IsCompleted == true)
{
Logger.Reauthenticating();
_negotiateState.Dispose();
_negotiateState = null;
if (persistence != null)
{
persistence.State = null;
}
}
_negotiateState ??= Options.StateFactory.CreateInstance();
var outgoing = _negotiateState.GetOutgoingBlob(token, out var errorType, out var exception);
if (errorType != BlobErrorType.None)
{
Debug.Assert(exception != null);
Logger.NegotiateError(errorType.ToString());
_negotiateState.Dispose();
_negotiateState = null;
if (persistence?.State != null)
{
persistence.State.Dispose();
persistence.State = null;
}
if (errorType == BlobErrorType.CredentialError)
{
Logger.CredentialError(exception);
authFailedEventCalled = true; // Could throw, and we don't want to double trigger the event.
var result = await InvokeAuthenticateFailedEvent(exception);
return result ?? false; // Default to skipping the handler, let AuthZ generate a new 401
}
else if (errorType == BlobErrorType.ClientError)
{
Logger.ClientError(exception);
authFailedEventCalled = true; // Could throw, and we don't want to double trigger the event.
var result = await InvokeAuthenticateFailedEvent(exception);
if (result.HasValue)
{
return result.Value;
}
Context.Response.StatusCode = StatusCodes.Status400BadRequest;
return true; // Default to terminating request
}
throw exception;
}
if (!_negotiateState.IsCompleted)
{
persistence ??= EstablishConnectionPersistence(connectionItems);
// Save the state long enough to complete the multi-stage handshake.
// We'll remove it once complete if !PersistNtlm/KerberosCredentials.
persistence.State = _negotiateState;
Logger.IncompleteNegotiateChallenge();
Response.StatusCode = StatusCodes.Status401Unauthorized;
Response.Headers.Append(HeaderNames.WWWAuthenticate, AuthHeaderPrefix + outgoing);
return true;
}
Logger.NegotiateComplete();
// There can be a final blob of data we need to send to the client, but let the request execute as normal.
if (!string.IsNullOrEmpty(outgoing))
{
Response.OnStarting(() =>
{
// Only include it if the response ultimately succeeds. This avoids adding it twice if Challenge is called again.
if (Response.StatusCode < StatusCodes.Status400BadRequest)
{
Response.Headers.Append(HeaderNames.WWWAuthenticate, AuthHeaderPrefix + outgoing);
}
return Task.CompletedTask;
});
}
// Deal with connection credential persistence.
if (_negotiateState.Protocol == "NTLM" && !Options.PersistNtlmCredentials)
{
// NTLM was already put in the persitence cache on the prior request so we could complete the handshake.
// Take it out if we don't want it to persist.
Debug.Assert(object.ReferenceEquals(persistence?.State, _negotiateState),
"NTLM is a two stage process, it must have already been in the cache for the handshake to succeed.");
Logger.DisablingCredentialPersistence(_negotiateState.Protocol);
persistence.State = null;
Response.RegisterForDispose(_negotiateState);
}
else if (_negotiateState.Protocol == "Kerberos")
{
// Kerberos can require one or two stage handshakes
if (Options.PersistKerberosCredentials)
{
Logger.EnablingCredentialPersistence();
persistence ??= EstablishConnectionPersistence(connectionItems);
persistence.State = _negotiateState;
}
else
{
if (persistence?.State != null)
{
Logger.DisablingCredentialPersistence(_negotiateState.Protocol);
persistence.State = null;
}
Response.RegisterForDispose(_negotiateState);
}
}
// Note we run the Authenticated event in HandleAuthenticateAsync so it is per-request rather than per connection.
}
catch (Exception ex)
{
if (authFailedEventCalled)
{
throw;
}
Logger.ExceptionProcessingAuth(ex);
// Clear state so it's possible to retry on the same connection.
_negotiateState?.Dispose();
_negotiateState = null;
if (persistence?.State != null)
{
persistence.State.Dispose();
persistence.State = null;
}
var result = await InvokeAuthenticateFailedEvent(ex);
if (result.HasValue)
{
return result.Value;
}
throw;
}
return false;
}
private async Task<bool?> InvokeAuthenticateFailedEvent(Exception ex)
{
var errorContext = new AuthenticationFailedContext(Context, Scheme, Options) { Exception = ex };
await Events.AuthenticationFailed(errorContext);
if (errorContext.Result != null)
{
if (errorContext.Result.Handled)
{
return true;
}
else if (errorContext.Result.Skipped)
{
return false;
}
else if (errorContext.Result.Failure != null)
{
throw new Exception("An error was returned from the AuthenticationFailed event.", errorContext.Result.Failure);
}
}
return null;
}
/// <summary>
/// Checks if the current request is authenticated and returns the user.
/// </summary>
/// <returns></returns>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!_requestProcessed)
{
throw new InvalidOperationException("AuthenticateAsync must not be called before the UseAuthentication middleware runs.");
}
if (!IsSupportedProtocol)
{
// Not supported. We don't throw because Negotiate may be set as the default auth
// handler on a server that's running HTTP/1 and HTTP/2. We'll challenge HTTP/2 requests
// that require auth and they'll downgrade to HTTP/1.1.
Logger.ProtocolNotSupported(Request.Protocol);
return AuthenticateResult.NoResult();
}
if (_negotiateState == null)
{
return AuthenticateResult.NoResult();
}
if (!_negotiateState.IsCompleted)
{
// This case should have been rejected by HandleRequestAsync
throw new InvalidOperationException("Attempting to use an incomplete authentication context.");
}
// Make a new copy of the user for each request, they are mutable objects and
// things like ClaimsTransformation run per request.
var identity = _negotiateState.GetIdentity();
ClaimsPrincipal user;
if (OperatingSystem.IsWindows() && identity is WindowsIdentity winIdentity)
{
user = new WindowsPrincipal(winIdentity);
Response.RegisterForDispose(winIdentity);
}
else
{
user = new ClaimsPrincipal(new ClaimsIdentity(identity));
}
AuthenticatedContext authenticatedContext;
if (Options.LdapSettings.EnableLdapClaimResolution)
{
var ldapContext = new LdapContext(Context, Scheme, Options, Options.LdapSettings)
{
Principal = user
};
await Events.RetrieveLdapClaims(ldapContext);
if (ldapContext.Result != null)
{
return ldapContext.Result;
}
await LdapAdapter.RetrieveClaimsAsync(ldapContext.LdapSettings, (ldapContext.Principal.Identity as ClaimsIdentity)!, Logger);
authenticatedContext = new AuthenticatedContext(Context, Scheme, Options)
{
Principal = ldapContext.Principal
};
}
else
{
authenticatedContext = new AuthenticatedContext(Context, Scheme, Options)
{
Principal = user
};
}
await Events.Authenticated(authenticatedContext);
if (authenticatedContext.Result != null)
{
return authenticatedContext.Result;
}
var ticket = new AuthenticationTicket(authenticatedContext.Principal, authenticatedContext.Properties, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
/// <summary>
/// Issues a 401 WWW-Authenticate Negotiate challenge.
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
// We allow issuing a challenge from an HTTP/2 request. Browser clients will gracefully downgrade to HTTP/1.1.
// SocketHttpHandler will not downgrade (https://github.com/dotnet/corefx/issues/35195), but WinHttpHandler will.
var eventContext = new ChallengeContext(Context, Scheme, Options, properties);
await Events.Challenge(eventContext);
if (eventContext.Handled)
{
return;
}
Response.StatusCode = StatusCodes.Status401Unauthorized;
Response.Headers.Append(HeaderNames.WWWAuthenticate, NegotiateVerb);
Logger.ChallengeNegotiate();
}
private AuthPersistence EstablishConnectionPersistence(IDictionary<object, object?> items)
{
Debug.Assert(!items.ContainsKey(AuthPersistenceKey), "This should only be registered once per connection");
var persistence = new AuthPersistence();
RegisterForConnectionDispose(persistence);
items[AuthPersistenceKey] = persistence;
return persistence;
}
private IDictionary<object, object?> GetConnectionItems()
{
return Context.Features.Get<IConnectionItemsFeature>()?.Items
?? throw new NotSupportedException($"Negotiate authentication requires a server that supports {nameof(IConnectionItemsFeature)} like Kestrel.");
}
private void RegisterForConnectionDispose(IDisposable authState)
{
var connectionCompleteFeature = Context.Features.Get<IConnectionCompleteFeature>()
??throw new NotSupportedException($"Negotiate authentication requires a server that supports {nameof(IConnectionCompleteFeature)} like Kestrel.");
connectionCompleteFeature.OnCompleted(DisposeState, authState);
}
private static Task DisposeState(object state)
{
((IDisposable)state).Dispose();
return Task.CompletedTask;
}
// This allows us to have one disposal registration per connection and limits churn on the Items collection.
private class AuthPersistence : IDisposable
{
internal INegotiateState? State { get; set; }
public void Dispose()
{
State?.Dispose();
}
}
}
}