pkixcheck.cpp 37 KB

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