| | | 1 | | using System.Security.Cryptography.X509Certificates; |
| | | 2 | | using Microsoft.AspNetCore.DataProtection; |
| | | 3 | | using ProjectTemplate.Web.Options; |
| | | 4 | | |
| | | 5 | | namespace ProjectTemplate.Web.Extensions; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Provides extension methods for configuring the persistent ASP.NET Core Data Protection key ring. |
| | | 9 | | /// </summary> |
| | | 10 | | public static class DataProtectionServiceExtensions |
| | | 11 | | { |
| | | 12 | | private const string _keyEncryptionPasswordWithoutPathMessage = |
| | | 13 | | "ProjectTemplate:DataProtection:KeyEncryptionCertificatePassword requires KeyEncryptionCertificatePath."; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Registers Data Protection with a stable application discriminator and persistent filesystem key ring. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="services">The service collection to configure.</param> |
| | | 19 | | /// <param name="configuration">The application configuration source.</param> |
| | | 20 | | /// <param name="environment">The current hosting environment.</param> |
| | | 21 | | /// <returns>The same service collection instance for chaining.</returns> |
| | | 22 | | public static IServiceCollection AddApplicationDataProtection( |
| | | 23 | | this IServiceCollection services, |
| | | 24 | | IConfiguration configuration, |
| | | 25 | | IHostEnvironment environment) |
| | | 26 | | { |
| | 126 | 27 | | ArgumentNullException.ThrowIfNull(services); |
| | 126 | 28 | | ArgumentNullException.ThrowIfNull(configuration); |
| | 126 | 29 | | ArgumentNullException.ThrowIfNull(environment); |
| | | 30 | | |
| | 126 | 31 | | IConfigurationSection section = configuration.GetSection(ApplicationDataProtectionOptions.SectionName); |
| | | 32 | | |
| | 126 | 33 | | services |
| | 126 | 34 | | .AddOptions<ApplicationDataProtectionOptions>() |
| | 126 | 35 | | .Bind(section) |
| | 126 | 36 | | .Validate( |
| | 126 | 37 | | options => !string.IsNullOrWhiteSpace(options.ApplicationName), |
| | 126 | 38 | | "ProjectTemplate:DataProtection:ApplicationName is required.") |
| | 126 | 39 | | .Validate( |
| | 126 | 40 | | options => !string.IsNullOrWhiteSpace(options.KeyRingPath), |
| | 126 | 41 | | "ProjectTemplate:DataProtection:KeyRingPath is required.") |
| | 126 | 42 | | .Validate( |
| | 126 | 43 | | options => string.IsNullOrEmpty(options.KeyEncryptionCertificatePassword) || |
| | 126 | 44 | | !string.IsNullOrWhiteSpace(options.KeyEncryptionCertificatePath), |
| | 126 | 45 | | _keyEncryptionPasswordWithoutPathMessage) |
| | 126 | 46 | | .ValidateOnStart(); |
| | | 47 | | |
| | 126 | 48 | | ApplicationDataProtectionOptions defaults = new(); |
| | | 49 | | |
| | 126 | 50 | | string applicationName = ResolveRequiredSetting( |
| | 126 | 51 | | section[nameof(ApplicationDataProtectionOptions.ApplicationName)], |
| | 126 | 52 | | defaults.ApplicationName, |
| | 126 | 53 | | $"{ApplicationDataProtectionOptions.SectionName}:ApplicationName"); |
| | 125 | 54 | | string configuredKeyRingPath = ResolveRequiredSetting( |
| | 125 | 55 | | section[nameof(ApplicationDataProtectionOptions.KeyRingPath)], |
| | 125 | 56 | | defaults.KeyRingPath, |
| | 125 | 57 | | $"{ApplicationDataProtectionOptions.SectionName}:KeyRingPath"); |
| | 124 | 58 | | string keyRingPath = Path.IsPathFullyQualified(configuredKeyRingPath) |
| | 124 | 59 | | ? configuredKeyRingPath |
| | 124 | 60 | | : Path.GetFullPath(configuredKeyRingPath, environment.ContentRootPath); |
| | | 61 | | |
| | 124 | 62 | | IDataProtectionBuilder dataProtectionBuilder = services |
| | 124 | 63 | | .AddDataProtection() |
| | 124 | 64 | | .SetApplicationName(applicationName) |
| | 124 | 65 | | .PersistKeysToFileSystem(new DirectoryInfo(keyRingPath)); |
| | | 66 | | |
| | 124 | 67 | | string? configuredCertificatePath = section[nameof(ApplicationDataProtectionOptions.KeyEncryptionCertificatePath |
| | 124 | 68 | | string? configuredCertificatePassword = section[nameof(ApplicationDataProtectionOptions.KeyEncryptionCertificate |
| | | 69 | | |
| | 124 | 70 | | if (!string.IsNullOrWhiteSpace(configuredCertificatePath)) |
| | | 71 | | { |
| | 3 | 72 | | X509Certificate2 keyEncryptionCertificate = LoadKeyEncryptionCertificate( |
| | 3 | 73 | | configuredCertificatePath.Trim(), |
| | 3 | 74 | | configuredCertificatePassword, |
| | 3 | 75 | | environment.ContentRootPath); |
| | | 76 | | |
| | | 77 | | // ProtectKeysWithCertificate encrypts new keys. UnprotectKeysWithAnyCertificate supplies the same |
| | | 78 | | // certificate for decryption, which is required on Linux and macOS where the framework cannot resolve it |
| | | 79 | | // from a certificate store by thumbprint. |
| | 2 | 80 | | _ = dataProtectionBuilder |
| | 2 | 81 | | .ProtectKeysWithCertificate(keyEncryptionCertificate) |
| | 2 | 82 | | .UnprotectKeysWithAnyCertificate(keyEncryptionCertificate); |
| | | 83 | | } |
| | | 84 | | |
| | 123 | 85 | | return services; |
| | | 86 | | } |
| | | 87 | | |
| | | 88 | | private static string ResolveRequiredSetting( |
| | | 89 | | string? configuredValue, |
| | | 90 | | string defaultValue, |
| | | 91 | | string settingName) |
| | | 92 | | { |
| | 251 | 93 | | return configuredValue switch |
| | 251 | 94 | | { |
| | 1 | 95 | | null => defaultValue, |
| | 250 | 96 | | var value when string.IsNullOrWhiteSpace(value) => |
| | 2 | 97 | | throw new InvalidOperationException($"{settingName} is required."), |
| | 248 | 98 | | var value => value.Trim() |
| | 251 | 99 | | }; |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | private static X509Certificate2 LoadKeyEncryptionCertificate( |
| | | 103 | | string configuredCertificatePath, |
| | | 104 | | string? password, |
| | | 105 | | string contentRootPath) |
| | | 106 | | { |
| | 3 | 107 | | string certificatePath = Path.IsPathFullyQualified(configuredCertificatePath) |
| | 3 | 108 | | ? configuredCertificatePath |
| | 3 | 109 | | : Path.GetFullPath(configuredCertificatePath, contentRootPath); |
| | | 110 | | |
| | 3 | 111 | | if (!File.Exists(certificatePath)) |
| | | 112 | | { |
| | 1 | 113 | | throw new InvalidOperationException( |
| | 1 | 114 | | $"ProjectTemplate:DataProtection:KeyEncryptionCertificatePath '{certificatePath}' was not found."); |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | // EphemeralKeySet avoids writing the private key to the user profile or machine key store. macOS does not |
| | | 118 | | // support ephemeral key sets, so the default storage is used there. |
| | 2 | 119 | | X509KeyStorageFlags keyStorageFlags = OperatingSystem.IsMacOS() |
| | 2 | 120 | | ? X509KeyStorageFlags.DefaultKeySet |
| | 2 | 121 | | : X509KeyStorageFlags.EphemeralKeySet; |
| | | 122 | | |
| | 2 | 123 | | X509Certificate2 certificate = X509CertificateLoader.LoadPkcs12FromFile( |
| | 2 | 124 | | certificatePath, |
| | 2 | 125 | | password, |
| | 2 | 126 | | keyStorageFlags); |
| | | 127 | | |
| | 2 | 128 | | if (!certificate.HasPrivateKey) |
| | | 129 | | { |
| | 0 | 130 | | certificate.Dispose(); |
| | 0 | 131 | | throw new InvalidOperationException( |
| | 0 | 132 | | "ProjectTemplate:DataProtection:KeyEncryptionCertificatePath must reference a certificate that includes |
| | | 133 | | } |
| | | 134 | | |
| | 2 | 135 | | return certificate; |
| | | 136 | | } |
| | | 137 | | } |