-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathDefaultCertificateLoader.cs
277 lines (248 loc) · 12.2 KB
/
DefaultCertificateLoader.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography.X509Certificates;
using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
using Azure.Security.KeyVault.Secrets;
namespace Microsoft.Identity.Web
{
/// <summary>
/// Certificate Loader.
/// Only use when loading a certificate from a daemon application, or an ASP NET app, using MSAL .NET directly.
/// For an ASP NET Core app, <b>Microsoft Identity Web will handle the certificate loading</b> for you.
/// <example><code>
/// IConfidentialClientApplication app;
/// ICertificateLoader certificateLoader = new DefaultCertificateLoader();
/// certificateLoader.LoadIfNeeded(config.CertificateDescription);
///
/// app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
/// .WithCertificate(config.CertificateDescription.Certificate)
/// .WithAuthority(new Uri(config.Authority))
/// .Build();
/// </code></example>
/// </summary>
public class DefaultCertificateLoader : ICertificateLoader
{
/// <summary>
/// User assigned managed identity client ID (as opposed to system assigned managed identity)
/// See https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-manage-ua-identity-portal.
/// </summary>
public static string? UserAssignedManagedIdentityClientId { get; set; }
/// <summary>
/// Load the certificate from the description, if needed.
/// </summary>
/// <param name="certificateDescription">Description of the certificate.</param>
public void LoadIfNeeded(CertificateDescription certificateDescription)
{
if (certificateDescription == null)
{
throw new ArgumentNullException(nameof(certificateDescription));
}
if (certificateDescription.Certificate == null)
{
switch (certificateDescription.SourceType)
{
case CertificateSource.KeyVault:
certificateDescription.Certificate = LoadFromKeyVault(
certificateDescription.Container!,
certificateDescription.ReferenceOrValue!,
certificateDescription.X509KeyStorageFlags!);
break;
case CertificateSource.Base64Encoded:
certificateDescription.Certificate = LoadFromBase64Encoded(
certificateDescription.ReferenceOrValue!,
certificateDescription.X509KeyStorageFlags!);
break;
case CertificateSource.Path:
certificateDescription.Certificate = LoadFromPath(
certificateDescription.Container!,
certificateDescription.ReferenceOrValue!);
break;
case CertificateSource.StoreWithThumbprint:
certificateDescription.Certificate = LoadFromStoreWithThumbprint(
certificateDescription.ReferenceOrValue!,
certificateDescription.Container!);
break;
case CertificateSource.StoreWithDistinguishedName:
certificateDescription.Certificate = LoadFromStoreWithDistinguishedName(
certificateDescription.ReferenceOrValue!,
certificateDescription.Container!);
break;
default:
break;
}
}
}
private static X509Certificate2 LoadFromBase64Encoded(string certificateBase64, X509KeyStorageFlags x509KeyStorageFlags)
{
byte[] decoded = Convert.FromBase64String(certificateBase64);
return new X509Certificate2(
decoded,
(string?)null,
x509KeyStorageFlags);
}
/// <summary>
/// Load a certificate from Key Vault, including the private key.
/// </summary>
/// <param name="keyVaultUrl">URL of Key Vault.</param>
/// <param name="certificateName">Name of the certificate.</param>
/// <param name="x509KeyStorageFlags">Defines where and how to import the private key of an X.509 certificate.</param>
/// <returns>An <see cref="X509Certificate2"/> certificate.</returns>
/// <remarks>This code is inspired by Heath Stewart's code in:
/// https://github.com/heaths/azsdk-sample-getcert/blob/master/Program.cs#L46-L82.
/// </remarks>
private static X509Certificate2 LoadFromKeyVault(
string keyVaultUrl,
string certificateName,
X509KeyStorageFlags x509KeyStorageFlags)
{
Uri keyVaultUri = new Uri(keyVaultUrl);
DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions();
options.ManagedIdentityClientId = UserAssignedManagedIdentityClientId;
DefaultAzureCredential credential = new DefaultAzureCredential(options);
CertificateClient certificateClient = new CertificateClient(keyVaultUri, credential);
SecretClient secretClient = new SecretClient(keyVaultUri, credential);
KeyVaultCertificateWithPolicy certificate = certificateClient.GetCertificate(certificateName);
// Return a certificate with only the public key if the private key is not exportable.
if (certificate.Policy?.Exportable != true)
{
return new X509Certificate2(
certificate.Cer,
(string?)null,
x509KeyStorageFlags);
}
// Parse the secret ID and version to retrieve the private key.
string[] segments = certificate.SecretId.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length != 3)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
IDWebErrorMessage.IncorrectNumberOfUriSegments,
segments.Length,
certificate.SecretId));
}
string secretName = segments[1];
string secretVersion = segments[2];
KeyVaultSecret secret = secretClient.GetSecret(secretName, secretVersion);
// For PEM, you'll need to extract the base64-encoded message body.
// .NET 5.0 preview introduces the System.Security.Cryptography.PemEncoding class to make this easier.
if (Constants.MediaTypePksc12.Equals(secret.Properties.ContentType, StringComparison.InvariantCultureIgnoreCase))
{
return LoadFromBase64Encoded(secret.Value, x509KeyStorageFlags);
}
throw new NotSupportedException(
string.Format(
CultureInfo.InvariantCulture,
IDWebErrorMessage.OnlyPkcs12IsSupported,
secret.Properties.ContentType));
}
private static X509Certificate2? LoadFromStoreWithThumbprint(
string certificateThumbprint,
string storeDescription = Constants.PersonalUserCertificateStorePath)
{
StoreLocation certificateStoreLocation = StoreLocation.CurrentUser;
StoreName certificateStoreName = StoreName.My;
ParseStoreLocationAndName(
storeDescription,
ref certificateStoreLocation,
ref certificateStoreName);
X509Certificate2? cert;
using (X509Store x509Store = new X509Store(
certificateStoreName,
certificateStoreLocation))
{
cert = FindCertificateByCriterium(
x509Store,
X509FindType.FindByThumbprint,
certificateThumbprint);
}
return cert;
}
private static X509Certificate2? LoadFromStoreWithDistinguishedName(
string certificateSubjectDistinguishedName,
string storeDescription = Constants.PersonalUserCertificateStorePath)
{
StoreLocation certificateStoreLocation = StoreLocation.CurrentUser;
StoreName certificateStoreName = StoreName.My;
ParseStoreLocationAndName(
storeDescription,
ref certificateStoreLocation,
ref certificateStoreName);
X509Certificate2? cert;
using (X509Store x509Store = new X509Store(
certificateStoreName,
certificateStoreLocation))
{
cert = FindCertificateByCriterium(
x509Store,
X509FindType.FindBySubjectDistinguishedName,
certificateSubjectDistinguishedName);
}
return cert;
}
private static X509Certificate2 LoadFromPath(
string certificateFileName,
string? password = null)
{
return new X509Certificate2(
certificateFileName,
password,
X509KeyStorageFlags.EphemeralKeySet);
}
private static void ParseStoreLocationAndName(
string storeDescription,
ref StoreLocation certificateStoreLocation,
ref StoreName certificateStoreName)
{
string[] path = storeDescription.Split('/');
if (path.Length != 2
|| !Enum.TryParse<StoreLocation>(path[0], true, out certificateStoreLocation)
|| !Enum.TryParse<StoreName>(path[1], true, out certificateStoreName))
{
throw new ArgumentException(string.Format(
CultureInfo.InvariantCulture,
IDWebErrorMessage.InvalidCertificateStorePath,
string.Join("', '", typeof(StoreName).GetEnumNames())));
}
}
/// <summary>
/// Find a certificate by criteria.
/// </summary>
private static X509Certificate2? FindCertificateByCriterium(
X509Store x509Store,
X509FindType identifierCriterium,
string certificateIdentifier)
{
x509Store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = x509Store.Certificates;
// Find unexpired certificates.
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
// From the collection of unexpired certificates, find the ones with the correct name.
X509Certificate2Collection signingCert = currentCerts.Find(identifierCriterium, certificateIdentifier, false);
// Return the first certificate in the collection, has the right name and is current.
var cert = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore).FirstOrDefault();
return cert;
}
internal /*for test only*/ static X509Certificate2? LoadFirstCertificate(IEnumerable<CertificateDescription> certificateDescription)
{
DefaultCertificateLoader defaultCertificateLoader = new DefaultCertificateLoader();
CertificateDescription certDescription = certificateDescription.First();
defaultCertificateLoader.LoadIfNeeded(certDescription);
return certDescription.Certificate;
}
internal /*for test only*/ static IEnumerable<X509Certificate2?> LoadAllCertificates(IEnumerable<CertificateDescription> certificateDescriptions)
{
DefaultCertificateLoader defaultCertificateLoader = new DefaultCertificateLoader();
foreach (var certDescription in certificateDescriptions)
{
defaultCertificateLoader.LoadIfNeeded(certDescription);
yield return certDescription.Certificate;
}
}
}
}