1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/cert/pki/parse_certificate.h"
6
7 #include <utility>
8
9 #include "net/cert/pki/cert_error_params.h"
10 #include "net/cert/pki/cert_errors.h"
11 #include "net/cert/pki/general_names.h"
12 #include "net/cert/pki/string_util.h"
13 #include "net/der/input.h"
14 #include "net/der/parse_values.h"
15 #include "net/der/parser.h"
16 #include "third_party/abseil-cpp/absl/types/optional.h"
17
18 namespace net {
19
20 namespace {
21
22 DEFINE_CERT_ERROR_ID(kCertificateNotSequence,
23 "Failed parsing Certificate SEQUENCE");
24 DEFINE_CERT_ERROR_ID(kUnconsumedDataInsideCertificateSequence,
25 "Unconsumed data inside Certificate SEQUENCE");
26 DEFINE_CERT_ERROR_ID(kUnconsumedDataAfterCertificateSequence,
27 "Unconsumed data after Certificate SEQUENCE");
28 DEFINE_CERT_ERROR_ID(kTbsCertificateNotSequence,
29 "Couldn't read tbsCertificate as SEQUENCE");
30 DEFINE_CERT_ERROR_ID(
31 kSignatureAlgorithmNotSequence,
32 "Couldn't read Certificate.signatureAlgorithm as SEQUENCE");
33 DEFINE_CERT_ERROR_ID(kSignatureValueNotBitString,
34 "Couldn't read Certificate.signatureValue as BIT STRING");
35 DEFINE_CERT_ERROR_ID(kUnconsumedDataInsideTbsCertificateSequence,
36 "Unconsumed data inside TBSCertificate");
37 DEFINE_CERT_ERROR_ID(kTbsNotSequence, "Failed parsing TBSCertificate SEQUENCE");
38 DEFINE_CERT_ERROR_ID(kFailedReadingVersion, "Failed reading version");
39 DEFINE_CERT_ERROR_ID(kFailedParsingVersion, "Failed parsing version");
40 DEFINE_CERT_ERROR_ID(kVersionExplicitlyV1,
41 "Version explicitly V1 (should be omitted)");
42 DEFINE_CERT_ERROR_ID(kFailedReadingSerialNumber, "Failed reading serialNumber");
43 DEFINE_CERT_ERROR_ID(kFailedReadingSignatureValue, "Failed reading signature");
44 DEFINE_CERT_ERROR_ID(kFailedReadingIssuer, "Failed reading issuer");
45 DEFINE_CERT_ERROR_ID(kFailedReadingValidity, "Failed reading validity");
46 DEFINE_CERT_ERROR_ID(kFailedParsingValidity, "Failed parsing validity");
47 DEFINE_CERT_ERROR_ID(kFailedReadingSubject, "Failed reading subject");
48 DEFINE_CERT_ERROR_ID(kFailedReadingSpki, "Failed reading subjectPublicKeyInfo");
49 DEFINE_CERT_ERROR_ID(kFailedReadingIssuerUniqueId,
50 "Failed reading issuerUniqueId");
51 DEFINE_CERT_ERROR_ID(kFailedParsingIssuerUniqueId,
52 "Failed parsing issuerUniqueId");
53 DEFINE_CERT_ERROR_ID(
54 kIssuerUniqueIdNotExpected,
55 "Unexpected issuerUniqueId (must be V2 or V3 certificate)");
56 DEFINE_CERT_ERROR_ID(kFailedReadingSubjectUniqueId,
57 "Failed reading subjectUniqueId");
58 DEFINE_CERT_ERROR_ID(kFailedParsingSubjectUniqueId,
59 "Failed parsing subjectUniqueId");
60 DEFINE_CERT_ERROR_ID(
61 kSubjectUniqueIdNotExpected,
62 "Unexpected subjectUniqueId (must be V2 or V3 certificate)");
63 DEFINE_CERT_ERROR_ID(kFailedReadingExtensions,
64 "Failed reading extensions SEQUENCE");
65 DEFINE_CERT_ERROR_ID(kUnexpectedExtensions,
66 "Unexpected extensions (must be V3 certificate)");
67 DEFINE_CERT_ERROR_ID(kSerialNumberIsNegative, "Serial number is negative");
68 DEFINE_CERT_ERROR_ID(kSerialNumberIsZero, "Serial number is zero");
69 DEFINE_CERT_ERROR_ID(kSerialNumberLengthOver20,
70 "Serial number is longer than 20 octets");
71 DEFINE_CERT_ERROR_ID(kSerialNumberNotValidInteger,
72 "Serial number is not a valid INTEGER");
73
74 // Returns true if |input| is a SEQUENCE and nothing else.
IsSequenceTLV(const der::Input & input)75 [[nodiscard]] bool IsSequenceTLV(const der::Input& input) {
76 der::Parser parser(input);
77 der::Parser unused_sequence_parser;
78 if (!parser.ReadSequence(&unused_sequence_parser))
79 return false;
80 // Should by a single SEQUENCE by definition of the function.
81 return !parser.HasMore();
82 }
83
84 // Reads a SEQUENCE from |parser| and writes the full tag-length-value into
85 // |out|. On failure |parser| may or may not have been advanced.
ReadSequenceTLV(der::Parser * parser,der::Input * out)86 [[nodiscard]] bool ReadSequenceTLV(der::Parser* parser, der::Input* out) {
87 return parser->ReadRawTLV(out) && IsSequenceTLV(*out);
88 }
89
90 // Parses a Version according to RFC 5280:
91 //
92 // Version ::= INTEGER { v1(0), v2(1), v3(2) }
93 //
94 // No value other that v1, v2, or v3 is allowed (and if given will fail). RFC
95 // 5280 minimally requires the handling of v3 (and overwhelmingly these are the
96 // certificate versions in use today):
97 //
98 // Implementations SHOULD be prepared to accept any version certificate.
99 // At a minimum, conforming implementations MUST recognize version 3
100 // certificates.
ParseVersion(const der::Input & in,CertificateVersion * version)101 [[nodiscard]] bool ParseVersion(const der::Input& in,
102 CertificateVersion* version) {
103 der::Parser parser(in);
104 uint64_t version64;
105 if (!parser.ReadUint64(&version64))
106 return false;
107
108 switch (version64) {
109 case 0:
110 *version = CertificateVersion::V1;
111 break;
112 case 1:
113 *version = CertificateVersion::V2;
114 break;
115 case 2:
116 *version = CertificateVersion::V3;
117 break;
118 default:
119 // Don't allow any other version identifier.
120 return false;
121 }
122
123 // By definition the input to this function was a single INTEGER, so there
124 // shouldn't be anything else after it.
125 return !parser.HasMore();
126 }
127
128 // Returns true if every bit in |bits| is zero (including empty).
BitStringIsAllZeros(const der::BitString & bits)129 [[nodiscard]] bool BitStringIsAllZeros(const der::BitString& bits) {
130 // Note that it is OK to read from the unused bits, since BitString parsing
131 // guarantees they are all zero.
132 for (size_t i = 0; i < bits.bytes().Length(); ++i) {
133 if (bits.bytes().UnsafeData()[i] != 0)
134 return false;
135 }
136 return true;
137 }
138
139 // Parses a DistributionPointName.
140 //
141 // From RFC 5280:
142 //
143 // DistributionPointName ::= CHOICE {
144 // fullName [0] GeneralNames,
145 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
ParseDistributionPointName(const der::Input & dp_name,ParsedDistributionPoint * distribution_point)146 bool ParseDistributionPointName(const der::Input& dp_name,
147 ParsedDistributionPoint* distribution_point) {
148 der::Parser parser(dp_name);
149 absl::optional<der::Input> der_full_name;
150 if (!parser.ReadOptionalTag(
151 der::kTagContextSpecific | der::kTagConstructed | 0,
152 &der_full_name)) {
153 return false;
154 }
155 if (der_full_name) {
156 // TODO(mattm): surface the CertErrors.
157 CertErrors errors;
158 distribution_point->distribution_point_fullname =
159 GeneralNames::CreateFromValue(*der_full_name, &errors);
160 if (!distribution_point->distribution_point_fullname)
161 return false;
162 return !parser.HasMore();
163 }
164
165 if (!parser.ReadOptionalTag(
166 der::kTagContextSpecific | der::kTagConstructed | 1,
167 &distribution_point
168 ->distribution_point_name_relative_to_crl_issuer)) {
169 return false;
170 }
171 if (distribution_point->distribution_point_name_relative_to_crl_issuer) {
172 return !parser.HasMore();
173 }
174
175 // The CHOICE must contain either fullName or nameRelativeToCRLIssuer.
176 return false;
177 }
178
179 // RFC 5280, section 4.2.1.13.
180 //
181 // DistributionPoint ::= SEQUENCE {
182 // distributionPoint [0] DistributionPointName OPTIONAL,
183 // reasons [1] ReasonFlags OPTIONAL,
184 // cRLIssuer [2] GeneralNames OPTIONAL }
ParseAndAddDistributionPoint(der::Parser * parser,std::vector<ParsedDistributionPoint> * distribution_points)185 bool ParseAndAddDistributionPoint(
186 der::Parser* parser,
187 std::vector<ParsedDistributionPoint>* distribution_points) {
188 ParsedDistributionPoint distribution_point;
189
190 // DistributionPoint ::= SEQUENCE {
191 der::Parser distrib_point_parser;
192 if (!parser->ReadSequence(&distrib_point_parser))
193 return false;
194
195 // distributionPoint [0] DistributionPointName OPTIONAL,
196 absl::optional<der::Input> distribution_point_name;
197 if (!distrib_point_parser.ReadOptionalTag(
198 der::kTagContextSpecific | der::kTagConstructed | 0,
199 &distribution_point_name)) {
200 return false;
201 }
202
203 if (distribution_point_name &&
204 !ParseDistributionPointName(*distribution_point_name,
205 &distribution_point)) {
206 return false;
207 }
208
209 // reasons [1] ReasonFlags OPTIONAL,
210 if (!distrib_point_parser.ReadOptionalTag(der::kTagContextSpecific | 1,
211 &distribution_point.reasons)) {
212 return false;
213 }
214
215 // cRLIssuer [2] GeneralNames OPTIONAL }
216 if (!distrib_point_parser.ReadOptionalTag(
217 der::kTagContextSpecific | der::kTagConstructed | 2,
218 &distribution_point.crl_issuer)) {
219 return false;
220 }
221 // TODO(eroman): Parse "cRLIssuer"?
222
223 // RFC 5280, section 4.2.1.13:
224 // either distributionPoint or cRLIssuer MUST be present.
225 if (!distribution_point_name && !distribution_point.crl_issuer)
226 return false;
227
228 if (distrib_point_parser.HasMore())
229 return false;
230
231 distribution_points->push_back(std::move(distribution_point));
232 return true;
233 }
234
235 } // namespace
236
237 ParsedTbsCertificate::ParsedTbsCertificate() = default;
238
239 ParsedTbsCertificate::ParsedTbsCertificate(ParsedTbsCertificate&& other) =
240 default;
241
242 ParsedTbsCertificate::~ParsedTbsCertificate() = default;
243
VerifySerialNumber(const der::Input & value,bool warnings_only,CertErrors * errors)244 bool VerifySerialNumber(const der::Input& value,
245 bool warnings_only,
246 CertErrors* errors) {
247 // If |warnings_only| was set to true, the exact same errors will be logged,
248 // only they will be logged with a lower severity (warning rather than error).
249 CertError::Severity error_severity =
250 warnings_only ? CertError::SEVERITY_WARNING : CertError::SEVERITY_HIGH;
251
252 bool negative;
253 if (!der::IsValidInteger(value, &negative)) {
254 errors->Add(error_severity, kSerialNumberNotValidInteger, nullptr);
255 return false;
256 }
257
258 // RFC 5280 section 4.1.2.2:
259 //
260 // Note: Non-conforming CAs may issue certificates with serial numbers
261 // that are negative or zero. Certificate users SHOULD be prepared to
262 // gracefully handle such certificates.
263 if (negative)
264 errors->AddWarning(kSerialNumberIsNegative);
265 if (value.Length() == 1 && value.UnsafeData()[0] == 0)
266 errors->AddWarning(kSerialNumberIsZero);
267
268 // RFC 5280 section 4.1.2.2:
269 //
270 // Certificate users MUST be able to handle serialNumber values up to 20
271 // octets. Conforming CAs MUST NOT use serialNumber values longer than 20
272 // octets.
273 if (value.Length() > 20) {
274 errors->Add(error_severity, kSerialNumberLengthOver20,
275 CreateCertErrorParams1SizeT("length", value.Length()));
276 return false;
277 }
278
279 return true;
280 }
281
ReadUTCOrGeneralizedTime(der::Parser * parser,der::GeneralizedTime * out)282 bool ReadUTCOrGeneralizedTime(der::Parser* parser, der::GeneralizedTime* out) {
283 der::Input value;
284 der::Tag tag;
285
286 if (!parser->ReadTagAndValue(&tag, &value))
287 return false;
288
289 if (tag == der::kUtcTime)
290 return der::ParseUTCTime(value, out);
291
292 if (tag == der::kGeneralizedTime)
293 return der::ParseGeneralizedTime(value, out);
294
295 // Unrecognized tag.
296 return false;
297 }
298
ParseValidity(const der::Input & validity_tlv,der::GeneralizedTime * not_before,der::GeneralizedTime * not_after)299 bool ParseValidity(const der::Input& validity_tlv,
300 der::GeneralizedTime* not_before,
301 der::GeneralizedTime* not_after) {
302 der::Parser parser(validity_tlv);
303
304 // Validity ::= SEQUENCE {
305 der::Parser validity_parser;
306 if (!parser.ReadSequence(&validity_parser))
307 return false;
308
309 // notBefore Time,
310 if (!ReadUTCOrGeneralizedTime(&validity_parser, not_before))
311 return false;
312
313 // notAfter Time }
314 if (!ReadUTCOrGeneralizedTime(&validity_parser, not_after))
315 return false;
316
317 // By definition the input was a single Validity sequence, so there shouldn't
318 // be unconsumed data.
319 if (parser.HasMore())
320 return false;
321
322 // The Validity type does not have an extension point.
323 if (validity_parser.HasMore())
324 return false;
325
326 // Note that RFC 5280 doesn't require notBefore to be <=
327 // notAfter, so that will not be considered a "parsing" error here. Instead it
328 // will be considered an expired certificate later when testing against the
329 // current timestamp.
330 return true;
331 }
332
ParseCertificate(const der::Input & certificate_tlv,der::Input * out_tbs_certificate_tlv,der::Input * out_signature_algorithm_tlv,der::BitString * out_signature_value,CertErrors * out_errors)333 bool ParseCertificate(const der::Input& certificate_tlv,
334 der::Input* out_tbs_certificate_tlv,
335 der::Input* out_signature_algorithm_tlv,
336 der::BitString* out_signature_value,
337 CertErrors* out_errors) {
338 // |out_errors| is optional. But ensure it is non-null for the remainder of
339 // this function.
340 CertErrors unused_errors;
341 if (!out_errors)
342 out_errors = &unused_errors;
343
344 der::Parser parser(certificate_tlv);
345
346 // Certificate ::= SEQUENCE {
347 der::Parser certificate_parser;
348 if (!parser.ReadSequence(&certificate_parser)) {
349 out_errors->AddError(kCertificateNotSequence);
350 return false;
351 }
352
353 // tbsCertificate TBSCertificate,
354 if (!ReadSequenceTLV(&certificate_parser, out_tbs_certificate_tlv)) {
355 out_errors->AddError(kTbsCertificateNotSequence);
356 return false;
357 }
358
359 // signatureAlgorithm AlgorithmIdentifier,
360 if (!ReadSequenceTLV(&certificate_parser, out_signature_algorithm_tlv)) {
361 out_errors->AddError(kSignatureAlgorithmNotSequence);
362 return false;
363 }
364
365 // signatureValue BIT STRING }
366 absl::optional<der::BitString> signature_value =
367 certificate_parser.ReadBitString();
368 if (!signature_value) {
369 out_errors->AddError(kSignatureValueNotBitString);
370 return false;
371 }
372 *out_signature_value = signature_value.value();
373
374 // There isn't an extension point at the end of Certificate.
375 if (certificate_parser.HasMore()) {
376 out_errors->AddError(kUnconsumedDataInsideCertificateSequence);
377 return false;
378 }
379
380 // By definition the input was a single Certificate, so there shouldn't be
381 // unconsumed data.
382 if (parser.HasMore()) {
383 out_errors->AddError(kUnconsumedDataAfterCertificateSequence);
384 return false;
385 }
386
387 return true;
388 }
389
390 // From RFC 5280 section 4.1:
391 //
392 // TBSCertificate ::= SEQUENCE {
393 // version [0] EXPLICIT Version DEFAULT v1,
394 // serialNumber CertificateSerialNumber,
395 // signature AlgorithmIdentifier,
396 // issuer Name,
397 // validity Validity,
398 // subject Name,
399 // subjectPublicKeyInfo SubjectPublicKeyInfo,
400 // issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
401 // -- If present, version MUST be v2 or v3
402 // subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
403 // -- If present, version MUST be v2 or v3
404 // extensions [3] EXPLICIT Extensions OPTIONAL
405 // -- If present, version MUST be v3
406 // }
ParseTbsCertificate(const der::Input & tbs_tlv,const ParseCertificateOptions & options,ParsedTbsCertificate * out,CertErrors * errors)407 bool ParseTbsCertificate(const der::Input& tbs_tlv,
408 const ParseCertificateOptions& options,
409 ParsedTbsCertificate* out,
410 CertErrors* errors) {
411 // The rest of this function assumes that |errors| is non-null.
412 CertErrors unused_errors;
413 if (!errors)
414 errors = &unused_errors;
415
416 // TODO(crbug.com/634443): Add useful error information to |errors|.
417
418 der::Parser parser(tbs_tlv);
419
420 // TBSCertificate ::= SEQUENCE {
421 der::Parser tbs_parser;
422 if (!parser.ReadSequence(&tbs_parser)) {
423 errors->AddError(kTbsNotSequence);
424 return false;
425 }
426
427 // version [0] EXPLICIT Version DEFAULT v1,
428 absl::optional<der::Input> version;
429 if (!tbs_parser.ReadOptionalTag(der::ContextSpecificConstructed(0),
430 &version)) {
431 errors->AddError(kFailedReadingVersion);
432 return false;
433 }
434 if (version) {
435 if (!ParseVersion(version.value(), &out->version)) {
436 errors->AddError(kFailedParsingVersion);
437 return false;
438 }
439 if (out->version == CertificateVersion::V1) {
440 errors->AddError(kVersionExplicitlyV1);
441 // The correct way to specify v1 is to omit the version field since v1 is
442 // the DEFAULT.
443 return false;
444 }
445 } else {
446 out->version = CertificateVersion::V1;
447 }
448
449 // serialNumber CertificateSerialNumber,
450 if (!tbs_parser.ReadTag(der::kInteger, &out->serial_number)) {
451 errors->AddError(kFailedReadingSerialNumber);
452 return false;
453 }
454 if (!VerifySerialNumber(out->serial_number,
455 options.allow_invalid_serial_numbers, errors)) {
456 // Invalid serial numbers are only considered fatal failures if
457 // |!allow_invalid_serial_numbers|.
458 if (!options.allow_invalid_serial_numbers)
459 return false;
460 }
461
462 // signature AlgorithmIdentifier,
463 if (!ReadSequenceTLV(&tbs_parser, &out->signature_algorithm_tlv)) {
464 errors->AddError(kFailedReadingSignatureValue);
465 return false;
466 }
467
468 // issuer Name,
469 if (!ReadSequenceTLV(&tbs_parser, &out->issuer_tlv)) {
470 errors->AddError(kFailedReadingIssuer);
471 return false;
472 }
473
474 // validity Validity,
475 der::Input validity_tlv;
476 if (!tbs_parser.ReadRawTLV(&validity_tlv)) {
477 errors->AddError(kFailedReadingValidity);
478 return false;
479 }
480 if (!ParseValidity(validity_tlv, &out->validity_not_before,
481 &out->validity_not_after)) {
482 errors->AddError(kFailedParsingValidity);
483 return false;
484 }
485
486 // subject Name,
487 if (!ReadSequenceTLV(&tbs_parser, &out->subject_tlv)) {
488 errors->AddError(kFailedReadingSubject);
489 return false;
490 }
491
492 // subjectPublicKeyInfo SubjectPublicKeyInfo,
493 if (!ReadSequenceTLV(&tbs_parser, &out->spki_tlv)) {
494 errors->AddError(kFailedReadingSpki);
495 return false;
496 }
497
498 // issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
499 // -- If present, version MUST be v2 or v3
500 absl::optional<der::Input> issuer_unique_id;
501 if (!tbs_parser.ReadOptionalTag(der::ContextSpecificPrimitive(1),
502 &issuer_unique_id)) {
503 errors->AddError(kFailedReadingIssuerUniqueId);
504 return false;
505 }
506 if (issuer_unique_id) {
507 out->issuer_unique_id = der::ParseBitString(issuer_unique_id.value());
508 if (!out->issuer_unique_id) {
509 errors->AddError(kFailedParsingIssuerUniqueId);
510 return false;
511 }
512 if (out->version != CertificateVersion::V2 &&
513 out->version != CertificateVersion::V3) {
514 errors->AddError(kIssuerUniqueIdNotExpected);
515 return false;
516 }
517 }
518
519 // subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
520 // -- If present, version MUST be v2 or v3
521 absl::optional<der::Input> subject_unique_id;
522 if (!tbs_parser.ReadOptionalTag(der::ContextSpecificPrimitive(2),
523 &subject_unique_id)) {
524 errors->AddError(kFailedReadingSubjectUniqueId);
525 return false;
526 }
527 if (subject_unique_id) {
528 out->subject_unique_id = der::ParseBitString(subject_unique_id.value());
529 if (!out->subject_unique_id) {
530 errors->AddError(kFailedParsingSubjectUniqueId);
531 return false;
532 }
533 if (out->version != CertificateVersion::V2 &&
534 out->version != CertificateVersion::V3) {
535 errors->AddError(kSubjectUniqueIdNotExpected);
536 return false;
537 }
538 }
539
540 // extensions [3] EXPLICIT Extensions OPTIONAL
541 // -- If present, version MUST be v3
542 if (!tbs_parser.ReadOptionalTag(der::ContextSpecificConstructed(3),
543 &out->extensions_tlv)) {
544 errors->AddError(kFailedReadingExtensions);
545 return false;
546 }
547 if (out->extensions_tlv) {
548 // extensions_tlv must be a single element. Also check that it is a
549 // SEQUENCE.
550 if (!IsSequenceTLV(out->extensions_tlv.value())) {
551 errors->AddError(kFailedReadingExtensions);
552 return false;
553 }
554 if (out->version != CertificateVersion::V3) {
555 errors->AddError(kUnexpectedExtensions);
556 return false;
557 }
558 }
559
560 // Note that there IS an extension point at the end of TBSCertificate
561 // (according to RFC 5912), so from that interpretation, unconsumed data would
562 // be allowed in |tbs_parser|.
563 //
564 // However because only v1, v2, and v3 certificates are supported by the
565 // parsing, there shouldn't be any subsequent data in those versions, so
566 // reject.
567 if (tbs_parser.HasMore()) {
568 errors->AddError(kUnconsumedDataInsideTbsCertificateSequence);
569 return false;
570 }
571
572 // By definition the input was a single TBSCertificate, so there shouldn't be
573 // unconsumed data.
574 if (parser.HasMore())
575 return false;
576
577 return true;
578 }
579
580 // From RFC 5280:
581 //
582 // Extension ::= SEQUENCE {
583 // extnID OBJECT IDENTIFIER,
584 // critical BOOLEAN DEFAULT FALSE,
585 // extnValue OCTET STRING
586 // -- contains the DER encoding of an ASN.1 value
587 // -- corresponding to the extension type identified
588 // -- by extnID
589 // }
ParseExtension(const der::Input & extension_tlv,ParsedExtension * out)590 bool ParseExtension(const der::Input& extension_tlv, ParsedExtension* out) {
591 der::Parser parser(extension_tlv);
592
593 // Extension ::= SEQUENCE {
594 der::Parser extension_parser;
595 if (!parser.ReadSequence(&extension_parser))
596 return false;
597
598 // extnID OBJECT IDENTIFIER,
599 if (!extension_parser.ReadTag(der::kOid, &out->oid))
600 return false;
601
602 // critical BOOLEAN DEFAULT FALSE,
603 out->critical = false;
604 bool has_critical;
605 der::Input critical;
606 if (!extension_parser.ReadOptionalTag(der::kBool, &critical, &has_critical))
607 return false;
608 if (has_critical) {
609 if (!der::ParseBool(critical, &out->critical))
610 return false;
611 if (!out->critical)
612 return false; // DER-encoding requires DEFAULT values be omitted.
613 }
614
615 // extnValue OCTET STRING
616 if (!extension_parser.ReadTag(der::kOctetString, &out->value))
617 return false;
618
619 // The Extension type does not have an extension point (everything goes in
620 // extnValue).
621 if (extension_parser.HasMore())
622 return false;
623
624 // By definition the input was a single Extension sequence, so there shouldn't
625 // be unconsumed data.
626 if (parser.HasMore())
627 return false;
628
629 return true;
630 }
631
ParseExtensions(const der::Input & extensions_tlv,std::map<der::Input,ParsedExtension> * extensions)632 NET_EXPORT bool ParseExtensions(
633 const der::Input& extensions_tlv,
634 std::map<der::Input, ParsedExtension>* extensions) {
635 der::Parser parser(extensions_tlv);
636
637 // Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
638 der::Parser extensions_parser;
639 if (!parser.ReadSequence(&extensions_parser))
640 return false;
641
642 // The Extensions SEQUENCE must contains at least 1 element (otherwise it
643 // should have been omitted).
644 if (!extensions_parser.HasMore())
645 return false;
646
647 extensions->clear();
648
649 while (extensions_parser.HasMore()) {
650 ParsedExtension extension;
651
652 der::Input extension_tlv;
653 if (!extensions_parser.ReadRawTLV(&extension_tlv))
654 return false;
655
656 if (!ParseExtension(extension_tlv, &extension))
657 return false;
658
659 bool is_duplicate =
660 !extensions->insert(std::make_pair(extension.oid, extension)).second;
661
662 // RFC 5280 says that an extension should not appear more than once.
663 if (is_duplicate)
664 return false;
665 }
666
667 // By definition the input was a single Extensions sequence, so there
668 // shouldn't be unconsumed data.
669 if (parser.HasMore())
670 return false;
671
672 return true;
673 }
674
ConsumeExtension(const der::Input & oid,std::map<der::Input,ParsedExtension> * unconsumed_extensions,ParsedExtension * extension)675 NET_EXPORT bool ConsumeExtension(
676 const der::Input& oid,
677 std::map<der::Input, ParsedExtension>* unconsumed_extensions,
678 ParsedExtension* extension) {
679 auto it = unconsumed_extensions->find(oid);
680 if (it == unconsumed_extensions->end())
681 return false;
682
683 *extension = it->second;
684 unconsumed_extensions->erase(it);
685 return true;
686 }
687
ParseBasicConstraints(const der::Input & basic_constraints_tlv,ParsedBasicConstraints * out)688 bool ParseBasicConstraints(const der::Input& basic_constraints_tlv,
689 ParsedBasicConstraints* out) {
690 der::Parser parser(basic_constraints_tlv);
691
692 // BasicConstraints ::= SEQUENCE {
693 der::Parser sequence_parser;
694 if (!parser.ReadSequence(&sequence_parser))
695 return false;
696
697 // cA BOOLEAN DEFAULT FALSE,
698 out->is_ca = false;
699 bool has_ca;
700 der::Input ca;
701 if (!sequence_parser.ReadOptionalTag(der::kBool, &ca, &has_ca))
702 return false;
703 if (has_ca) {
704 if (!der::ParseBool(ca, &out->is_ca))
705 return false;
706 // TODO(eroman): Should reject if CA was set to false, since
707 // DER-encoding requires DEFAULT values be omitted. In
708 // practice however there are a lot of certificates that use
709 // the broken encoding.
710 }
711
712 // pathLenConstraint INTEGER (0..MAX) OPTIONAL }
713 der::Input encoded_path_len;
714 if (!sequence_parser.ReadOptionalTag(der::kInteger, &encoded_path_len,
715 &out->has_path_len)) {
716 return false;
717 }
718 if (out->has_path_len) {
719 // TODO(eroman): Surface reason for failure if length was longer than uint8.
720 if (!der::ParseUint8(encoded_path_len, &out->path_len))
721 return false;
722 } else {
723 // Default initialize to 0 as a precaution.
724 out->path_len = 0;
725 }
726
727 // There shouldn't be any unconsumed data in the extension.
728 if (sequence_parser.HasMore())
729 return false;
730
731 // By definition the input was a single BasicConstraints sequence, so there
732 // shouldn't be unconsumed data.
733 if (parser.HasMore())
734 return false;
735
736 return true;
737 }
738
739 // TODO(crbug.com/1314019): return absl::optional<BitString> when converting
740 // has_key_usage_ and key_usage_ into single absl::optional field.
ParseKeyUsage(const der::Input & key_usage_tlv,der::BitString * key_usage)741 bool ParseKeyUsage(const der::Input& key_usage_tlv, der::BitString* key_usage) {
742 der::Parser parser(key_usage_tlv);
743 absl::optional<der::BitString> key_usage_internal = parser.ReadBitString();
744 if (!key_usage_internal)
745 return false;
746
747 // By definition the input was a single BIT STRING.
748 if (parser.HasMore())
749 return false;
750
751 // RFC 5280 section 4.2.1.3:
752 //
753 // When the keyUsage extension appears in a certificate, at least
754 // one of the bits MUST be set to 1.
755 if (BitStringIsAllZeros(key_usage_internal.value()))
756 return false;
757
758 *key_usage = key_usage_internal.value();
759 return true;
760 }
761
ParseAuthorityInfoAccess(const der::Input & authority_info_access_tlv,std::vector<AuthorityInfoAccessDescription> * out_access_descriptions)762 bool ParseAuthorityInfoAccess(
763 const der::Input& authority_info_access_tlv,
764 std::vector<AuthorityInfoAccessDescription>* out_access_descriptions) {
765 der::Parser parser(authority_info_access_tlv);
766
767 out_access_descriptions->clear();
768
769 // AuthorityInfoAccessSyntax ::=
770 // SEQUENCE SIZE (1..MAX) OF AccessDescription
771 der::Parser sequence_parser;
772 if (!parser.ReadSequence(&sequence_parser))
773 return false;
774 if (!sequence_parser.HasMore())
775 return false;
776
777 while (sequence_parser.HasMore()) {
778 AuthorityInfoAccessDescription access_description;
779
780 // AccessDescription ::= SEQUENCE {
781 der::Parser access_description_sequence_parser;
782 if (!sequence_parser.ReadSequence(&access_description_sequence_parser))
783 return false;
784
785 // accessMethod OBJECT IDENTIFIER,
786 if (!access_description_sequence_parser.ReadTag(
787 der::kOid, &access_description.access_method_oid)) {
788 return false;
789 }
790
791 // accessLocation GeneralName }
792 if (!access_description_sequence_parser.ReadRawTLV(
793 &access_description.access_location)) {
794 return false;
795 }
796
797 if (access_description_sequence_parser.HasMore())
798 return false;
799
800 out_access_descriptions->push_back(access_description);
801 }
802
803 return true;
804 }
805
ParseAuthorityInfoAccessURIs(const der::Input & authority_info_access_tlv,std::vector<std::string_view> * out_ca_issuers_uris,std::vector<std::string_view> * out_ocsp_uris)806 bool ParseAuthorityInfoAccessURIs(
807 const der::Input& authority_info_access_tlv,
808 std::vector<std::string_view>* out_ca_issuers_uris,
809 std::vector<std::string_view>* out_ocsp_uris) {
810 std::vector<AuthorityInfoAccessDescription> access_descriptions;
811 if (!ParseAuthorityInfoAccess(authority_info_access_tlv,
812 &access_descriptions)) {
813 return false;
814 }
815
816 for (const auto& access_description : access_descriptions) {
817 der::Parser access_location_parser(access_description.access_location);
818 der::Tag access_location_tag;
819 der::Input access_location_value;
820 if (!access_location_parser.ReadTagAndValue(&access_location_tag,
821 &access_location_value)) {
822 return false;
823 }
824
825 // GeneralName ::= CHOICE {
826 if (access_location_tag == der::ContextSpecificPrimitive(6)) {
827 // uniformResourceIdentifier [6] IA5String,
828 std::string_view uri = access_location_value.AsStringView();
829 if (!net::string_util::IsAscii(uri))
830 return false;
831
832 if (access_description.access_method_oid == der::Input(kAdCaIssuersOid))
833 out_ca_issuers_uris->push_back(uri);
834 else if (access_description.access_method_oid == der::Input(kAdOcspOid))
835 out_ocsp_uris->push_back(uri);
836 }
837 }
838 return true;
839 }
840
841 ParsedDistributionPoint::ParsedDistributionPoint() = default;
842 ParsedDistributionPoint::ParsedDistributionPoint(
843 ParsedDistributionPoint&& other) = default;
844 ParsedDistributionPoint::~ParsedDistributionPoint() = default;
845
ParseCrlDistributionPoints(const der::Input & extension_value,std::vector<ParsedDistributionPoint> * distribution_points)846 bool ParseCrlDistributionPoints(
847 const der::Input& extension_value,
848 std::vector<ParsedDistributionPoint>* distribution_points) {
849 distribution_points->clear();
850
851 // RFC 5280, section 4.2.1.13.
852 //
853 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
854 der::Parser extension_value_parser(extension_value);
855 der::Parser distribution_points_parser;
856 if (!extension_value_parser.ReadSequence(&distribution_points_parser))
857 return false;
858 if (extension_value_parser.HasMore())
859 return false;
860
861 // Sequence must have a minimum of 1 item.
862 if (!distribution_points_parser.HasMore())
863 return false;
864
865 while (distribution_points_parser.HasMore()) {
866 if (!ParseAndAddDistributionPoint(&distribution_points_parser,
867 distribution_points))
868 return false;
869 }
870
871 return true;
872 }
873
874 ParsedAuthorityKeyIdentifier::ParsedAuthorityKeyIdentifier() = default;
875 ParsedAuthorityKeyIdentifier::~ParsedAuthorityKeyIdentifier() = default;
876 ParsedAuthorityKeyIdentifier::ParsedAuthorityKeyIdentifier(
877 ParsedAuthorityKeyIdentifier&& other) = default;
878 ParsedAuthorityKeyIdentifier& ParsedAuthorityKeyIdentifier::operator=(
879 ParsedAuthorityKeyIdentifier&& other) = default;
880
ParseAuthorityKeyIdentifier(const der::Input & extension_value,ParsedAuthorityKeyIdentifier * authority_key_identifier)881 bool ParseAuthorityKeyIdentifier(
882 const der::Input& extension_value,
883 ParsedAuthorityKeyIdentifier* authority_key_identifier) {
884 // RFC 5280, section 4.2.1.1.
885 // AuthorityKeyIdentifier ::= SEQUENCE {
886 // keyIdentifier [0] KeyIdentifier OPTIONAL,
887 // authorityCertIssuer [1] GeneralNames OPTIONAL,
888 // authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
889 //
890 // KeyIdentifier ::= OCTET STRING
891
892 der::Parser extension_value_parser(extension_value);
893 der::Parser aki_parser;
894 if (!extension_value_parser.ReadSequence(&aki_parser))
895 return false;
896 if (extension_value_parser.HasMore())
897 return false;
898
899 // TODO(mattm): Should having an empty AuthorityKeyIdentifier SEQUENCE be an
900 // error? RFC 5280 doesn't explicitly say it.
901
902 // keyIdentifier [0] KeyIdentifier OPTIONAL,
903 if (!aki_parser.ReadOptionalTag(der::ContextSpecificPrimitive(0),
904 &authority_key_identifier->key_identifier)) {
905 return false;
906 }
907
908 // authorityCertIssuer [1] GeneralNames OPTIONAL,
909 if (!aki_parser.ReadOptionalTag(
910 der::ContextSpecificConstructed(1),
911 &authority_key_identifier->authority_cert_issuer)) {
912 return false;
913 }
914
915 // authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
916 if (!aki_parser.ReadOptionalTag(
917 der::ContextSpecificPrimitive(2),
918 &authority_key_identifier->authority_cert_serial_number)) {
919 return false;
920 }
921
922 // -- authorityCertIssuer and authorityCertSerialNumber MUST both
923 // -- be present or both be absent
924 if (authority_key_identifier->authority_cert_issuer.has_value() !=
925 authority_key_identifier->authority_cert_serial_number.has_value()) {
926 return false;
927 }
928
929 // There shouldn't be any unconsumed data in the AuthorityKeyIdentifier
930 // SEQUENCE.
931 if (aki_parser.HasMore())
932 return false;
933
934 return true;
935 }
936
ParseSubjectKeyIdentifier(const der::Input & extension_value,der::Input * subject_key_identifier)937 bool ParseSubjectKeyIdentifier(const der::Input& extension_value,
938 der::Input* subject_key_identifier) {
939 // SubjectKeyIdentifier ::= KeyIdentifier
940 //
941 // KeyIdentifier ::= OCTET STRING
942 der::Parser extension_value_parser(extension_value);
943 if (!extension_value_parser.ReadTag(der::kOctetString,
944 subject_key_identifier)) {
945 return false;
946 }
947
948 // There shouldn't be any unconsumed data in the extension SEQUENCE.
949 if (extension_value_parser.HasMore())
950 return false;
951
952 return true;
953 }
954
955 } // namespace net
956