/
CertificateAuthenticationHandler.cs
293 lines (244 loc) · 10.7 KB
/
CertificateAuthenticationHandler.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Encodings.Web;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication.Certificate;
internal sealed class CertificateAuthenticationHandler : AuthenticationHandler<CertificateAuthenticationOptions>
{
private static readonly Oid ClientCertificateOid = new Oid("1.3.6.1.5.5.7.3.2");
private ICertificateValidationCache? _cache;
public CertificateAuthenticationHandler(
IOptionsMonitor<CertificateAuthenticationOptions> 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>
private new CertificateAuthenticationEvents Events
{
get { return (CertificateAuthenticationEvents)base.Events!; }
set { base.Events = value; }
}
/// <summary>
/// Creates a new instance of the events instance.
/// </summary>
/// <returns>A new instance of the events instance.</returns>
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new CertificateAuthenticationEvents());
protected override Task InitializeHandlerAsync()
{
_cache = Context.RequestServices.GetService<ICertificateValidationCache>();
return base.InitializeHandlerAsync();
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// You only get client certificates over HTTPS
if (!Context.Request.IsHttps)
{
Logger.NotHttps();
return AuthenticateResult.NoResult();
}
try
{
var clientCertificate = await Context.Connection.GetClientCertificateAsync();
// This should never be the case, as cert authentication happens long before ASP.NET kicks in.
if (clientCertificate == null)
{
Logger.NoCertificate();
return AuthenticateResult.NoResult();
}
if (_cache != null)
{
var cacheHit = _cache.Get(Context, clientCertificate);
if (cacheHit != null)
{
return cacheHit;
}
}
var result = await ValidateCertificateAsync(clientCertificate);
// Invoke the failed handler if validation failed, before updating the cache
if (result.Failure != null)
{
var authenticationFailedContext = await HandleFailureAsync(result.Failure);
if (authenticationFailedContext.Result != null)
{
result = authenticationFailedContext.Result;
}
}
_cache?.Put(Context, clientCertificate, result);
return result;
}
catch (Exception ex)
{
var authenticationFailedContext = await HandleFailureAsync(ex);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
throw;
}
}
private async Task<CertificateAuthenticationFailedContext> HandleFailureAsync(Exception error)
{
var authenticationFailedContext = new CertificateAuthenticationFailedContext(Context, Scheme, Options)
{
Exception = error
};
await Events.AuthenticationFailed(authenticationFailedContext);
return authenticationFailedContext;
}
private async Task<AuthenticateResult> ValidateCertificateAsync(X509Certificate2 clientCertificate)
{
var isCertificateSelfSigned = clientCertificate.IsSelfSigned();
// If we have a self signed cert, and they're not allowed, exit early and not bother with
// any other validations.
if (isCertificateSelfSigned &&
!Options.AllowedCertificateTypes.HasFlag(CertificateTypes.SelfSigned))
{
Logger.CertificateRejected("Self signed", clientCertificate.Subject);
return AuthenticateResults.NoSelfSigned;
}
// If we have a chained cert, and they're not allowed, exit early and not bother with
// any other validations.
if (!isCertificateSelfSigned &&
!Options.AllowedCertificateTypes.HasFlag(CertificateTypes.Chained))
{
Logger.CertificateRejected("Chained", clientCertificate.Subject);
return AuthenticateResults.NoChainedCertificates;
}
var chainPolicy = BuildChainPolicy(clientCertificate, isCertificateSelfSigned);
using var chain = new X509Chain
{
ChainPolicy = chainPolicy
};
var certificateIsValid = chain.Build(clientCertificate);
if (!certificateIsValid)
{
var chainErrors = new List<string>(chain.ChainStatus.Length);
foreach (var validationFailure in chain.ChainStatus)
{
chainErrors.Add($"{validationFailure.Status} {validationFailure.StatusInformation}");
}
Logger.CertificateFailedValidation(clientCertificate.Subject, chainErrors);
return AuthenticateResults.InvalidClientCertificate;
}
var certificateValidatedContext = new CertificateValidatedContext(Context, Scheme, Options)
{
ClientCertificate = clientCertificate,
Principal = CreatePrincipal(clientCertificate)
};
await Events.CertificateValidated(certificateValidatedContext);
if (certificateValidatedContext.Result != null)
{
return certificateValidatedContext.Result;
}
certificateValidatedContext.Success();
return certificateValidatedContext.Result!;
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
var authenticationChallengedContext = new CertificateChallengeContext(Context, Scheme, Options, properties);
await Events.Challenge(authenticationChallengedContext);
if (authenticationChallengedContext.Handled)
{
return;
}
// Certificate authentication takes place at the connection level. We can't prompt once we're in
// user code, so the best thing to do is Forbid, not Challenge.
await HandleForbiddenAsync(properties);
}
private X509ChainPolicy BuildChainPolicy(X509Certificate2 certificate, bool isCertificateSelfSigned)
{
// Now build the chain validation options.
X509RevocationFlag revocationFlag = Options.RevocationFlag;
X509RevocationMode revocationMode = Options.RevocationMode;
if (isCertificateSelfSigned)
{
// Turn off chain validation, because we have a self signed certificate.
revocationFlag = X509RevocationFlag.EntireChain;
revocationMode = X509RevocationMode.NoCheck;
}
var chainPolicy = new X509ChainPolicy
{
RevocationFlag = revocationFlag,
RevocationMode = revocationMode,
};
if (Options.ValidateCertificateUse)
{
chainPolicy.ApplicationPolicy.Add(ClientCertificateOid);
}
if (isCertificateSelfSigned)
{
chainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
chainPolicy.VerificationFlags |= X509VerificationFlags.IgnoreEndRevocationUnknown;
chainPolicy.ExtraStore.Add(certificate);
}
else
{
if (Options.CustomTrustStore != null)
{
chainPolicy.CustomTrustStore.AddRange(Options.CustomTrustStore);
}
chainPolicy.TrustMode = Options.ChainTrustValidationMode;
}
chainPolicy.ExtraStore.AddRange(Options.AdditionalChainCertificates);
if (!Options.ValidateValidityPeriod)
{
chainPolicy.VerificationFlags |= X509VerificationFlags.IgnoreNotTimeValid;
}
return chainPolicy;
}
private ClaimsPrincipal CreatePrincipal(X509Certificate2 certificate)
{
var claims = new List<Claim>();
var issuer = certificate.Issuer;
claims.Add(new Claim("issuer", issuer, ClaimValueTypes.String, Options.ClaimsIssuer));
var thumbprint = certificate.Thumbprint;
claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, ClaimValueTypes.Base64Binary, Options.ClaimsIssuer));
var value = certificate.SubjectName.Name;
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.X500DistinguishedName, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
value = certificate.SerialNumber;
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.SerialNumber, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
value = certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.Dns, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
value = certificate.GetNameInfo(X509NameType.SimpleName, false);
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.Name, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
value = certificate.GetNameInfo(X509NameType.EmailName, false);
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.Email, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
value = certificate.GetNameInfo(X509NameType.UpnName, false);
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.Upn, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
value = certificate.GetNameInfo(X509NameType.UrlName, false);
if (!string.IsNullOrWhiteSpace(value))
{
claims.Add(new Claim(ClaimTypes.Uri, value, ClaimValueTypes.String, Options.ClaimsIssuer));
}
var identity = new ClaimsIdentity(claims, CertificateAuthenticationDefaults.AuthenticationScheme);
return new ClaimsPrincipal(identity);
}
}