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