/
CertificateRequest.Load.cs
395 lines (341 loc) · 16.4 KB
/
CertificateRequest.Load.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Formats.Asn1;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates.Asn1;
namespace System.Security.Cryptography.X509Certificates
{
public sealed partial class CertificateRequest
{
private const CertificateRequestLoadOptions AllOptions =
CertificateRequestLoadOptions.SkipSignatureValidation |
CertificateRequestLoadOptions.UnsafeLoadCertificateExtensions;
public static CertificateRequest LoadSigningRequestPem(
string pkcs10Pem,
HashAlgorithmName signerHashAlgorithm,
CertificateRequestLoadOptions options = CertificateRequestLoadOptions.Default,
RSASignaturePadding? signerSignaturePadding = null)
{
ArgumentNullException.ThrowIfNull(pkcs10Pem);
return LoadSigningRequestPem(
pkcs10Pem.AsSpan(),
signerHashAlgorithm,
options,
signerSignaturePadding);
}
public static CertificateRequest LoadSigningRequestPem(
ReadOnlySpan<char> pkcs10Pem,
HashAlgorithmName signerHashAlgorithm,
CertificateRequestLoadOptions options = CertificateRequestLoadOptions.Default,
RSASignaturePadding? signerSignaturePadding = null)
{
ArgumentException.ThrowIfNullOrEmpty(signerHashAlgorithm.Name, nameof(signerHashAlgorithm));
if ((options & ~AllOptions) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options), options, SR.Argument_InvalidFlag);
}
foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(pkcs10Pem))
{
if (contents[fields.Label].SequenceEqual(PemLabels.Pkcs10CertificateRequest))
{
byte[] rented = ArrayPool<byte>.Shared.Rent(fields.DecodedDataLength);
if (!Convert.TryFromBase64Chars(contents[fields.Base64Data], rented, out int bytesWritten) ||
bytesWritten != fields.DecodedDataLength)
{
Debug.Fail("Base64Decode failed, but PemEncoding said it was legal");
throw new UnreachableException();
}
try
{
return LoadSigningRequest(
rented.AsSpan(0, bytesWritten),
permitTrailingData: false,
signerHashAlgorithm,
out _,
options,
signerSignaturePadding);
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}
}
}
throw new CryptographicException(
SR.Format(SR.Cryptography_NoPemOfLabel, PemLabels.Pkcs10CertificateRequest));
}
public static CertificateRequest LoadSigningRequest(
byte[] pkcs10,
HashAlgorithmName signerHashAlgorithm,
CertificateRequestLoadOptions options = CertificateRequestLoadOptions.Default,
RSASignaturePadding? signerSignaturePadding = null)
{
ArgumentNullException.ThrowIfNull(pkcs10);
return LoadSigningRequest(
pkcs10,
permitTrailingData: false,
signerHashAlgorithm,
out _,
options,
signerSignaturePadding);
}
public static CertificateRequest LoadSigningRequest(
ReadOnlySpan<byte> pkcs10,
HashAlgorithmName signerHashAlgorithm,
out int bytesConsumed,
CertificateRequestLoadOptions options = CertificateRequestLoadOptions.Default,
RSASignaturePadding? signerSignaturePadding = null)
{
return LoadSigningRequest(
pkcs10,
permitTrailingData: true,
signerHashAlgorithm,
out bytesConsumed,
options,
signerSignaturePadding);
}
private static unsafe CertificateRequest LoadSigningRequest(
ReadOnlySpan<byte> pkcs10,
bool permitTrailingData,
HashAlgorithmName signerHashAlgorithm,
out int bytesConsumed,
CertificateRequestLoadOptions options,
RSASignaturePadding? signerSignaturePadding)
{
ArgumentException.ThrowIfNullOrEmpty(signerHashAlgorithm.Name, nameof(signerHashAlgorithm));
if ((options & ~AllOptions) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options), options, SR.Argument_InvalidFlag);
}
bool skipSignatureValidation =
(options & CertificateRequestLoadOptions.SkipSignatureValidation) != 0;
bool unsafeLoadCertificateExtensions =
(options & CertificateRequestLoadOptions.UnsafeLoadCertificateExtensions) != 0;
try
{
AsnValueReader outer = new AsnValueReader(pkcs10, AsnEncodingRules.DER);
int encodedLength = outer.PeekEncodedValue().Length;
AsnValueReader pkcs10Asn = outer.ReadSequence();
CertificateRequest req;
if (!permitTrailingData)
{
outer.ThrowIfNotEmpty();
}
fixed (byte* p10ptr = pkcs10)
{
using (PointerMemoryManager<byte> manager = new PointerMemoryManager<byte>(p10ptr, encodedLength))
{
ReadOnlyMemory<byte> rebind = manager.Memory;
ReadOnlySpan<byte> encodedRequestInfo = pkcs10Asn.PeekEncodedValue();
CertificationRequestInfoAsn requestInfo;
AlgorithmIdentifierAsn algorithmIdentifier;
ReadOnlySpan<byte> signature;
int signatureUnusedBitCount;
CertificationRequestInfoAsn.Decode(ref pkcs10Asn, rebind, out requestInfo);
AlgorithmIdentifierAsn.Decode(ref pkcs10Asn, rebind, out algorithmIdentifier);
if (!pkcs10Asn.TryReadPrimitiveBitString(out signatureUnusedBitCount, out signature))
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
pkcs10Asn.ThrowIfNotEmpty();
if (requestInfo.Version < 0)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
// They haven't bumped from v0 to v1 as of 2022.
const int MaxSupportedVersion = 0;
if (requestInfo.Version != MaxSupportedVersion)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_CertReq_Load_VersionTooNew,
requestInfo.Version,
MaxSupportedVersion));
}
PublicKey publicKey = PublicKey.DecodeSubjectPublicKeyInfo(ref requestInfo.SubjectPublicKeyInfo);
if (!skipSignatureValidation)
{
// None of the supported signature algorithms support signatures that are not full bytes.
// So, shortcut the verification on the bit length
if (signatureUnusedBitCount != 0 ||
!VerifyX509Signature(encodedRequestInfo, signature, publicKey, algorithmIdentifier))
{
throw new CryptographicException(SR.Cryptography_CertReq_SignatureVerificationFailed);
}
}
X500DistinguishedName subject = new X500DistinguishedName(requestInfo.Subject.Span);
req = new CertificateRequest(
subject,
publicKey,
signerHashAlgorithm,
signerSignaturePadding);
if (requestInfo.Attributes is not null)
{
bool foundCertExt = false;
foreach (AttributeAsn attr in requestInfo.Attributes)
{
if (attr.AttrType == Oids.Pkcs9ExtensionRequest)
{
if (foundCertExt)
{
throw new CryptographicException(
SR.Cryptography_CertReq_Load_DuplicateExtensionRequests);
}
foundCertExt = true;
if (attr.AttrValues.Length != 1)
{
throw new CryptographicException(
SR.Cryptography_CertReq_Load_DuplicateExtensionRequests);
}
AsnValueReader extsReader = new AsnValueReader(
attr.AttrValues[0].Span,
AsnEncodingRules.DER);
AsnValueReader exts = extsReader.ReadSequence();
extsReader.ThrowIfNotEmpty();
// Minimum length is 1, so do..while
do
{
X509ExtensionAsn.Decode(ref exts, rebind, out X509ExtensionAsn extAsn);
if (unsafeLoadCertificateExtensions)
{
X509Extension ext = new X509Extension(
extAsn.ExtnId,
extAsn.ExtnValue.Span,
extAsn.Critical);
X509Extension? rich =
X509Certificate2.CreateCustomExtensionIfAny(extAsn.ExtnId);
if (rich is not null)
{
rich.CopyFrom(ext);
req.CertificateExtensions.Add(rich);
}
else
{
req.CertificateExtensions.Add(ext);
}
}
} while (exts.HasData);
}
else
{
if (attr.AttrValues.Length == 0)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
foreach (ReadOnlyMemory<byte> val in attr.AttrValues)
{
req.OtherRequestAttributes.Add(
new AsnEncodedData(attr.AttrType, val.Span));
}
}
}
}
}
}
bytesConsumed = encodedLength;
return req;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
private static bool VerifyX509Signature(
ReadOnlySpan<byte> toBeSigned,
ReadOnlySpan<byte> signature,
PublicKey publicKey,
AlgorithmIdentifierAsn algorithmIdentifier)
{
RSA? rsa = publicKey.GetRSAPublicKey();
ECDsa? ecdsa = publicKey.GetECDsaPublicKey();
try
{
HashAlgorithmName hashAlg;
if (algorithmIdentifier.Algorithm == Oids.RsaPss)
{
if (rsa is null || !algorithmIdentifier.Parameters.HasValue)
{
return false;
}
PssParamsAsn pssParams = PssParamsAsn.Decode(
algorithmIdentifier.Parameters.GetValueOrDefault(),
AsnEncodingRules.DER);
RSASignaturePadding padding = pssParams.GetSignaturePadding();
hashAlg = HashAlgorithmName.FromOid(pssParams.HashAlgorithm.Algorithm);
return rsa.VerifyData(
toBeSigned,
signature,
hashAlg,
padding);
}
switch (algorithmIdentifier.Algorithm)
{
case Oids.RsaPkcs1Sha256:
case Oids.ECDsaWithSha256:
hashAlg = HashAlgorithmName.SHA256;
break;
case Oids.RsaPkcs1Sha384:
case Oids.ECDsaWithSha384:
hashAlg = HashAlgorithmName.SHA384;
break;
case Oids.RsaPkcs1Sha512:
case Oids.ECDsaWithSha512:
hashAlg = HashAlgorithmName.SHA512;
break;
case Oids.RsaPkcs1Sha1:
case Oids.ECDsaWithSha1:
hashAlg = HashAlgorithmName.SHA1;
break;
default:
throw new NotSupportedException(
SR.Format(SR.Cryptography_UnknownKeyAlgorithm, algorithmIdentifier.Algorithm));
}
// All remaining supported algorithms have no defined parameters
if (!algorithmIdentifier.HasNullEquivalentParameters())
{
return false;
}
switch (algorithmIdentifier.Algorithm)
{
case Oids.RsaPkcs1Sha256:
case Oids.RsaPkcs1Sha384:
case Oids.RsaPkcs1Sha512:
case Oids.RsaPkcs1Sha1:
if (rsa is null)
{
return false;
}
return rsa.VerifyData(toBeSigned, signature, hashAlg, RSASignaturePadding.Pkcs1);
case Oids.ECDsaWithSha256:
case Oids.ECDsaWithSha384:
case Oids.ECDsaWithSha512:
case Oids.ECDsaWithSha1:
if (ecdsa is null)
{
return false;
}
return ecdsa.VerifyData(toBeSigned, signature, hashAlg, DSASignatureFormat.Rfc3279DerSequence);
default:
Debug.Fail(
$"Algorithm ID {algorithmIdentifier.Algorithm} was in the first switch, but not the second");
return false;
}
}
catch (AsnContentException)
{
return false;
}
catch (CryptographicException)
{
return false;
}
finally
{
rsa?.Dispose();
ecdsa?.Dispose();
}
}
}
}