-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
CertificateRevocationListBuilder.Build.cs
441 lines (401 loc) · 17.9 KB
/
CertificateRevocationListBuilder.Build.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
434
435
436
437
438
439
440
441
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Formats.Asn1;
using System.Numerics;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
namespace System.Security.Cryptography.X509Certificates
{
public sealed partial class CertificateRevocationListBuilder
{
/// <summary>
/// Builds a Certificate Revocation List (CRL) signed by the specified certificate.
/// </summary>
/// <param name="issuerCertificate">
/// The certificate representing the Certificate Authority (CA) that is creating
/// this Certificate Revocation List.
/// </param>
/// <param name="crlNumber">
/// The sequence number for this CRL. Per IETF RFC 5280, this value must always
/// increase from one CRL to the next for a given CA.
/// </param>
/// <param name="nextUpdate">
/// The latest possible time before the CA will publish a newer CRL, generally
/// treated as an expiration date for this CRL.
/// </param>
/// <param name="hashAlgorithm">
/// The hash algorithm to use when signing the CRL.
/// </param>
/// <param name="rsaSignaturePadding">
/// For Certificate Authorities with RSA keys, this parameter is required and specifies
/// the RSA signature padding mode to use when signing the CRL.
/// For all other algorithms, this parameter is ignored.
/// The default is <see langword="null"/>.
/// </param>
/// <param name="thisUpdate">
/// An optional value that specifies when this CRL was created, or
/// <see langword="null"/> to use the current system time.
/// The default is <see langword="null" />.
/// </param>
/// <returns>
/// An array that contains the bytes of the signed CRL.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para>
/// <paramref name="issuerCertificate" /> is <see langword="null" />.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="hashAlgorithm" /> has <see langword="null" /> as the value of
/// <see cref="HashAlgorithmName.Name"/>.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="issuerCertificate"/> does not have an associated private key.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="issuerCertificate"/> uses a public key algorithm that is unknown,
/// or not supported by this implementation.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="issuerCertificate"/> does not have a Basic Constraints extension.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="issuerCertificate"/> has a Basic Constraints extension that indicates
/// it is not a valid Certificate Authority certificate.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="issuerCertificate"/> has a Key Usage extension that lacks the
/// <see cref="X509KeyUsageFlags.CrlSign" /> usage.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="issuerCertificate"/> has an RSA private key but
/// <paramref name="rsaSignaturePadding"/> is <see langword="null" />.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="issuerCertificate"/> has an unknown key algorithm.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="nextUpdate"/> is older than <paramref name="thisUpdate"/>.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="hashAlgorithm" /> has the empty string as the value of
/// <see cref="HashAlgorithmName.Name"/>.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="rsaSignaturePadding"/> was not recognized.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="crlNumber"/> is negative.
/// </exception>
/// <exception cref="CryptographicException">
/// an error occurred during signing.
/// </exception>
public byte[] Build(
X509Certificate2 issuerCertificate,
BigInteger crlNumber,
DateTimeOffset nextUpdate,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding? rsaSignaturePadding = null,
DateTimeOffset? thisUpdate = null)
{
return Build(
issuerCertificate,
crlNumber,
nextUpdate,
thisUpdate.GetValueOrDefault(DateTimeOffset.UtcNow),
hashAlgorithm,
rsaSignaturePadding);
}
private byte[] Build(
X509Certificate2 issuerCertificate,
BigInteger crlNumber,
DateTimeOffset nextUpdate,
DateTimeOffset thisUpdate,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding? rsaSignaturePadding)
{
ArgumentNullException.ThrowIfNull(issuerCertificate);
if (!issuerCertificate.HasPrivateKey)
throw new ArgumentException(
SR.Cryptography_CertReq_IssuerRequiresPrivateKey,
nameof(issuerCertificate));
ArgumentOutOfRangeException.ThrowIfNegative(crlNumber);
if (nextUpdate <= thisUpdate)
throw new ArgumentException(SR.Cryptography_CRLBuilder_DatesReversed);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
// Check the Basic Constraints and Key Usage extensions to help identify inappropriate certificates.
// Note that this is not a security check. The system library backing X509Chain will use these same criteria
// to determine if the CRL is valid; and a user can easily call the X509SignatureGenerator overload to
// bypass this validation. We're simply helping them at signing time understand that they've
// chosen the wrong cert.
var basicConstraints = (X509BasicConstraintsExtension?)issuerCertificate.Extensions[Oids.BasicConstraints2];
var keyUsage = (X509KeyUsageExtension?)issuerCertificate.Extensions[Oids.KeyUsage];
var subjectKeyIdentifier =
(X509SubjectKeyIdentifierExtension?)issuerCertificate.Extensions[Oids.SubjectKeyIdentifier];
if (basicConstraints == null)
{
throw new ArgumentException(
SR.Cryptography_CertReq_BasicConstraintsRequired,
nameof(issuerCertificate));
}
if (!basicConstraints.CertificateAuthority)
{
throw new ArgumentException(
SR.Cryptography_CertReq_IssuerBasicConstraintsInvalid,
nameof(issuerCertificate));
}
if (keyUsage != null && (keyUsage.KeyUsages & X509KeyUsageFlags.CrlSign) == 0)
{
throw new ArgumentException(
SR.Cryptography_CRLBuilder_IssuerKeyUsageInvalid,
nameof(issuerCertificate));
}
AsymmetricAlgorithm? key = null;
string keyAlgorithm = issuerCertificate.GetKeyAlgorithm();
X509SignatureGenerator generator;
try
{
switch (keyAlgorithm)
{
case Oids.Rsa:
if (rsaSignaturePadding is null)
{
throw new ArgumentException(SR.Cryptography_CertReq_RSAPaddingRequired);
}
RSA? rsa = issuerCertificate.GetRSAPrivateKey();
key = rsa;
generator = X509SignatureGenerator.CreateForRSA(rsa!, rsaSignaturePadding);
break;
case Oids.EcPublicKey:
ECDsa? ecdsa = issuerCertificate.GetECDsaPrivateKey();
key = ecdsa;
generator = X509SignatureGenerator.CreateForECDsa(ecdsa!);
break;
default:
throw new ArgumentException(
SR.Format(SR.Cryptography_UnknownKeyAlgorithm, keyAlgorithm),
nameof(issuerCertificate));
}
X509AuthorityKeyIdentifierExtension akid;
if (subjectKeyIdentifier is not null)
{
akid = X509AuthorityKeyIdentifierExtension.CreateFromSubjectKeyIdentifier(subjectKeyIdentifier);
}
else
{
akid = X509AuthorityKeyIdentifierExtension.CreateFromIssuerNameAndSerialNumber(
issuerCertificate.IssuerName,
issuerCertificate.SerialNumberBytes.Span);
}
return Build(
issuerCertificate.SubjectName,
generator,
crlNumber,
nextUpdate,
thisUpdate,
hashAlgorithm,
akid);
}
finally
{
key?.Dispose();
}
}
/// <summary>
/// Builds a Certificate Revocation List (CRL).
/// </summary>
/// <param name="issuerName">
/// The subject name of the certificate for the Certificate Authority (CA) that is
/// issuing this CRL.
/// </param>
/// <param name="generator">
/// A signature generator to produce the CA signature for this CRL.
/// </param>
/// <param name="crlNumber">
/// The sequence number for this CRL. Per IETF RFC 5280, this value must always
/// increase from one CRL to the next for a given CA.
/// </param>
/// <param name="nextUpdate">
/// The latest possible time before the CA will publish a newer CRL, generally
/// treated as an expiration date for this CRL.
/// </param>
/// <param name="hashAlgorithm">
/// The hash algorithm to use when signing the CRL.
/// </param>
/// <param name="authorityKeyIdentifier">
/// The Authority Key Identifier to use in this CRL, identifying the CA certificate.
/// </param>
/// <param name="thisUpdate">
/// An optional value that specifies when this CRL was created, or
/// <see langword="null" /> to use the current system time.
/// The default is <see langword="null" />.
/// </param>
/// <returns>
/// An array that contains the bytes of the signed CRL.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para>
/// <paramref name="issuerName" />, <paramref name="generator" />, or
/// <paramref name="authorityKeyIdentifier" /> is <see langword="null" />.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="hashAlgorithm" /> has <see langword="null" /> as the value of
/// <see cref="HashAlgorithmName.Name"/>.
/// </para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="nextUpdate"/> is older than <paramref name="thisUpdate"/>.
/// </para>
/// <para>- or -</para>
/// <para>
/// <paramref name="hashAlgorithm" /> has the empty string as the value of
/// <see cref="HashAlgorithmName.Name"/>.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="crlNumber"/> is negative.
/// </exception>
/// <exception cref="CryptographicException">
/// an error occurred during signing.
/// </exception>
public byte[] Build(
X500DistinguishedName issuerName,
X509SignatureGenerator generator,
BigInteger crlNumber,
DateTimeOffset nextUpdate,
HashAlgorithmName hashAlgorithm,
X509AuthorityKeyIdentifierExtension authorityKeyIdentifier,
DateTimeOffset? thisUpdate = null)
{
return Build(
issuerName,
generator,
crlNumber,
nextUpdate,
thisUpdate.GetValueOrDefault(DateTimeOffset.UtcNow),
hashAlgorithm,
authorityKeyIdentifier);
}
private byte[] Build(
X500DistinguishedName issuerName,
X509SignatureGenerator generator,
BigInteger crlNumber,
DateTimeOffset nextUpdate,
DateTimeOffset thisUpdate,
HashAlgorithmName hashAlgorithm,
X509AuthorityKeyIdentifierExtension authorityKeyIdentifier)
{
ArgumentNullException.ThrowIfNull(issuerName);
ArgumentNullException.ThrowIfNull(generator);
ArgumentOutOfRangeException.ThrowIfNegative(crlNumber);
if (nextUpdate <= thisUpdate)
throw new ArgumentException(SR.Cryptography_CRLBuilder_DatesReversed);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(authorityKeyIdentifier);
byte[] signatureAlgId = generator.GetSignatureAlgorithmIdentifier(hashAlgorithm);
{
AlgorithmIdentifierAsn signatureAlgorithmAsn;
// Deserialization also does validation of the value (except for Parameters,
// which have to be validated separately).
signatureAlgorithmAsn = AlgorithmIdentifierAsn.Decode(signatureAlgId, AsnEncodingRules.DER);
if (signatureAlgorithmAsn.Parameters.HasValue)
{
Helpers.ValidateDer(signatureAlgorithmAsn.Parameters.GetValueOrDefault().Span);
}
}
AsnWriter writer = (_writer ??= new AsnWriter(AsnEncodingRules.DER));
writer.Reset();
// TBSCertList
using (writer.PushSequence())
{
// version v2(1)
writer.WriteInteger(1);
// signature (AlgorithmIdentifier)
writer.WriteEncodedValue(signatureAlgId);
// issuer
writer.WriteEncodedValue(issuerName.RawData);
// thisUpdate
WriteX509Time(writer, thisUpdate);
// nextUpdate
WriteX509Time(writer, nextUpdate);
// revokedCertificates (don't write down if empty)
if (_revoked.Count > 0)
{
// SEQUENCE OF
using (writer.PushSequence())
{
foreach (RevokedCertificate revoked in _revoked)
{
// Anonymous CRL Entry type
using (writer.PushSequence())
{
writer.WriteInteger(revoked.Serial);
WriteX509Time(writer, revoked.RevocationTime);
if (revoked.Extensions is not null)
{
writer.WriteEncodedValue(revoked.Extensions);
}
}
}
}
}
// extensions [0] EXPLICIT Extensions
using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0)))
{
// Extensions (SEQUENCE OF)
using (writer.PushSequence())
{
// Authority Key Identifier Extension
using (writer.PushSequence())
{
writer.WriteObjectIdentifier(authorityKeyIdentifier.Oid!.Value!);
if (authorityKeyIdentifier.Critical)
{
writer.WriteBoolean(true);
}
byte[] encodedAkid = authorityKeyIdentifier.RawData;
Helpers.ValidateDer(encodedAkid);
writer.WriteOctetString(encodedAkid);
}
// CRL Number Extension
using (writer.PushSequence())
{
writer.WriteObjectIdentifier(Oids.CrlNumber);
using (writer.PushOctetString())
{
writer.WriteInteger(crlNumber);
}
}
}
}
}
byte[] tbsCertList = writer.Encode();
writer.Reset();
byte[] signature = generator.SignData(tbsCertList, hashAlgorithm);
// CertificateList
using (writer.PushSequence())
{
writer.WriteEncodedValue(tbsCertList);
writer.WriteEncodedValue(signatureAlgId);
writer.WriteBitString(signature);
}
byte[] crl = writer.Encode();
return crl;
}
}
}