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