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