| | | 1 | | using System.Security.Cryptography.X509Certificates; |
| | | 2 | | using System.Text.Encodings.Web; |
| | | 3 | | using Kestrun.Hosting; |
| | | 4 | | using Microsoft.AspNetCore.Authentication; |
| | | 5 | | using Microsoft.AspNetCore.Authentication.Certificate; |
| | | 6 | | using Microsoft.Extensions.Options; |
| | | 7 | | using System.Security.Claims; |
| | | 8 | | |
| | | 9 | | namespace Kestrun.Authentication; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Handles Client Certificate Authentication for HTTP requests. |
| | | 13 | | /// </summary> |
| | | 14 | | public class ClientCertificateAuthHandler : AuthenticationHandler<ClientCertificateAuthenticationOptions>, IAuthHandler |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// The Kestrun host instance. |
| | | 18 | | /// </summary> |
| | 32 | 19 | | public KestrunHost Host { get; private set; } |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Initializes a new instance of the <see cref="ClientCertificateAuthHandler"/> class. |
| | | 23 | | /// </summary> |
| | | 24 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 25 | | /// <param name="options">The options for Client Certificate Authentication.</param> |
| | | 26 | | /// <param name="loggerFactory">The logger factory.</param> |
| | | 27 | | /// <param name="encoder">The URL encoder.</param> |
| | | 28 | | public ClientCertificateAuthHandler( |
| | | 29 | | KestrunHost host, |
| | | 30 | | IOptionsMonitor<ClientCertificateAuthenticationOptions> options, |
| | | 31 | | ILoggerFactory loggerFactory, |
| | | 32 | | UrlEncoder encoder) |
| | 8 | 33 | | : base(options, loggerFactory, encoder) |
| | | 34 | | { |
| | 8 | 35 | | ArgumentNullException.ThrowIfNull(host); |
| | 8 | 36 | | Host = host; |
| | | 37 | | |
| | 8 | 38 | | if (Host.Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug)) |
| | | 39 | | { |
| | 8 | 40 | | Host.Logger.Debug("ClientCertificateAuthHandler initialized"); |
| | | 41 | | } |
| | 8 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Handles the authentication process for Client Certificate Authentication. |
| | | 46 | | /// </summary> |
| | | 47 | | /// <returns>A task representing the authentication result.</returns> |
| | | 48 | | protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
| | | 49 | | { |
| | | 50 | | try |
| | | 51 | | { |
| | | 52 | | // Get the client certificate |
| | 8 | 53 | | var clientCertificate = await Context.Connection.GetClientCertificateAsync(); |
| | | 54 | | |
| | 8 | 55 | | if (clientCertificate == null) |
| | | 56 | | { |
| | 1 | 57 | | Host.Logger.Warning("No client certificate provided"); |
| | 1 | 58 | | return AuthenticateResult.NoResult(); |
| | | 59 | | } |
| | | 60 | | |
| | | 61 | | // Validate the certificate using built-in validation |
| | 7 | 62 | | var certificateValidator = new CertificateValidator(Options); |
| | 7 | 63 | | var (Success, FailureMessage) = await certificateValidator.ValidateAsync(clientCertificate); |
| | | 64 | | |
| | 7 | 65 | | if (!Success) |
| | | 66 | | { |
| | 4 | 67 | | Host.Logger.Warning("Certificate validation failed: {Reason}", FailureMessage); |
| | 4 | 68 | | return AuthenticateResult.Fail(FailureMessage ?? "Certificate validation failed"); |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | // Build the claims identity |
| | 3 | 72 | | var claims = new List<Claim> |
| | 3 | 73 | | { |
| | 3 | 74 | | new(ClaimTypes.NameIdentifier, clientCertificate.Subject, ClaimValueTypes.String, Options.ClaimsIssuer), |
| | 3 | 75 | | new(ClaimTypes.Name, clientCertificate.Subject, ClaimValueTypes.String, Options.ClaimsIssuer), |
| | 3 | 76 | | // Add thumbprint as a claim |
| | 3 | 77 | | new("thumbprint", clientCertificate.Thumbprint, ClaimValueTypes.String, Options.ClaimsIssuer), |
| | 3 | 78 | | |
| | 3 | 79 | | // Add issuer and serial number |
| | 3 | 80 | | new("issuer", clientCertificate.Issuer, ClaimValueTypes.String, Options.ClaimsIssuer), |
| | 3 | 81 | | new("serialnumber", clientCertificate.SerialNumber ?? string.Empty, ClaimValueTypes.String, Options.Clai |
| | 3 | 82 | | }; |
| | | 83 | | |
| | | 84 | | // Create identity and principal |
| | 3 | 85 | | var identity = new ClaimsIdentity(claims, Scheme.Name); |
| | 3 | 86 | | var principal = new ClaimsPrincipal(identity); |
| | | 87 | | |
| | | 88 | | // Invoke the OnAuthenticationSucceeded event if configured |
| | 3 | 89 | | if (Options.Events is CertificateAuthenticationEvents certEvents) |
| | | 90 | | { |
| | 0 | 91 | | var certValidatedContext = new CertificateValidatedContext(Context, Scheme, Options) |
| | 0 | 92 | | { |
| | 0 | 93 | | Principal = principal |
| | 0 | 94 | | }; |
| | | 95 | | |
| | 0 | 96 | | await certEvents.CertificateValidated(certValidatedContext); |
| | | 97 | | |
| | 0 | 98 | | if (certValidatedContext.Result != null) |
| | | 99 | | { |
| | 0 | 100 | | return certValidatedContext.Result; |
| | | 101 | | } |
| | | 102 | | |
| | 0 | 103 | | principal = certValidatedContext.Principal ?? principal; |
| | 0 | 104 | | } |
| | | 105 | | |
| | 3 | 106 | | Host.Logger.Information("Client certificate authentication succeeded for subject: {Subject}", clientCertific |
| | | 107 | | |
| | 3 | 108 | | var ticket = new AuthenticationTicket(principal, Scheme.Name); |
| | 3 | 109 | | return AuthenticateResult.Success(ticket); |
| | | 110 | | } |
| | 0 | 111 | | catch (Exception ex) |
| | | 112 | | { |
| | 0 | 113 | | Host.Logger.Error(ex, "Error processing Client Certificate Authentication"); |
| | 0 | 114 | | return AuthenticateResult.Fail("Exception during authentication"); |
| | | 115 | | } |
| | 8 | 116 | | } |
| | | 117 | | |
| | | 118 | | /// <summary> |
| | | 119 | | /// Handles the challenge response for Client Certificate Authentication. |
| | | 120 | | /// </summary> |
| | | 121 | | /// <param name="properties">The authentication properties.</param> |
| | | 122 | | protected override Task HandleChallengeAsync(AuthenticationProperties properties) |
| | | 123 | | { |
| | 0 | 124 | | Response.StatusCode = StatusCodes.Status401Unauthorized; |
| | 0 | 125 | | return Task.CompletedTask; |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Handles the forbidden response for Client Certificate Authentication. |
| | | 130 | | /// </summary> |
| | | 131 | | /// <param name="properties">The authentication properties.</param> |
| | | 132 | | protected override Task HandleForbiddenAsync(AuthenticationProperties properties) |
| | | 133 | | { |
| | 0 | 134 | | Response.StatusCode = StatusCodes.Status403Forbidden; |
| | 0 | 135 | | return Task.CompletedTask; |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Helper class to validate X509 certificates. |
| | | 140 | | /// </summary> |
| | | 141 | | /// <param name="options">The client certificate authentication options.</param> |
| | 7 | 142 | | private class CertificateValidator(ClientCertificateAuthenticationOptions options) |
| | | 143 | | { |
| | 7 | 144 | | private readonly ClientCertificateAuthenticationOptions _options = options; |
| | | 145 | | |
| | | 146 | | private const string ClientAuthenticationOid = "1.3.6.1.5.5.7.3.2"; |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Validates the specified certificate according to the configured options. |
| | | 150 | | /// </summary> |
| | | 151 | | /// <param name="certificate">The X509 certificate to validate.</param> |
| | | 152 | | /// <returns>A task that represents the asynchronous validation operation. The task result contains a tuple indi |
| | | 153 | | public Task<(bool Success, string? FailureMessage)> ValidateAsync(X509Certificate2 certificate) |
| | | 154 | | { |
| | 7 | 155 | | ArgumentNullException.ThrowIfNull(certificate); |
| | | 156 | | |
| | 7 | 157 | | var result = ValidateAllowedCertificateTypes(certificate); |
| | 7 | 158 | | if (!result.Success) |
| | | 159 | | { |
| | 1 | 160 | | return Task.FromResult(result); |
| | | 161 | | } |
| | | 162 | | |
| | 6 | 163 | | result = ValidateValidityPeriod(certificate); |
| | 6 | 164 | | if (!result.Success) |
| | | 165 | | { |
| | 2 | 166 | | return Task.FromResult(result); |
| | | 167 | | } |
| | | 168 | | |
| | 4 | 169 | | result = ValidateCertificateUse(certificate); |
| | 4 | 170 | | if (!result.Success) |
| | | 171 | | { |
| | 1 | 172 | | return Task.FromResult(result); |
| | | 173 | | } |
| | | 174 | | |
| | 3 | 175 | | result = ValidateRevocation(certificate); |
| | 3 | 176 | | return Task.FromResult(result); |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Validates that the certificate type (self-signed vs chained) is allowed by the configured options. |
| | | 181 | | /// </summary> |
| | | 182 | | /// <param name="certificate">The certificate to validate.</param> |
| | | 183 | | /// <returns>Success when allowed; otherwise a failure with a message.</returns> |
| | | 184 | | private (bool Success, string? FailureMessage) ValidateAllowedCertificateTypes(X509Certificate2 certificate) |
| | | 185 | | { |
| | 7 | 186 | | if (_options.AllowedCertificateTypes == CertificateTypes.All) |
| | | 187 | | { |
| | 5 | 188 | | return (true, null); |
| | | 189 | | } |
| | | 190 | | |
| | 2 | 191 | | var isSelfSigned = string.Equals(certificate.Subject, certificate.Issuer, StringComparison.Ordinal); |
| | 2 | 192 | | var isAllowed = _options.AllowedCertificateTypes switch |
| | 2 | 193 | | { |
| | 1 | 194 | | CertificateTypes.Chained => !isSelfSigned, |
| | 1 | 195 | | CertificateTypes.SelfSigned => isSelfSigned, |
| | 0 | 196 | | _ => true |
| | 2 | 197 | | }; |
| | | 198 | | |
| | 2 | 199 | | return isAllowed |
| | 2 | 200 | | ? (true, null) |
| | 2 | 201 | | : (false, $"Certificate type not allowed: {(isSelfSigned ? "SelfSigned" : "Chained")}"); |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | /// <summary> |
| | | 205 | | /// Validates that the certificate is within its validity period when enabled. |
| | | 206 | | /// </summary> |
| | | 207 | | /// <param name="certificate">The certificate to validate.</param> |
| | | 208 | | /// <returns>Success when valid or validation is disabled; otherwise a failure with a message.</returns> |
| | | 209 | | private (bool Success, string? FailureMessage) ValidateValidityPeriod(X509Certificate2 certificate) |
| | | 210 | | { |
| | 6 | 211 | | if (!_options.ValidateValidityPeriod) |
| | | 212 | | { |
| | 4 | 213 | | return (true, null); |
| | | 214 | | } |
| | | 215 | | |
| | 2 | 216 | | var now = DateTime.UtcNow; |
| | 2 | 217 | | return certificate.NotBefore > now || certificate.NotAfter < now |
| | 2 | 218 | | ? (false, "Certificate is not within its validity period") |
| | 2 | 219 | | : (true, null); |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | /// <summary> |
| | | 223 | | /// Validates that the certificate has client authentication usage when enabled. |
| | | 224 | | /// </summary> |
| | | 225 | | /// <param name="certificate">The certificate to validate.</param> |
| | | 226 | | /// <returns>Success when usage is present or validation is disabled; otherwise a failure with a message.</retur |
| | | 227 | | private (bool Success, string? FailureMessage) ValidateCertificateUse(X509Certificate2 certificate) |
| | | 228 | | { |
| | 4 | 229 | | if (!_options.ValidateCertificateUse) |
| | | 230 | | { |
| | 3 | 231 | | return (true, null); |
| | | 232 | | } |
| | | 233 | | |
| | 1 | 234 | | return HasEnhancedKeyUsageOid(certificate, ClientAuthenticationOid) |
| | 1 | 235 | | ? (true, null) |
| | 1 | 236 | | : (false, "Certificate does not have Client Authentication usage"); |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Validates the certificate chain and revocation status when enabled by the configured options. |
| | | 241 | | /// </summary> |
| | | 242 | | /// <param name="certificate">The certificate to validate.</param> |
| | | 243 | | /// <returns>Success when valid or revocation checking is disabled; otherwise a failure with a message.</returns |
| | | 244 | | private (bool Success, string? FailureMessage) ValidateRevocation(X509Certificate2 certificate) |
| | | 245 | | { |
| | 3 | 246 | | var isSelfSigned = string.Equals(certificate.Subject, certificate.Issuer, StringComparison.Ordinal); |
| | 3 | 247 | | var hasCustomTrustStore = _options.CustomTrustStore is { Count: > 0 }; |
| | | 248 | | |
| | | 249 | | // If self-signed certificates are explicitly allowed and the caller did not supply a trust store, |
| | | 250 | | // treat the certificate as valid at the authentication layer. |
| | | 251 | | // (Chain building for self-signed end-entity certs is platform-dependent and commonly fails.) |
| | 3 | 252 | | if (isSelfSigned && !hasCustomTrustStore && |
| | 3 | 253 | | (_options.AllowedCertificateTypes == CertificateTypes.SelfSigned || |
| | 3 | 254 | | _options.AllowedCertificateTypes == CertificateTypes.All)) |
| | | 255 | | { |
| | 3 | 256 | | return (true, null); |
| | | 257 | | } |
| | | 258 | | |
| | 0 | 259 | | using var chain = new X509Chain |
| | 0 | 260 | | { |
| | 0 | 261 | | ChainPolicy = |
| | 0 | 262 | | { |
| | 0 | 263 | | RevocationMode = _options.RevocationMode, |
| | 0 | 264 | | RevocationFlag = _options.RevocationFlag |
| | 0 | 265 | | } |
| | 0 | 266 | | }; |
| | | 267 | | |
| | 0 | 268 | | if (hasCustomTrustStore) |
| | | 269 | | { |
| | 0 | 270 | | chain.ChainPolicy.CustomTrustStore.AddRange(_options.CustomTrustStore); |
| | 0 | 271 | | chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; |
| | | 272 | | } |
| | | 273 | | |
| | 0 | 274 | | if (chain.Build(certificate)) |
| | | 275 | | { |
| | 0 | 276 | | return (true, null); |
| | | 277 | | } |
| | | 278 | | |
| | 0 | 279 | | var errors = string.Join(", ", chain.ChainStatus.Select(s => |
| | 0 | 280 | | { |
| | 0 | 281 | | var info = s.StatusInformation?.Trim(); |
| | 0 | 282 | | return string.IsNullOrEmpty(info) ? s.Status.ToString() : info; |
| | 0 | 283 | | })); |
| | | 284 | | |
| | 0 | 285 | | return (false, $"Certificate chain validation failed: {errors}"); |
| | 0 | 286 | | } |
| | | 287 | | |
| | | 288 | | /// <summary> |
| | | 289 | | /// Checks whether the certificate contains the specified Enhanced Key Usage (EKU) OID. |
| | | 290 | | /// </summary> |
| | | 291 | | /// <param name="certificate">The certificate to inspect.</param> |
| | | 292 | | /// <param name="oidValue">The OID value to match.</param> |
| | | 293 | | /// <returns><c>true</c> when the EKU is present; otherwise <c>false</c>.</returns> |
| | | 294 | | private static bool HasEnhancedKeyUsageOid(X509Certificate2 certificate, string oidValue) |
| | | 295 | | { |
| | 2 | 296 | | foreach (var extension in certificate.Extensions) |
| | | 297 | | { |
| | 0 | 298 | | if (extension is not X509EnhancedKeyUsageExtension eku) |
| | | 299 | | { |
| | | 300 | | continue; |
| | | 301 | | } |
| | | 302 | | |
| | 0 | 303 | | foreach (var oid in eku.EnhancedKeyUsages) |
| | | 304 | | { |
| | 0 | 305 | | if (string.Equals(oid.Value, oidValue, StringComparison.Ordinal)) |
| | | 306 | | { |
| | 0 | 307 | | return true; |
| | | 308 | | } |
| | | 309 | | } |
| | | 310 | | } |
| | | 311 | | |
| | 1 | 312 | | return false; |
| | 0 | 313 | | } |
| | | 314 | | } |
| | | 315 | | } |