1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This code is made available to you under your choice of the following sets
4  * of licensing terms:
5  */
6 /* This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0. If a copy of the MPL was not distributed with this
8  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9  */
10 /* Copyright 2013 Mozilla Contributors
11  *
12  * Licensed under the Apache License, Version 2.0 (the "License");
13  * you may not use this file except in compliance with the License.
14  * You may obtain a copy of the License at
15  *
16  *     http://www.apache.org/licenses/LICENSE-2.0
17  *
18  * Unless required by applicable law or agreed to in writing, software
19  * distributed under the License is distributed on an "AS IS" BASIS,
20  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  * See the License for the specific language governing permissions and
22  * limitations under the License.
23  */
24 
25 #include "mozpkix/pkixcheck.h"
26 
27 #include "mozpkix/pkixder.h"
28 #include "mozpkix/pkixutil.h"
29 
30 namespace mozilla { namespace pkix {
31 
32 // 4.1.1.2 signatureAlgorithm
33 // 4.1.2.3 signature
34 
35 Result
CheckSignatureAlgorithm(TrustDomain & trustDomain,EndEntityOrCA endEntityOrCA,Time notBefore,const der::SignedDataWithSignature & signedData,Input signatureValue)36 CheckSignatureAlgorithm(TrustDomain& trustDomain,
37                         EndEntityOrCA endEntityOrCA,
38                         Time notBefore,
39                         const der::SignedDataWithSignature& signedData,
40                         Input signatureValue)
41 {
42   // 4.1.1.2. signatureAlgorithm
43   der::PublicKeyAlgorithm publicKeyAlg;
44   DigestAlgorithm digestAlg;
45   Reader signatureAlgorithmReader(signedData.algorithm);
46   Result rv = der::SignatureAlgorithmIdentifierValue(signatureAlgorithmReader,
47                                                      publicKeyAlg, digestAlg);
48   if (rv != Success) {
49     return rv;
50   }
51   rv = der::End(signatureAlgorithmReader);
52   if (rv != Success) {
53     return rv;
54   }
55 
56   // 4.1.2.3. Signature
57   der::PublicKeyAlgorithm signedPublicKeyAlg;
58   DigestAlgorithm signedDigestAlg;
59   Reader signedSignatureAlgorithmReader(signatureValue);
60   rv = der::SignatureAlgorithmIdentifierValue(signedSignatureAlgorithmReader,
61                                               signedPublicKeyAlg,
62                                               signedDigestAlg);
63   if (rv != Success) {
64     return rv;
65   }
66   rv = der::End(signedSignatureAlgorithmReader);
67   if (rv != Success) {
68     return rv;
69   }
70 
71   // "This field MUST contain the same algorithm identifier as the
72   // signatureAlgorithm field in the sequence Certificate." However, it may
73   // be encoded differently. In particular, one of the fields may have a NULL
74   // parameter while the other one may omit the parameter field altogether, and
75   // these are considered equivalent. Some certificates generation software
76   // actually generates certificates like that, so we compare the parsed values
77   // instead of comparing the encoded values byte-for-byte.
78   //
79   // Along the same lines, we accept two different OIDs for RSA-with-SHA1, and
80   // we consider those OIDs to be equivalent here.
81   if (publicKeyAlg != signedPublicKeyAlg || digestAlg != signedDigestAlg) {
82     return Result::ERROR_SIGNATURE_ALGORITHM_MISMATCH;
83   }
84 
85   // During the time of the deprecation of SHA-1 and the deprecation of RSA
86   // keys of less than 2048 bits, we will encounter many certs signed using
87   // SHA-1 and/or too-small RSA keys. With this in mind, we ask the trust
88   // domain early on if it knows it will reject the signature purely based on
89   // the digest algorithm and/or the RSA key size (if an RSA signature). This
90   // is a good optimization because it completely avoids calling
91   // trustDomain.FindIssuers (which may be slow) for such rejected certs, and
92   // more generally it short-circuits any path building with them (which, of
93   // course, is even slower).
94 
95   rv = trustDomain.CheckSignatureDigestAlgorithm(digestAlg, endEntityOrCA,
96                                                  notBefore);
97   if (rv != Success) {
98     return rv;
99   }
100 
101   switch (publicKeyAlg) {
102     case der::PublicKeyAlgorithm::RSA_PKCS1:
103     {
104       // The RSA computation may give a result that requires fewer bytes to
105       // encode than the public key (since it is modular arithmetic). However,
106       // the last step of generating a PKCS#1.5 signature is the I2OSP
107       // procedure, which pads any such shorter result with zeros so that it
108       // is exactly the same length as the public key.
109       unsigned int signatureSizeInBits = signedData.signature.GetLength() * 8u;
110       return trustDomain.CheckRSAPublicKeyModulusSizeInBits(
111                endEntityOrCA, signatureSizeInBits);
112     }
113 
114     case der::PublicKeyAlgorithm::ECDSA:
115       // In theory, we could implement a similar early-pruning optimization for
116       // ECDSA curves. However, since there has been no similar deprecation for
117       // for any curve that we support, the chances of us encountering a curve
118       // during path building is too low to be worth bothering with.
119       break;
120     case der::PublicKeyAlgorithm::Uninitialized:
121     {
122       assert(false);
123       return Result::FATAL_ERROR_LIBRARY_FAILURE;
124     }
125     MOZILLA_PKIX_UNREACHABLE_DEFAULT_ENUM
126   }
127 
128   return Success;
129 }
130 
131 // 4.1.2.4 Issuer
132 
133 Result
CheckIssuer(Input encodedIssuer)134 CheckIssuer(Input encodedIssuer)
135 {
136   // "The issuer field MUST contain a non-empty distinguished name (DN)."
137   Reader issuer(encodedIssuer);
138   Input encodedRDNs;
139   ExpectTagAndGetValue(issuer, der::SEQUENCE, encodedRDNs);
140   Reader rdns(encodedRDNs);
141   // Check that the issuer name contains at least one RDN
142   // (Note: this does not check related grammar rules, such as there being one
143   // or more AVAs in each RDN, or the values in AVAs not being empty strings)
144   if (rdns.AtEnd()) {
145     return Result::ERROR_EMPTY_ISSUER_NAME;
146   }
147   return Success;
148 }
149 
150 // 4.1.2.5 Validity
151 
152 Result
ParseValidity(Input encodedValidity,Time * notBeforeOut,Time * notAfterOut)153 ParseValidity(Input encodedValidity,
154               /*optional out*/ Time* notBeforeOut,
155               /*optional out*/ Time* notAfterOut)
156 {
157   Reader validity(encodedValidity);
158   Time notBefore(Time::uninitialized);
159   if (der::TimeChoice(validity, notBefore) != Success) {
160     return Result::ERROR_INVALID_DER_TIME;
161   }
162 
163   Time notAfter(Time::uninitialized);
164   if (der::TimeChoice(validity, notAfter) != Success) {
165     return Result::ERROR_INVALID_DER_TIME;
166   }
167 
168   if (der::End(validity) != Success) {
169     return Result::ERROR_INVALID_DER_TIME;
170   }
171 
172   if (notBefore > notAfter) {
173     return Result::ERROR_INVALID_DER_TIME;
174   }
175 
176   if (notBeforeOut) {
177     *notBeforeOut = notBefore;
178   }
179   if (notAfterOut) {
180     *notAfterOut = notAfter;
181   }
182 
183   return Success;
184 }
185 
186 Result
CheckValidity(Time time,Time notBefore,Time notAfter)187 CheckValidity(Time time, Time notBefore, Time notAfter)
188 {
189   if (time < notBefore) {
190     return Result::ERROR_NOT_YET_VALID_CERTIFICATE;
191   }
192 
193   if (time > notAfter) {
194     return Result::ERROR_EXPIRED_CERTIFICATE;
195   }
196 
197   return Success;
198 }
199 
200 // 4.1.2.7 Subject Public Key Info
201 
202 Result
CheckSubjectPublicKeyInfoContents(Reader & input,TrustDomain & trustDomain,EndEntityOrCA endEntityOrCA)203 CheckSubjectPublicKeyInfoContents(Reader& input, TrustDomain& trustDomain,
204                                   EndEntityOrCA endEntityOrCA)
205 {
206   // Here, we validate the syntax and do very basic semantic validation of the
207   // public key of the certificate. The intention here is to filter out the
208   // types of bad inputs that are most likely to trigger non-mathematical
209   // security vulnerabilities in the TrustDomain, like buffer overflows or the
210   // use of unsafe elliptic curves.
211   //
212   // We don't check (all of) the mathematical properties of the public key here
213   // because it is more efficient for the TrustDomain to do it during signature
214   // verification and/or other use of the public key. In particular, we
215   // delegate the arithmetic validation of the public key, as specified in
216   // NIST SP800-56A section 5.6.2, to the TrustDomain, at least for now.
217 
218   Reader algorithm;
219   Input subjectPublicKey;
220   Result rv = der::ExpectTagAndGetValue(input, der::SEQUENCE, algorithm);
221   if (rv != Success) {
222     return rv;
223   }
224   rv = der::BitStringWithNoUnusedBits(input, subjectPublicKey);
225   if (rv != Success) {
226     return rv;
227   }
228   rv = der::End(input);
229   if (rv != Success) {
230     return rv;
231   }
232 
233   Reader subjectPublicKeyReader(subjectPublicKey);
234 
235   Reader algorithmOID;
236   rv = der::ExpectTagAndGetValue(algorithm, der::OIDTag, algorithmOID);
237   if (rv != Success) {
238     return rv;
239   }
240 
241   // RFC 3279 Section 2.3.1
242   // python DottedOIDToCode.py rsaEncryption 1.2.840.113549.1.1.1
243   static const uint8_t rsaEncryption[] = {
244     0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01
245   };
246 
247   // RFC 3279 Section 2.3.5 and RFC 5480 Section 2.1.1
248   // python DottedOIDToCode.py id-ecPublicKey 1.2.840.10045.2.1
249   static const uint8_t id_ecPublicKey[] = {
250     0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01
251   };
252 
253   if (algorithmOID.MatchRest(id_ecPublicKey)) {
254     // An id-ecPublicKey AlgorithmIdentifier has a parameter that identifes
255     // the curve being used. Although RFC 5480 specifies multiple forms, we
256     // only supported the NamedCurve form, where the curve is identified by an
257     // OID.
258 
259     Reader namedCurveOIDValue;
260     rv = der::ExpectTagAndGetValue(algorithm, der::OIDTag,
261                                    namedCurveOIDValue);
262     if (rv != Success) {
263       return rv;
264     }
265 
266     // RFC 5480
267     // python DottedOIDToCode.py secp256r1 1.2.840.10045.3.1.7
268     static const uint8_t secp256r1[] = {
269       0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07
270     };
271 
272     // RFC 5480
273     // python DottedOIDToCode.py secp384r1 1.3.132.0.34
274     static const uint8_t secp384r1[] = {
275       0x2b, 0x81, 0x04, 0x00, 0x22
276     };
277 
278     // RFC 5480
279     // python DottedOIDToCode.py secp521r1 1.3.132.0.35
280     static const uint8_t secp521r1[] = {
281       0x2b, 0x81, 0x04, 0x00, 0x23
282     };
283 
284     // Matching is attempted based on a rough estimate of the commonality of the
285     // elliptic curve, to minimize the number of MatchRest calls.
286     NamedCurve curve;
287     unsigned int bits;
288     if (namedCurveOIDValue.MatchRest(secp256r1)) {
289       curve = NamedCurve::secp256r1;
290       bits = 256;
291     } else if (namedCurveOIDValue.MatchRest(secp384r1)) {
292       curve = NamedCurve::secp384r1;
293       bits = 384;
294     } else if (namedCurveOIDValue.MatchRest(secp521r1)) {
295       curve = NamedCurve::secp521r1;
296       bits = 521;
297     } else {
298       return Result::ERROR_UNSUPPORTED_ELLIPTIC_CURVE;
299     }
300 
301     rv = trustDomain.CheckECDSACurveIsAcceptable(endEntityOrCA, curve);
302     if (rv != Success) {
303       return rv;
304     }
305 
306     // RFC 5480 Section 2.2 says that the first octet will be 0x04 to indicate
307     // an uncompressed point, which is the only encoding we support.
308     uint8_t compressedOrUncompressed;
309     rv = subjectPublicKeyReader.Read(compressedOrUncompressed);
310     if (rv != Success) {
311       return rv;
312     }
313     if (compressedOrUncompressed != 0x04) {
314       return Result::ERROR_UNSUPPORTED_EC_POINT_FORM;
315     }
316 
317     // The point is encoded as two raw (not DER-encoded) integers, each padded
318     // to the bit length (rounded up to the nearest byte).
319     Input point;
320     rv = subjectPublicKeyReader.SkipToEnd(point);
321     if (rv != Success) {
322       return rv;
323     }
324     if (point.GetLength() != ((bits + 7) / 8u) * 2u) {
325       return Result::ERROR_BAD_DER;
326     }
327 
328     // XXX: We defer the mathematical verification of the validity of the point
329     // until signature verification. This means that if we never verify a
330     // signature, we'll never fully check whether the public key is valid.
331   } else if (algorithmOID.MatchRest(rsaEncryption)) {
332     // RFC 3279 Section 2.3.1 says "The parameters field MUST have ASN.1 type
333     // NULL for this algorithm identifier."
334     rv = der::ExpectTagAndEmptyValue(algorithm, der::NULLTag);
335     if (rv != Success) {
336       return rv;
337     }
338 
339     // RSAPublicKey :: = SEQUENCE{
340     //    modulus            INTEGER,    --n
341     //    publicExponent     INTEGER  }  --e
342     rv = der::Nested(subjectPublicKeyReader, der::SEQUENCE,
343                      [&trustDomain, endEntityOrCA](Reader& r) {
344       Input modulus;
345       Input::size_type modulusSignificantBytes;
346       Result nestedRv =
347         der::PositiveInteger(r, modulus, &modulusSignificantBytes);
348       if (nestedRv != Success) {
349         return nestedRv;
350       }
351       // XXX: Should we do additional checks of the modulus?
352       nestedRv = trustDomain.CheckRSAPublicKeyModulusSizeInBits(
353         endEntityOrCA, modulusSignificantBytes * 8u);
354       if (nestedRv != Success) {
355         return nestedRv;
356       }
357 
358       // XXX: We don't allow the TrustDomain to validate the exponent.
359       // XXX: We don't do our own sanity checking of the exponent.
360       Input exponent;
361       return der::PositiveInteger(r, exponent);
362     });
363     if (rv != Success) {
364       return rv;
365     }
366   } else {
367     return Result::ERROR_UNSUPPORTED_KEYALG;
368   }
369 
370   rv = der::End(algorithm);
371   if (rv != Success) {
372     return rv;
373   }
374   rv = der::End(subjectPublicKeyReader);
375   if (rv != Success) {
376     return rv;
377   }
378 
379   return Success;
380 }
381 
382 Result
CheckSubjectPublicKeyInfo(Input subjectPublicKeyInfo,TrustDomain & trustDomain,EndEntityOrCA endEntityOrCA)383 CheckSubjectPublicKeyInfo(Input subjectPublicKeyInfo, TrustDomain& trustDomain,
384                           EndEntityOrCA endEntityOrCA)
385 {
386   Reader spkiReader(subjectPublicKeyInfo);
387   Result rv = der::Nested(spkiReader, der::SEQUENCE, [&](Reader& r) {
388     return CheckSubjectPublicKeyInfoContents(r, trustDomain, endEntityOrCA);
389   });
390   if (rv != Success) {
391     return rv;
392   }
393   return der::End(spkiReader);
394 }
395 
396 // 4.2.1.3. Key Usage (id-ce-keyUsage)
397 
398 // As explained in the comment in CheckKeyUsage, bit 0 is the most significant
399 // bit and bit 7 is the least significant bit.
KeyUsageToBitMask(KeyUsage keyUsage)400 inline uint8_t KeyUsageToBitMask(KeyUsage keyUsage)
401 {
402   assert(keyUsage != KeyUsage::noParticularKeyUsageRequired);
403   return 0x80u >> static_cast<uint8_t>(keyUsage);
404 }
405 
406 Result
CheckKeyUsage(EndEntityOrCA endEntityOrCA,const Input * encodedKeyUsage,KeyUsage requiredKeyUsageIfPresent)407 CheckKeyUsage(EndEntityOrCA endEntityOrCA, const Input* encodedKeyUsage,
408               KeyUsage requiredKeyUsageIfPresent)
409 {
410   if (!encodedKeyUsage) {
411     // TODO(bug 970196): Reject certificates that are being used to verify
412     // certificate signatures unless the certificate is a trust anchor, to
413     // reduce the chances of an end-entity certificate being abused as a CA
414     // certificate.
415     // if (endEntityOrCA == EndEntityOrCA::MustBeCA && !isTrustAnchor) {
416     //   return Result::ERROR_INADEQUATE_KEY_USAGE;
417     // }
418     //
419     // TODO: Users may configure arbitrary certificates as trust anchors, not
420     // just roots. We should only allow a certificate without a key usage to be
421     // used as a CA when it is self-issued and self-signed.
422     return Success;
423   }
424 
425   Reader input(*encodedKeyUsage);
426   Reader value;
427   if (der::ExpectTagAndGetValue(input, der::BIT_STRING, value) != Success) {
428     return Result::ERROR_INADEQUATE_KEY_USAGE;
429   }
430 
431   uint8_t numberOfPaddingBits;
432   if (value.Read(numberOfPaddingBits) != Success) {
433     return Result::ERROR_INADEQUATE_KEY_USAGE;
434   }
435   if (numberOfPaddingBits > 7) {
436     return Result::ERROR_INADEQUATE_KEY_USAGE;
437   }
438 
439   uint8_t bits;
440   if (value.Read(bits) != Success) {
441     // Reject empty bit masks.
442     return Result::ERROR_INADEQUATE_KEY_USAGE;
443   }
444 
445   // The most significant bit is numbered 0 (digitalSignature) and the least
446   // significant bit is numbered 7 (encipherOnly), and the padding is in the
447   // least significant bits of the last byte. The numbering of bits in a byte
448   // is backwards from how we usually interpret them.
449   //
450   // For example, let's say bits is encoded in one byte with of value 0xB0 and
451   // numberOfPaddingBits == 4. Then, bits is 10110000 in binary:
452   //
453   //      bit 0  bit 3
454   //          |  |
455   //          v  v
456   //          10110000
457   //              ^^^^
458   //               |
459   //               4 padding bits
460   //
461   // Since bits is the last byte, we have to consider the padding by ensuring
462   // that the least significant 4 bits are all zero, since DER rules require
463   // all padding bits to be zero. Then we have to look at the bit N bits to the
464   // right of the most significant bit, where N is a value from the KeyUsage
465   // enumeration.
466   //
467   // Let's say we're interested in the keyCertSign (5) bit. We'd need to look
468   // at bit 5, which is zero, so keyCertSign is not asserted. (Since we check
469   // that the padding is all zeros, it is OK to read from the padding bits.)
470   //
471   // Let's say we're interested in the digitalSignature (0) bit. We'd need to
472   // look at the bit 0 (the most significant bit), which is set, so that means
473   // digitalSignature is asserted. Similarly, keyEncipherment (2) and
474   // dataEncipherment (3) are asserted.
475   //
476   // Note that since the KeyUsage enumeration is limited to values 0-7, we
477   // only ever need to examine the first byte test for
478   // requiredKeyUsageIfPresent.
479 
480   if (requiredKeyUsageIfPresent != KeyUsage::noParticularKeyUsageRequired) {
481     // Check that the required key usage bit is set.
482     if ((bits & KeyUsageToBitMask(requiredKeyUsageIfPresent)) == 0) {
483       return Result::ERROR_INADEQUATE_KEY_USAGE;
484     }
485   }
486 
487   // RFC 5280 says "The keyCertSign bit is asserted when the subject public
488   // key is used for verifying signatures on public key certificates. If the
489   // keyCertSign bit is asserted, then the cA bit in the basic constraints
490   // extension (Section 4.2.1.9) MUST also be asserted."
491   // However, we allow end-entity certificates (i.e. certificates without
492   // basicConstraints.cA set to TRUE) to claim keyCertSign for compatibility
493   // reasons. This does not compromise security because we only allow
494   // certificates with basicConstraints.cA set to TRUE to act as CAs.
495   if (requiredKeyUsageIfPresent == KeyUsage::keyCertSign &&
496       endEntityOrCA != EndEntityOrCA::MustBeCA) {
497     return Result::ERROR_INADEQUATE_KEY_USAGE;
498   }
499 
500   // The padding applies to the last byte, so skip to the last byte.
501   while (!value.AtEnd()) {
502     if (value.Read(bits) != Success) {
503       return Result::ERROR_INADEQUATE_KEY_USAGE;
504     }
505   }
506 
507   // All of the padding bits must be zero, according to DER rules.
508   uint8_t paddingMask = static_cast<uint8_t>((1 << numberOfPaddingBits) - 1);
509   if ((bits & paddingMask) != 0) {
510     return Result::ERROR_INADEQUATE_KEY_USAGE;
511   }
512 
513   return Success;
514 }
515 
516 // RFC5820 4.2.1.4. Certificate Policies
517 
518 // "The user-initial-policy-set contains the special value any-policy if the
519 // user is not concerned about certificate policy."
520 //
521 // python DottedOIDToCode.py anyPolicy 2.5.29.32.0
522 
523 static const uint8_t anyPolicy[] = {
524   0x55, 0x1d, 0x20, 0x00
525 };
526 
527 /*static*/ const CertPolicyId CertPolicyId::anyPolicy = {
528   4, { 0x55, 0x1d, 0x20, 0x00 }
529 };
530 
531 bool
IsAnyPolicy() const532 CertPolicyId::IsAnyPolicy() const {
533   if (this == &CertPolicyId::anyPolicy) {
534     return true;
535   }
536   return numBytes == sizeof(::mozilla::pkix::anyPolicy) &&
537          std::equal(bytes, bytes + numBytes, ::mozilla::pkix::anyPolicy);
538 }
539 
540 bool
operator ==(const CertPolicyId & other) const541 CertPolicyId::operator==(const CertPolicyId& other) const
542 {
543   return numBytes == other.numBytes &&
544          std::equal(bytes, bytes + numBytes, other.bytes);
545 }
546 
547 // certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
548 Result
CheckCertificatePolicies(EndEntityOrCA endEntityOrCA,const Input * encodedCertificatePolicies,const Input * encodedInhibitAnyPolicy,TrustLevel trustLevel,const CertPolicyId & requiredPolicy)549 CheckCertificatePolicies(EndEntityOrCA endEntityOrCA,
550                          const Input* encodedCertificatePolicies,
551                          const Input* encodedInhibitAnyPolicy,
552                          TrustLevel trustLevel,
553                          const CertPolicyId& requiredPolicy)
554 {
555   if (requiredPolicy.numBytes == 0 ||
556       requiredPolicy.numBytes > sizeof requiredPolicy.bytes) {
557     return Result::FATAL_ERROR_INVALID_ARGS;
558   }
559 
560   bool requiredPolicyFound = requiredPolicy.IsAnyPolicy();
561   if (requiredPolicyFound) {
562     return Success;
563   }
564 
565   // Bug 989051. Until we handle inhibitAnyPolicy we will fail close when
566   // inhibitAnyPolicy extension is present and we are validating for a policy.
567   if (!requiredPolicyFound && encodedInhibitAnyPolicy) {
568     return Result::ERROR_POLICY_VALIDATION_FAILED;
569   }
570 
571   // The root CA certificate may omit the policies that it has been
572   // trusted for, so we cannot require the policies to be present in those
573   // certificates. Instead, the determination of which roots are trusted for
574   // which policies is made by the TrustDomain's GetCertTrust method.
575   if (trustLevel == TrustLevel::TrustAnchor &&
576       endEntityOrCA == EndEntityOrCA::MustBeCA) {
577     requiredPolicyFound = true;
578   }
579 
580   Input requiredPolicyDER;
581   if (requiredPolicyDER.Init(requiredPolicy.bytes, requiredPolicy.numBytes)
582         != Success) {
583     return Result::FATAL_ERROR_INVALID_ARGS;
584   }
585 
586   if (encodedCertificatePolicies) {
587     Reader extension(*encodedCertificatePolicies);
588     Reader certificatePolicies;
589     Result rv = der::ExpectTagAndGetValue(extension, der::SEQUENCE,
590                                           certificatePolicies);
591     if (rv != Success) {
592       return Result::ERROR_POLICY_VALIDATION_FAILED;
593     }
594     if (!extension.AtEnd()) {
595       return Result::ERROR_POLICY_VALIDATION_FAILED;
596     }
597 
598     do {
599       // PolicyInformation ::= SEQUENCE {
600       //         policyIdentifier   CertPolicyId,
601       //         policyQualifiers   SEQUENCE SIZE (1..MAX) OF
602       //                                 PolicyQualifierInfo OPTIONAL }
603       Reader policyInformation;
604       rv = der::ExpectTagAndGetValue(certificatePolicies, der::SEQUENCE,
605                                      policyInformation);
606       if (rv != Success) {
607         return Result::ERROR_POLICY_VALIDATION_FAILED;
608       }
609 
610       Reader policyIdentifier;
611       rv = der::ExpectTagAndGetValue(policyInformation, der::OIDTag,
612                                      policyIdentifier);
613       if (rv != Success) {
614         return rv;
615       }
616 
617       if (policyIdentifier.MatchRest(requiredPolicyDER)) {
618         requiredPolicyFound = true;
619       } else if (endEntityOrCA == EndEntityOrCA::MustBeCA &&
620                  policyIdentifier.MatchRest(anyPolicy)) {
621         requiredPolicyFound = true;
622       }
623 
624       // RFC 5280 Section 4.2.1.4 says "Optional qualifiers, which MAY be
625       // present, are not expected to change the definition of the policy." Also,
626       // it seems that Section 6, which defines validation, does not require any
627       // matching of qualifiers. Thus, doing anything with the policy qualifiers
628       // would be a waste of time and a source of potential incompatibilities, so
629       // we just ignore them.
630     } while (!requiredPolicyFound && !certificatePolicies.AtEnd());
631   }
632 
633   if (!requiredPolicyFound) {
634     return Result::ERROR_POLICY_VALIDATION_FAILED;
635   }
636 
637   return Success;
638 }
639 
640 static const long UNLIMITED_PATH_LEN = -1; // must be less than zero
641 
642 //  BasicConstraints ::= SEQUENCE {
643 //          cA                      BOOLEAN DEFAULT FALSE,
644 //          pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
645 
646 // RFC5280 4.2.1.9. Basic Constraints (id-ce-basicConstraints)
647 Result
CheckBasicConstraints(EndEntityOrCA endEntityOrCA,const Input * encodedBasicConstraints,const der::Version version,TrustLevel trustLevel,unsigned int subCACount)648 CheckBasicConstraints(EndEntityOrCA endEntityOrCA,
649                       const Input* encodedBasicConstraints,
650                       const der::Version version, TrustLevel trustLevel,
651                       unsigned int subCACount)
652 {
653   bool isCA = false;
654   long pathLenConstraint = UNLIMITED_PATH_LEN;
655 
656   if (encodedBasicConstraints) {
657     Reader input(*encodedBasicConstraints);
658     Result rv = der::Nested(input, der::SEQUENCE,
659                             [&isCA, &pathLenConstraint](Reader& r) {
660       Result nestedRv = der::OptionalBoolean(r, isCA);
661       if (nestedRv != Success) {
662         return nestedRv;
663       }
664       // TODO(bug 985025): If isCA is false, pathLenConstraint
665       // MUST NOT be included (as per RFC 5280 section
666       // 4.2.1.9), but for compatibility reasons, we don't
667       // check this.
668       return der::OptionalInteger(r, UNLIMITED_PATH_LEN, pathLenConstraint);
669     });
670     if (rv != Success) {
671       return Result::ERROR_EXTENSION_VALUE_INVALID;
672     }
673     if (der::End(input) != Success) {
674       return Result::ERROR_EXTENSION_VALUE_INVALID;
675     }
676   } else {
677     // "If the basic constraints extension is not present in a version 3
678     //  certificate, or the extension is present but the cA boolean is not
679     //  asserted, then the certified public key MUST NOT be used to verify
680     //  certificate signatures."
681     //
682     // For compatibility, we must accept v1 trust anchors without basic
683     // constraints as CAs.
684     //
685     // There are devices with v1 certificates that are unlikely to be trust
686     // anchors. In order to allow applications to treat this case differently
687     // from other basic constraints violations (e.g. allowing certificate error
688     // overrides for only this case), we return a different error code.
689     //
690     // TODO: add check for self-signedness?
691     if (endEntityOrCA == EndEntityOrCA::MustBeCA && version == der::Version::v1) {
692       if (trustLevel == TrustLevel::TrustAnchor) {
693         isCA = true;
694       } else {
695         return Result::ERROR_V1_CERT_USED_AS_CA;
696       }
697     }
698   }
699 
700   if (endEntityOrCA == EndEntityOrCA::MustBeEndEntity) {
701     // CA certificates are not trusted as EE certs.
702 
703     if (isCA) {
704       // Note that this check prevents a delegated OCSP response signing
705       // certificate with the CA bit from successfully validating when we check
706       // it from pkixocsp.cpp, which is a good thing.
707       return Result::ERROR_CA_CERT_USED_AS_END_ENTITY;
708     }
709 
710     return Success;
711   }
712 
713   assert(endEntityOrCA == EndEntityOrCA::MustBeCA);
714 
715   // End-entity certificates are not allowed to act as CA certs.
716   if (!isCA) {
717     return Result::ERROR_CA_CERT_INVALID;
718   }
719 
720   if (pathLenConstraint >= 0 &&
721       static_cast<long>(subCACount) > pathLenConstraint) {
722     return Result::ERROR_PATH_LEN_CONSTRAINT_INVALID;
723   }
724 
725   return Success;
726 }
727 
728 // 4.2.1.12. Extended Key Usage (id-ce-extKeyUsage)
729 
730 static Result
MatchEKU(Reader & value,KeyPurposeId requiredEKU,EndEntityOrCA endEntityOrCA,TrustDomain & trustDomain,Time notBefore,bool & found,bool & foundOCSPSigning)731 MatchEKU(Reader& value, KeyPurposeId requiredEKU,
732          EndEntityOrCA endEntityOrCA, TrustDomain& trustDomain,
733          Time notBefore, /*in/out*/ bool& found,
734          /*in/out*/ bool& foundOCSPSigning)
735 {
736   // See Section 5.9 of "A Layman's Guide to a Subset of ASN.1, BER, and DER"
737   // for a description of ASN.1 DER encoding of OIDs.
738 
739   // id-pkix  OBJECT IDENTIFIER  ::=
740   //            { iso(1) identified-organization(3) dod(6) internet(1)
741   //                    security(5) mechanisms(5) pkix(7) }
742   // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
743   // id-kp-serverAuth      OBJECT IDENTIFIER ::= { id-kp 1 }
744   // id-kp-clientAuth      OBJECT IDENTIFIER ::= { id-kp 2 }
745   // id-kp-codeSigning     OBJECT IDENTIFIER ::= { id-kp 3 }
746   // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
747   // id-kp-OCSPSigning     OBJECT IDENTIFIER ::= { id-kp 9 }
748   static const uint8_t server[] = { (40*1)+3, 6, 1, 5, 5, 7, 3, 1 };
749   static const uint8_t client[] = { (40*1)+3, 6, 1, 5, 5, 7, 3, 2 };
750   static const uint8_t code  [] = { (40*1)+3, 6, 1, 5, 5, 7, 3, 3 };
751   static const uint8_t email [] = { (40*1)+3, 6, 1, 5, 5, 7, 3, 4 };
752   static const uint8_t ocsp  [] = { (40*1)+3, 6, 1, 5, 5, 7, 3, 9 };
753 
754   // id-Netscape        OBJECT IDENTIFIER ::= { 2 16 840 1 113730 }
755   // id-Netscape-policy OBJECT IDENTIFIER ::= { id-Netscape 4 }
756   // id-Netscape-stepUp OBJECT IDENTIFIER ::= { id-Netscape-policy 1 }
757   static const uint8_t serverStepUp[] =
758     { (40*2)+16, 128+6,72, 1, 128+6,128+120,66, 4, 1 };
759 
760   bool match = false;
761 
762   if (!found) {
763     switch (requiredEKU) {
764       case KeyPurposeId::id_kp_serverAuth: {
765         if (value.MatchRest(server)) {
766           match = true;
767           break;
768         }
769         // Potentially treat CA certs with step-up OID as also having SSL server
770         // type. Comodo has issued certificates that require this behavior that
771         // don't expire until June 2020!
772         if (endEntityOrCA == EndEntityOrCA::MustBeCA &&
773             value.MatchRest(serverStepUp)) {
774           Result rv = trustDomain.NetscapeStepUpMatchesServerAuth(notBefore,
775                                                                   match);
776           if (rv != Success) {
777             return rv;
778           }
779         }
780         break;
781       }
782 
783       case KeyPurposeId::id_kp_clientAuth:
784         match = value.MatchRest(client);
785         break;
786 
787       case KeyPurposeId::id_kp_codeSigning:
788         match = value.MatchRest(code);
789         break;
790 
791       case KeyPurposeId::id_kp_emailProtection:
792         match = value.MatchRest(email);
793         break;
794 
795       case KeyPurposeId::id_kp_OCSPSigning:
796         match = value.MatchRest(ocsp);
797         break;
798 
799       case KeyPurposeId::anyExtendedKeyUsage:
800         return NotReached("anyExtendedKeyUsage should start with found==true",
801                           Result::FATAL_ERROR_LIBRARY_FAILURE);
802     }
803   }
804 
805   if (match) {
806     found = true;
807     if (requiredEKU == KeyPurposeId::id_kp_OCSPSigning) {
808       foundOCSPSigning = true;
809     }
810   } else if (value.MatchRest(ocsp)) {
811     foundOCSPSigning = true;
812   }
813 
814   value.SkipToEnd(); // ignore unmatched OIDs.
815 
816   return Success;
817 }
818 
819 Result
CheckExtendedKeyUsage(EndEntityOrCA endEntityOrCA,const Input * encodedExtendedKeyUsage,KeyPurposeId requiredEKU,TrustDomain & trustDomain,Time notBefore)820 CheckExtendedKeyUsage(EndEntityOrCA endEntityOrCA,
821                       const Input* encodedExtendedKeyUsage,
822                       KeyPurposeId requiredEKU, TrustDomain& trustDomain,
823                       Time notBefore)
824 {
825   // XXX: We're using Result::ERROR_INADEQUATE_CERT_TYPE here so that callers
826   // can distinguish EKU mismatch from KU mismatch from basic constraints
827   // mismatch. We should probably add a new error code that is more clear for
828   // this type of problem.
829 
830   bool foundOCSPSigning = false;
831 
832   if (encodedExtendedKeyUsage) {
833     bool found = requiredEKU == KeyPurposeId::anyExtendedKeyUsage;
834 
835     Reader input(*encodedExtendedKeyUsage);
836     Result rv = der::NestedOf(input, der::SEQUENCE, der::OIDTag,
837                               der::EmptyAllowed::No, [&](Reader& r) {
838       return MatchEKU(r, requiredEKU, endEntityOrCA, trustDomain, notBefore,
839                       found, foundOCSPSigning);
840     });
841     if (rv != Success) {
842       return Result::ERROR_INADEQUATE_CERT_TYPE;
843     }
844     if (der::End(input) != Success) {
845       return Result::ERROR_INADEQUATE_CERT_TYPE;
846     }
847 
848     // If the EKU extension was included, then the required EKU must be in the
849     // list.
850     if (!found) {
851       return Result::ERROR_INADEQUATE_CERT_TYPE;
852     }
853   }
854 
855   // pkixocsp.cpp depends on the following additional checks.
856 
857   if (endEntityOrCA == EndEntityOrCA::MustBeEndEntity) {
858     // When validating anything other than an delegated OCSP signing cert,
859     // reject any cert that also claims to be an OCSP responder, because such
860     // a cert does not make sense. For example, if an SSL certificate were to
861     // assert id-kp-OCSPSigning then it could sign OCSP responses for itself,
862     // if not for this check.
863     // That said, we accept CA certificates with id-kp-OCSPSigning because
864     // some CAs in Mozilla's CA program have issued such intermediate
865     // certificates, and because some CAs have reported some Microsoft server
866     // software wrongly requires CA certificates to have id-kp-OCSPSigning.
867     // Allowing this exception does not cause any security issues because we
868     // require delegated OCSP response signing certificates to be end-entity
869     // certificates.
870     if (foundOCSPSigning && requiredEKU != KeyPurposeId::id_kp_OCSPSigning) {
871       return Result::ERROR_INADEQUATE_CERT_TYPE;
872     }
873     // http://tools.ietf.org/html/rfc6960#section-4.2.2.2:
874     // "OCSP signing delegation SHALL be designated by the inclusion of
875     // id-kp-OCSPSigning in an extended key usage certificate extension
876     // included in the OCSP response signer's certificate."
877     //
878     // id-kp-OCSPSigning is the only EKU that isn't implicitly assumed when the
879     // EKU extension is missing from an end-entity certificate. However, any CA
880     // certificate can issue a delegated OCSP response signing certificate, so
881     // we can't require the EKU be explicitly included for CA certificates.
882     if (!foundOCSPSigning && requiredEKU == KeyPurposeId::id_kp_OCSPSigning) {
883       return Result::ERROR_INADEQUATE_CERT_TYPE;
884     }
885   }
886 
887   return Success;
888 }
889 
890 Result
CheckTLSFeatures(const BackCert & subject,BackCert & potentialIssuer)891 CheckTLSFeatures(const BackCert& subject, BackCert& potentialIssuer)
892 {
893   const Input* issuerTLSFeatures = potentialIssuer.GetRequiredTLSFeatures();
894   if (!issuerTLSFeatures) {
895     return Success;
896   }
897 
898   const Input* subjectTLSFeatures = subject.GetRequiredTLSFeatures();
899   if (issuerTLSFeatures->GetLength() == 0 ||
900       !subjectTLSFeatures ||
901       !InputsAreEqual(*issuerTLSFeatures, *subjectTLSFeatures)) {
902     return Result::ERROR_REQUIRED_TLS_FEATURE_MISSING;
903   }
904 
905   return Success;
906 }
907 
908 Result
TLSFeaturesSatisfiedInternal(const Input * requiredTLSFeatures,const Input * stapledOCSPResponse)909 TLSFeaturesSatisfiedInternal(const Input* requiredTLSFeatures,
910                              const Input* stapledOCSPResponse)
911 {
912   if (!requiredTLSFeatures) {
913     return Success;
914   }
915 
916   // RFC 6066 10.2: ExtensionType status_request
917   const static uint8_t status_request = 5;
918   const static uint8_t status_request_bytes[] = { status_request };
919 
920   Reader input(*requiredTLSFeatures);
921   return der::NestedOf(input, der::SEQUENCE, der::INTEGER,
922                        der::EmptyAllowed::No, [&](Reader& r) {
923     if (!r.MatchRest(status_request_bytes)) {
924       return Result::ERROR_REQUIRED_TLS_FEATURE_MISSING;
925     }
926 
927     if (!stapledOCSPResponse) {
928       return Result::ERROR_REQUIRED_TLS_FEATURE_MISSING;
929     }
930 
931     return Result::Success;
932   });
933 }
934 
935 Result
CheckTLSFeaturesAreSatisfied(Input & cert,const Input * stapledOCSPResponse)936 CheckTLSFeaturesAreSatisfied(Input& cert,
937                              const Input* stapledOCSPResponse)
938 {
939   BackCert backCert(cert, EndEntityOrCA::MustBeEndEntity, nullptr);
940   Result rv = backCert.Init();
941   if (rv != Success) {
942     return rv;
943   }
944 
945   return TLSFeaturesSatisfiedInternal(backCert.GetRequiredTLSFeatures(),
946                                       stapledOCSPResponse);
947 }
948 
949 Result
CheckIssuerIndependentProperties(TrustDomain & trustDomain,const BackCert & cert,Time time,KeyUsage requiredKeyUsageIfPresent,KeyPurposeId requiredEKUIfPresent,const CertPolicyId & requiredPolicy,unsigned int subCACount,TrustLevel & trustLevel)950 CheckIssuerIndependentProperties(TrustDomain& trustDomain,
951                                  const BackCert& cert,
952                                  Time time,
953                                  KeyUsage requiredKeyUsageIfPresent,
954                                  KeyPurposeId requiredEKUIfPresent,
955                                  const CertPolicyId& requiredPolicy,
956                                  unsigned int subCACount,
957                                  /*out*/ TrustLevel& trustLevel)
958 {
959   Result rv;
960 
961   const EndEntityOrCA endEntityOrCA = cert.endEntityOrCA;
962 
963   // Check the cert's trust first, because we want to minimize the amount of
964   // processing we do on a distrusted cert, in case it is trying to exploit
965   // some bug in our processing.
966   rv = trustDomain.GetCertTrust(endEntityOrCA, requiredPolicy, cert.GetDER(),
967                                 trustLevel);
968   if (rv != Success) {
969     return rv;
970   }
971 
972   // IMPORTANT: We parse the validity interval here, so that we can use the
973   // notBefore and notAfter values in checks for things that might be deprecated
974   // over time. However, we must not fail for semantic errors until the end of
975   // this method, in order to preserve error ranking.
976   Time notBefore(Time::uninitialized);
977   Time notAfter(Time::uninitialized);
978   rv = ParseValidity(cert.GetValidity(), &notBefore, &notAfter);
979   if (rv != Success) {
980     return rv;
981   }
982 
983   if (trustLevel == TrustLevel::TrustAnchor &&
984       endEntityOrCA == EndEntityOrCA::MustBeEndEntity &&
985       requiredEKUIfPresent == KeyPurposeId::id_kp_OCSPSigning) {
986     // OCSP signer certificates can never be trust anchors, especially
987     // since we don't support designated OCSP responders. All of the checks
988     // below that are dependent on trustLevel rely on this overriding of the
989     // trust level for OCSP signers.
990     trustLevel = TrustLevel::InheritsTrust;
991   }
992 
993   switch (trustLevel) {
994     case TrustLevel::InheritsTrust:
995       rv = CheckSignatureAlgorithm(trustDomain, endEntityOrCA, notBefore,
996                                    cert.GetSignedData(), cert.GetSignature());
997       if (rv != Success) {
998         return rv;
999       }
1000       break;
1001 
1002     case TrustLevel::TrustAnchor:
1003       // We don't even bother checking signatureAlgorithm or signature for
1004       // syntactic validity for trust anchors, because we don't use those
1005       // fields for anything, and because the trust anchor might be signed
1006       // with a signature algorithm we don't actually support.
1007       break;
1008 
1009     case TrustLevel::ActivelyDistrusted:
1010       return Result::ERROR_UNTRUSTED_CERT;
1011   }
1012 
1013   // Check the SPKI early, because it is one of the most selective properties
1014   // of the certificate due to SHA-1 deprecation and the deprecation of
1015   // certificates with keys weaker than RSA 2048.
1016   rv = CheckSubjectPublicKeyInfo(cert.GetSubjectPublicKeyInfo(), trustDomain,
1017                                  endEntityOrCA);
1018   if (rv != Success) {
1019     return rv;
1020   }
1021 
1022   // 4.1.2.4. Issuer
1023   rv = CheckIssuer(cert.GetIssuer());
1024   if (rv != Success) {
1025     return rv;
1026   }
1027 
1028   // 4.2.1.1. Authority Key Identifier is ignored (see bug 965136).
1029 
1030   // 4.2.1.2. Subject Key Identifier is ignored (see bug 965136).
1031 
1032   // 4.2.1.3. Key Usage
1033   rv = CheckKeyUsage(endEntityOrCA, cert.GetKeyUsage(),
1034                      requiredKeyUsageIfPresent);
1035   if (rv != Success) {
1036     return rv;
1037   }
1038 
1039   // 4.2.1.4. Certificate Policies
1040   rv = CheckCertificatePolicies(endEntityOrCA, cert.GetCertificatePolicies(),
1041                                 cert.GetInhibitAnyPolicy(), trustLevel,
1042                                 requiredPolicy);
1043   if (rv != Success) {
1044     return rv;
1045   }
1046 
1047   // 4.2.1.5. Policy Mappings are not supported; see the documentation about
1048   //          policy enforcement in pkix.h.
1049 
1050   // 4.2.1.6. Subject Alternative Name dealt with during name constraint
1051   //          checking and during name verification (CERT_VerifyCertName).
1052 
1053   // 4.2.1.7. Issuer Alternative Name is not something that needs checking.
1054 
1055   // 4.2.1.8. Subject Directory Attributes is not something that needs
1056   //          checking.
1057 
1058   // 4.2.1.9. Basic Constraints.
1059   rv = CheckBasicConstraints(endEntityOrCA, cert.GetBasicConstraints(),
1060                              cert.GetVersion(), trustLevel, subCACount);
1061   if (rv != Success) {
1062     return rv;
1063   }
1064 
1065   // 4.2.1.10. Name Constraints is dealt with in during path building.
1066 
1067   // 4.2.1.11. Policy Constraints are implicitly supported; see the
1068   //           documentation about policy enforcement in pkix.h.
1069 
1070   // 4.2.1.12. Extended Key Usage
1071   rv = CheckExtendedKeyUsage(endEntityOrCA, cert.GetExtKeyUsage(),
1072                              requiredEKUIfPresent, trustDomain, notBefore);
1073   if (rv != Success) {
1074     return rv;
1075   }
1076 
1077   // 4.2.1.13. CRL Distribution Points is not supported, though the
1078   //           TrustDomain's CheckRevocation method may parse it and process it
1079   //           on its own.
1080 
1081   // 4.2.1.14. Inhibit anyPolicy is implicitly supported; see the documentation
1082   //           about policy enforcement in pkix.h.
1083 
1084   // IMPORTANT: Even though we parse validity above, we wait until this point to
1085   // check it, so that error ranking works correctly.
1086   rv = CheckValidity(time, notBefore, notAfter);
1087   if (rv != Success) {
1088     return rv;
1089   }
1090 
1091   rv = trustDomain.CheckValidityIsAcceptable(notBefore, notAfter, endEntityOrCA,
1092                                              requiredEKUIfPresent);
1093   if (rv != Success) {
1094     return rv;
1095   }
1096 
1097   return Success;
1098 }
1099 
1100 } } // namespace mozilla::pkix
1101