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