cert_verify_proc_mac.cc 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. // Copyright (c) 2012 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. #include "net/cert/cert_verify_proc_mac.h"
  5. #include <CommonCrypto/CommonDigest.h>
  6. #include <CoreServices/CoreServices.h>
  7. #include <Security/Security.h>
  8. #include <algorithm>
  9. #include <string>
  10. #include <vector>
  11. #include "base/logging.h"
  12. #include "base/mac/mac_logging.h"
  13. #include "base/mac/mac_util.h"
  14. #include "base/mac/scoped_cftyperef.h"
  15. #include "base/strings/string_piece.h"
  16. #include "base/synchronization/lock.h"
  17. #include "crypto/mac_security_services_lock.h"
  18. #include "crypto/sha2.h"
  19. #include "net/base/hash_value.h"
  20. #include "net/base/net_errors.h"
  21. #include "net/cert/asn1_util.h"
  22. #include "net/cert/cert_status_flags.h"
  23. #include "net/cert/cert_verifier.h"
  24. #include "net/cert/cert_verify_result.h"
  25. #include "net/cert/crl_set.h"
  26. #include "net/cert/ct_serialization.h"
  27. #include "net/cert/ev_root_ca_metadata.h"
  28. #include "net/cert/known_roots.h"
  29. #include "net/cert/known_roots_mac.h"
  30. #include "net/cert/pki/certificate_policies.h"
  31. #include "net/cert/pki/parsed_certificate.h"
  32. #include "net/cert/test_keychain_search_list_mac.h"
  33. #include "net/cert/test_root_certs.h"
  34. #include "net/cert/x509_certificate.h"
  35. #include "net/cert/x509_util.h"
  36. #include "net/cert/x509_util_apple.h"
  37. #include "net/cert/x509_util_mac.h"
  38. // CSSM functions are deprecated as of OSX 10.7, but have no replacement.
  39. // https://bugs.chromium.org/p/chromium/issues/detail?id=590914#c1
  40. #pragma clang diagnostic push
  41. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  42. using base::ScopedCFTypeRef;
  43. namespace net {
  44. namespace {
  45. const void* kResultDebugDataKey = &kResultDebugDataKey;
  46. typedef OSStatus (*SecTrustCopyExtendedResultFuncPtr)(SecTrustRef,
  47. CFDictionaryRef*);
  48. using CertEvidenceInfo = CertVerifyProcMac::ResultDebugData::CertEvidenceInfo;
  49. int NetErrorFromOSStatus(OSStatus status) {
  50. switch (status) {
  51. case noErr:
  52. return OK;
  53. case errSecNotAvailable:
  54. case errSecNoCertificateModule:
  55. case errSecNoPolicyModule:
  56. return ERR_NOT_IMPLEMENTED;
  57. case errSecAuthFailed:
  58. return ERR_ACCESS_DENIED;
  59. default: {
  60. OSSTATUS_LOG(ERROR, status) << "Unknown error mapped to ERR_FAILED";
  61. return ERR_FAILED;
  62. }
  63. }
  64. }
  65. // Beginning with macOS 10.13, certificate verification is dispatched
  66. // to trustd, which uses OSStatus internally to track errors, and
  67. // then maps the internal codes into CSSM codes for applications still
  68. // calling the deprecated (since 10.7) APIs.
  69. //
  70. // The mapping is maintained in SecPolicyChecks.list, to see the
  71. // checks applied to leaves/intermediates/roots/chains and what
  72. // failure of those checks will cause, both the OSStatus and the
  73. // mapped CSSM error code.
  74. //
  75. // Not all checks in the table are applicable; some only apply to
  76. // Apple-specific services (e.g. iTunes checking for an Apple
  77. // policy), so only those applicable to TLS are mapped here.
  78. //
  79. // The downside is that it does mean that as Apple introduces
  80. // additional checks (e.g. as done in 10.15), any failures of these
  81. // checks are initially mapped to ERR_CERT_INVALID for safety, even
  82. // if there may be a more applicable CertStatus code.
  83. CertStatus CertStatusFromOSStatus(OSStatus status) {
  84. switch (status) {
  85. case noErr:
  86. return 0;
  87. case CSSMERR_APPLETP_HOSTNAME_MISMATCH:
  88. return CERT_STATUS_COMMON_NAME_INVALID;
  89. case CSSMERR_TP_CERT_EXPIRED:
  90. case CSSMERR_TP_CERT_NOT_VALID_YET:
  91. return CERT_STATUS_DATE_INVALID;
  92. case CSSMERR_APPLETP_TRUST_SETTING_DENY:
  93. case CSSMERR_TP_NOT_TRUSTED:
  94. // CSSMERR_TP_VERIFY_ACTION_FAILED is used when CT is required
  95. // and not present. The OS rejected this chain, and so mapping
  96. // to CERT_STATUS_CT_COMPLIANCE_FAILED (which is informational,
  97. // as policy enforcement is not handled in the CertVerifier)
  98. // would cause this error to be ignored and mapped to
  99. // CERT_STATUS_INVALID. Rather than do that, mark it simply as
  100. // "untrusted". The CT_COMPLIANCE_FAILED bit is not set, since
  101. // it's not necessarily a compliance failure with the embedder's
  102. // CT policy. It's a bit of a hack, but hopefully temporary.
  103. // TP_NOT_TRUSTED is somewhat similar. It applies for
  104. // situations where a root isn't trusted or an intermediate
  105. // isn't trusted, when a key is restricted, or when the calling
  106. // application requested CT enforcement (which CertVerifier
  107. // should never being doing).
  108. case CSSMERR_TP_VERIFY_ACTION_FAILED:
  109. return CERT_STATUS_AUTHORITY_INVALID;
  110. case CSSMERR_APPLETP_INVALID_AUTHORITY_ID:
  111. case CSSMERR_APPLETP_INVALID_CA:
  112. case CSSMERR_APPLETP_INVALID_EMPTY_SUBJECT:
  113. case CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE:
  114. case CSSMERR_APPLETP_INVALID_KEY_USAGE:
  115. case CSSMERR_APPLETP_MISSING_REQUIRED_EXTENSION:
  116. case CSSMERR_APPLETP_NO_BASIC_CONSTRAINTS:
  117. case CSSMERR_APPLETP_PATH_LEN_CONSTRAINT:
  118. case CSSMERR_APPLETP_UNKNOWN_CERT_EXTEN:
  119. case CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN:
  120. case CSSMERR_CSP_ALGID_MISMATCH:
  121. // INVALID_POLICY_IDENTIFIERS and INVALID_NAME are used for
  122. // certificates that violate the constraints imposed upon the
  123. // issuer. Nominally this could be mapped to
  124. // CERT_STATUS_AUTHORITY_INVALID, except the trustd behaviour
  125. // is to treat this as a fatal (non-recoverable) error. That
  126. // behavior is preserved here for consistency with Safari.
  127. case CSSMERR_TP_INVALID_POLICY_IDENTIFIERS:
  128. case CSSMERR_TP_INVALID_NAME:
  129. return CERT_STATUS_INVALID;
  130. // In trustd, an unsupported algorithm is CSP_ALGID_MISMATCH,
  131. // which should cause a path building failure, while supported
  132. // but weak algorithms use this code.
  133. case CSSMERR_CSP_INVALID_DIGEST_ALGORITHM:
  134. return CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;
  135. // In trustd, certificates that are too weak to process, period,
  136. // are mapped to INVALID_CERTIFICATE. However, certificates which
  137. // are too weak according to compliance policies (e.g. restrictions
  138. // for publicly trusted certificates) are mapped to UNSUPPORTED_KEY_SIZE.
  139. case CSSMERR_CSP_UNSUPPORTED_KEY_SIZE:
  140. return CERT_STATUS_WEAK_KEY;
  141. case CSSMERR_TP_CERT_REVOKED:
  142. return CERT_STATUS_REVOKED;
  143. case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
  144. return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
  145. // In the trustd world, if a CRL suspends a certificate,
  146. // that's signaled by TP_CERT_REVOKED, with the revocation
  147. // reason available in the error details dictionary. The
  148. // SUSPENDED error is repurposed to indicate failure to
  149. // comply with the macOS 10.15+ limits on certificate
  150. // lifetimes - https://support.apple.com/en-us/HT210176
  151. case CSSMERR_TP_CERT_SUSPENDED:
  152. return CERT_STATUS_VALIDITY_TOO_LONG;
  153. // CSSMERR_TP_INVALID_CERTIFICATE is unfortunate. It may be
  154. // used to signal a weak key (CERT_STATUS_WEAK_KEY), which
  155. // would be accompanied by a kSecTrustResultFatalTrustFailure, while
  156. // the other situations (such as an invalid certificate, a
  157. // name constraint violation, or a policy constraint violation)
  158. // would be accompanied by a kSecTrustResultRecoverableTrustFailure.
  159. // However, CertVerifier treats these as inverted: name constraint or
  160. // policy violations are fatal (CERT_STATUS_INVALID), while WEAK_KEY
  161. // may be recoverable.
  162. // Further, because macOS attempts to gather all the errors, a different
  163. // fatal error may have occurred elsewhere in the chain, so the overall
  164. // result can't be used to distinguish individual certificate errors.
  165. // For this complicated reason, the weak key case is mapped to
  166. // CERT_STATUS_INVALID for safety, rather than mapping the policy
  167. // violations as weak keys.
  168. case CSSMERR_TP_INVALID_CERTIFICATE:
  169. return CERT_STATUS_INVALID;
  170. default: {
  171. // Failure was due to something Chromium doesn't define a
  172. // specific status for (such as basic constraints violation, or
  173. // unknown critical extension)
  174. OSSTATUS_LOG(WARNING, status)
  175. << "Unknown error mapped to CERT_STATUS_INVALID";
  176. return CERT_STATUS_INVALID;
  177. }
  178. }
  179. }
  180. // Creates a series of SecPolicyRefs to be added to a SecTrustRef used to
  181. // validate a certificate for an SSL server. |flags| is a bitwise-OR of
  182. // VerifyFlags that can further alter how trust is validated, such as how
  183. // revocation is checked. If successful, returns noErr, and stores the
  184. // resultant array of SecPolicyRefs in |policies|.
  185. OSStatus CreateTrustPolicies(int flags, ScopedCFTypeRef<CFArrayRef>* policies) {
  186. ScopedCFTypeRef<CFMutableArrayRef> local_policies(
  187. CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
  188. if (!local_policies)
  189. return memFullErr;
  190. ScopedCFTypeRef<SecPolicyRef> ssl_policy(
  191. SecPolicyCreateSSL(/*server=*/true, /*hostname=*/nullptr));
  192. if (!ssl_policy)
  193. return errSecNoPolicyModule;
  194. CFArrayAppendValue(local_policies, ssl_policy);
  195. // Explicitly add revocation policies, in order to override system
  196. // revocation checking policies and instead respect the application-level
  197. // revocation preference.
  198. if (flags & CertVerifyProc::VERIFY_REV_CHECKING_ENABLED) {
  199. // If revocation checking is requested, enable checking and require positive
  200. // results. Note that this will fail if there are certs with no
  201. // CRLDistributionPoints or OCSP AIA urls, which differs from the behavior
  202. // of |enable_revocation_checking| on pre-10.12. There does not appear to be
  203. // a way around this, but it shouldn't matter much in practice since
  204. // revocation checking is generally used with EV certs, where it is expected
  205. // that all certs include revocation mechanisms.
  206. ScopedCFTypeRef<SecPolicyRef> revocation_policy(
  207. SecPolicyCreateRevocation(kSecRevocationUseAnyAvailableMethod |
  208. kSecRevocationRequirePositiveResponse));
  209. if (!revocation_policy)
  210. return errSecNoPolicyModule;
  211. CFArrayAppendValue(local_policies, revocation_policy);
  212. }
  213. policies->reset(local_policies.release());
  214. return noErr;
  215. }
  216. // Stores the constructed certificate chain |cert_chain| into
  217. // |*verify_result|. |cert_chain| must not be empty.
  218. void CopyCertChainToVerifyResult(CFArrayRef cert_chain,
  219. CertVerifyResult* verify_result) {
  220. DCHECK_LT(0, CFArrayGetCount(cert_chain));
  221. base::ScopedCFTypeRef<SecCertificateRef> verified_cert;
  222. std::vector<base::ScopedCFTypeRef<SecCertificateRef>> verified_chain;
  223. for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
  224. SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
  225. const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
  226. if (i == 0) {
  227. verified_cert.reset(chain_cert, base::scoped_policy::RETAIN);
  228. } else {
  229. verified_chain.emplace_back(chain_cert, base::scoped_policy::RETAIN);
  230. }
  231. }
  232. if (!verified_cert) {
  233. NOTREACHED();
  234. verify_result->cert_status |= CERT_STATUS_INVALID;
  235. return;
  236. }
  237. scoped_refptr<X509Certificate> verified_cert_with_chain =
  238. x509_util::CreateX509CertificateFromSecCertificate(verified_cert,
  239. verified_chain);
  240. if (verified_cert_with_chain)
  241. verify_result->verified_cert = std::move(verified_cert_with_chain);
  242. else
  243. verify_result->cert_status |= CERT_STATUS_INVALID;
  244. }
  245. // Returns true if the certificate uses MD2, MD4, MD5, or SHA1, and false
  246. // otherwise. A return of false also includes the case where the signature
  247. // algorithm couldn't be conclusively labeled as weak.
  248. bool CertUsesWeakHash(SecCertificateRef cert_handle) {
  249. x509_util::CSSMCachedCertificate cached_cert;
  250. OSStatus status = cached_cert.Init(cert_handle);
  251. if (status)
  252. return false;
  253. x509_util::CSSMFieldValue signature_field;
  254. status =
  255. cached_cert.GetField(&CSSMOID_X509V1SignatureAlgorithm, &signature_field);
  256. if (status || !signature_field.field())
  257. return false;
  258. const CSSM_X509_ALGORITHM_IDENTIFIER* sig_algorithm =
  259. signature_field.GetAs<CSSM_X509_ALGORITHM_IDENTIFIER>();
  260. if (!sig_algorithm)
  261. return false;
  262. const CSSM_OID* alg_oid = &sig_algorithm->algorithm;
  263. return (x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_MD2WithRSA) ||
  264. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_MD4WithRSA) ||
  265. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_MD5WithRSA) ||
  266. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithRSA) ||
  267. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithRSA_OIW) ||
  268. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA) ||
  269. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA_CMS) ||
  270. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA_JDK) ||
  271. x509_util::CSSMOIDEqual(alg_oid, &CSSMOID_ECDSA_WithSHA1));
  272. }
  273. // Returns true if the intermediates (excluding trusted certificates) use a
  274. // weak hashing algorithm, but the target does not use a weak hash.
  275. bool IsWeakChainBasedOnHashingAlgorithms(
  276. CFArrayRef cert_chain,
  277. const std::vector<CertEvidenceInfo>& chain_info) {
  278. DCHECK_LT(0, CFArrayGetCount(cert_chain));
  279. DCHECK_EQ(chain_info.size(),
  280. static_cast<size_t>(CFArrayGetCount(cert_chain)));
  281. bool intermediates_contain_weak_hash = false;
  282. bool leaf_uses_weak_hash = false;
  283. for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
  284. SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
  285. const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
  286. if ((chain_info[i].status_bits & CSSM_CERT_STATUS_IS_IN_ANCHORS) ||
  287. (chain_info[i].status_bits & CSSM_CERT_STATUS_IS_ROOT)) {
  288. // The current certificate is either in the user's trusted store or is
  289. // a root (self-signed) certificate. Ignore the signature algorithm for
  290. // these certificates, as it is meaningless for security. We allow
  291. // self-signed certificates (i == 0 & IS_ROOT), since we accept that
  292. // any security assertions by such a cert are inherently meaningless.
  293. continue;
  294. }
  295. if (CertUsesWeakHash(chain_cert)) {
  296. if (i == 0) {
  297. leaf_uses_weak_hash = true;
  298. } else {
  299. intermediates_contain_weak_hash = true;
  300. }
  301. }
  302. }
  303. return !leaf_uses_weak_hash && intermediates_contain_weak_hash;
  304. }
  305. // Checks if |*cert| has a Certificate Policies extension containing either
  306. // of |ev_policy_oid| or anyPolicy.
  307. bool HasPolicyOrAnyPolicy(const ParsedCertificate* cert,
  308. const der::Input& ev_policy_oid) {
  309. if (!cert->has_policy_oids())
  310. return false;
  311. for (const der::Input& policy_oid : cert->policy_oids()) {
  312. if (policy_oid == ev_policy_oid || policy_oid == der::Input(kAnyPolicyOid))
  313. return true;
  314. }
  315. return false;
  316. }
  317. // Looks for known EV policy OIDs in |cert_input|, if one is found it will be
  318. // stored in |*ev_policy_oid| as a DER-encoded OID value (no tag or length).
  319. void GetCandidateEVPolicy(const X509Certificate* cert_input,
  320. std::string* ev_policy_oid) {
  321. ev_policy_oid->clear();
  322. scoped_refptr<ParsedCertificate> cert(ParsedCertificate::Create(
  323. bssl::UpRef(cert_input->cert_buffer()), {}, nullptr));
  324. if (!cert)
  325. return;
  326. if (!cert->has_policy_oids())
  327. return;
  328. EVRootCAMetadata* metadata = EVRootCAMetadata::GetInstance();
  329. for (const der::Input& policy_oid : cert->policy_oids()) {
  330. if (metadata->IsEVPolicyOID(policy_oid)) {
  331. *ev_policy_oid = policy_oid.AsString();
  332. // De-prioritize the CA/Browser forum Extended Validation policy
  333. // (2.23.140.1.1). See crbug.com/705285.
  334. if (!EVRootCAMetadata::IsCaBrowserForumEvOid(policy_oid))
  335. break;
  336. }
  337. }
  338. }
  339. // Checks that the certificate chain of |cert| has policies consistent with
  340. // |ev_policy_oid_string|. The leaf is not checked, as it is assumed that is
  341. // where the policy came from.
  342. bool CheckCertChainEV(const X509Certificate* cert,
  343. const std::string& ev_policy_oid_string) {
  344. der::Input ev_policy_oid(&ev_policy_oid_string);
  345. const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& cert_chain =
  346. cert->intermediate_buffers();
  347. // Root should have matching policy in EVRootCAMetadata.
  348. if (cert_chain.empty())
  349. return false;
  350. SHA256HashValue fingerprint =
  351. X509Certificate::CalculateFingerprint256(cert_chain.back().get());
  352. EVRootCAMetadata* metadata = EVRootCAMetadata::GetInstance();
  353. if (!metadata->HasEVPolicyOID(fingerprint, ev_policy_oid))
  354. return false;
  355. // Intermediates should have Certificate Policies extension with the EV policy
  356. // or AnyPolicy.
  357. for (size_t i = 0; i < cert_chain.size() - 1; ++i) {
  358. scoped_refptr<ParsedCertificate> intermediate_cert(
  359. ParsedCertificate::Create(bssl::UpRef(cert_chain[i].get()), {},
  360. nullptr));
  361. if (!intermediate_cert)
  362. return false;
  363. if (!HasPolicyOrAnyPolicy(intermediate_cert.get(), ev_policy_oid))
  364. return false;
  365. }
  366. return true;
  367. }
  368. void AppendPublicKeyHashesAndUpdateKnownRoot(CFArrayRef chain,
  369. HashValueVector* hashes,
  370. bool* known_root) {
  371. // Walk the chain in reverse, to optimize for IsKnownRoot checks.
  372. for (CFIndex i = CFArrayGetCount(chain); i > 0; i--) {
  373. SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
  374. const_cast<void*>(CFArrayGetValueAtIndex(chain, i - 1)));
  375. CSSM_DATA cert_data;
  376. OSStatus err = SecCertificateGetData(cert, &cert_data);
  377. DCHECK_EQ(err, noErr);
  378. base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
  379. cert_data.Length);
  380. base::StringPiece spki_bytes;
  381. if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes))
  382. continue;
  383. HashValue sha256(HASH_VALUE_SHA256);
  384. CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data());
  385. hashes->push_back(sha256);
  386. if (!*known_root) {
  387. *known_root =
  388. GetNetTrustAnchorHistogramIdForSPKI(sha256) != 0 || IsKnownRoot(cert);
  389. }
  390. }
  391. // Reverse the hash array, to maintain the leaf-first ordering.
  392. std::reverse(hashes->begin(), hashes->end());
  393. }
  394. enum CRLSetResult {
  395. kCRLSetOk,
  396. kCRLSetRevoked,
  397. kCRLSetUnknown,
  398. };
  399. // CheckRevocationWithCRLSet attempts to check each element of |cert_list|
  400. // against |crl_set|. It returns:
  401. // kCRLSetRevoked: if any element of the chain is known to have been revoked.
  402. // kCRLSetUnknown: if there is no fresh information about the leaf
  403. // certificate in the chain or if the CRLSet has expired.
  404. //
  405. // Only the leaf certificate is considered for coverage because some
  406. // intermediates have CRLs with no revocations (after filtering) and
  407. // those CRLs are pruned from the CRLSet at generation time. This means
  408. // that some EV sites would otherwise take the hit of an OCSP lookup for
  409. // no reason.
  410. // kCRLSetOk: otherwise.
  411. CRLSetResult CheckRevocationWithCRLSet(CFArrayRef chain, CRLSet* crl_set) {
  412. if (CFArrayGetCount(chain) == 0)
  413. return kCRLSetOk;
  414. // error is set to true if any errors are found. It causes such chains to be
  415. // considered as not covered.
  416. bool error = false;
  417. // last_covered is set to the coverage state of the previous certificate. The
  418. // certificates are iterated over backwards thus, after the iteration,
  419. // |last_covered| contains the coverage state of the leaf certificate.
  420. bool last_covered = false;
  421. // We iterate from the root certificate down to the leaf, keeping track of
  422. // the issuer's SPKI at each step.
  423. std::string issuer_spki_hash;
  424. for (CFIndex i = CFArrayGetCount(chain); i > 0; i--) {
  425. SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
  426. const_cast<void*>(CFArrayGetValueAtIndex(chain, i - 1)));
  427. CSSM_DATA cert_data;
  428. OSStatus err = SecCertificateGetData(cert, &cert_data);
  429. if (err != noErr) {
  430. NOTREACHED();
  431. error = true;
  432. continue;
  433. }
  434. base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
  435. cert_data.Length);
  436. base::StringPiece spki, subject;
  437. if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki) ||
  438. !asn1::ExtractSubjectFromDERCert(der_bytes, &subject)) {
  439. NOTREACHED();
  440. error = true;
  441. continue;
  442. }
  443. const std::string spki_hash = crypto::SHA256HashString(spki);
  444. x509_util::CSSMCachedCertificate cached_cert;
  445. if (cached_cert.Init(cert) != CSSM_OK) {
  446. NOTREACHED();
  447. error = true;
  448. continue;
  449. }
  450. x509_util::CSSMFieldValue serial_number;
  451. err = cached_cert.GetField(&CSSMOID_X509V1SerialNumber, &serial_number);
  452. if (err || !serial_number.field()) {
  453. NOTREACHED();
  454. error = true;
  455. continue;
  456. }
  457. base::StringPiece serial(
  458. reinterpret_cast<const char*>(serial_number.field()->Data),
  459. serial_number.field()->Length);
  460. CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
  461. if (result != CRLSet::REVOKED)
  462. result = crl_set->CheckSubject(subject, spki_hash);
  463. if (result != CRLSet::REVOKED && !issuer_spki_hash.empty())
  464. result = crl_set->CheckSerial(serial, issuer_spki_hash);
  465. issuer_spki_hash = spki_hash;
  466. switch (result) {
  467. case CRLSet::REVOKED:
  468. return kCRLSetRevoked;
  469. case CRLSet::UNKNOWN:
  470. last_covered = false;
  471. continue;
  472. case CRLSet::GOOD:
  473. last_covered = true;
  474. continue;
  475. default:
  476. NOTREACHED();
  477. error = true;
  478. continue;
  479. }
  480. }
  481. if (error || !last_covered || crl_set->IsExpired())
  482. return kCRLSetUnknown;
  483. return kCRLSetOk;
  484. }
  485. // Builds and evaluates a SecTrustRef for the certificate chain contained
  486. // in |cert_array|, using the verification policies in |trust_policies|. On
  487. // success, returns OK, and updates |trust_ref|, |trust_result|,
  488. // |verified_chain|, and |chain_info| with the verification results. On
  489. // failure, no output parameters are modified.
  490. //
  491. // Note: An OK return does not mean that |cert_array| is trusted, merely that
  492. // verification was performed successfully.
  493. //
  494. // This function should only be called while the Mac Security Services lock is
  495. // held.
  496. int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array,
  497. CFArrayRef trust_policies,
  498. CFDataRef ocsp_response_ref,
  499. CFArrayRef sct_array_ref,
  500. int flags,
  501. CFArrayRef keychain_search_list,
  502. ScopedCFTypeRef<SecTrustRef>* trust_ref,
  503. SecTrustResultType* trust_result,
  504. ScopedCFTypeRef<CFArrayRef>* verified_chain,
  505. std::vector<CertEvidenceInfo>* chain_info) {
  506. SecTrustRef tmp_trust = nullptr;
  507. OSStatus status = SecTrustCreateWithCertificates(cert_array, trust_policies,
  508. &tmp_trust);
  509. if (status)
  510. return NetErrorFromOSStatus(status);
  511. ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust);
  512. if (TestRootCerts::HasInstance()) {
  513. status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust);
  514. if (status)
  515. return NetErrorFromOSStatus(status);
  516. }
  517. if (keychain_search_list) {
  518. status = SecTrustSetKeychains(tmp_trust, keychain_search_list);
  519. if (status)
  520. return NetErrorFromOSStatus(status);
  521. }
  522. if (ocsp_response_ref) {
  523. status = SecTrustSetOCSPResponse(tmp_trust, ocsp_response_ref);
  524. if (status)
  525. return NetErrorFromOSStatus(status);
  526. }
  527. if (sct_array_ref) {
  528. if (__builtin_available(macOS 10.14.2, *)) {
  529. status = SecTrustSetSignedCertificateTimestamps(tmp_trust, sct_array_ref);
  530. if (status)
  531. return NetErrorFromOSStatus(status);
  532. }
  533. }
  534. CSSM_APPLE_TP_ACTION_DATA tp_action_data;
  535. memset(&tp_action_data, 0, sizeof(tp_action_data));
  536. tp_action_data.Version = CSSM_APPLE_TP_ACTION_VERSION;
  537. // Allow CSSM to download any missing intermediate certificates if an
  538. // authorityInfoAccess extension or issuerAltName extension is present.
  539. tp_action_data.ActionFlags = CSSM_TP_ACTION_FETCH_CERT_FROM_NET |
  540. CSSM_TP_ACTION_TRUST_SETTINGS;
  541. // Note: For EV certificates, the Apple TP will handle setting these flags
  542. // as part of EV evaluation.
  543. if (flags & CertVerifyProc::VERIFY_REV_CHECKING_ENABLED) {
  544. // Require a positive result from an OCSP responder or a CRL (or both)
  545. // for every certificate in the chain. The Apple TP automatically
  546. // excludes the self-signed root from this requirement. If a certificate
  547. // is missing both a crlDistributionPoints extension and an
  548. // authorityInfoAccess extension with an OCSP responder URL, then we
  549. // will get a kSecTrustResultRecoverableTrustFailure back from
  550. // SecTrustEvaluate(), with a
  551. // CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK error code. In that case,
  552. // we'll set our own result to include
  553. // CERT_STATUS_NO_REVOCATION_MECHANISM. If one or both extensions are
  554. // present, and a check fails (server unavailable, OCSP retry later,
  555. // signature mismatch), then we'll set our own result to include
  556. // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION.
  557. tp_action_data.ActionFlags |= CSSM_TP_ACTION_REQUIRE_REV_PER_CERT;
  558. // Note, even if revocation checking is disabled, SecTrustEvaluate() will
  559. // modify the OCSP options so as to attempt OCSP checking if it believes a
  560. // certificate may chain to an EV root. However, because network fetches
  561. // are disabled in CreateTrustPolicies() when revocation checking is
  562. // disabled, these will only go against the local cache.
  563. }
  564. ScopedCFTypeRef<CFDataRef> action_data_ref(CFDataCreate(
  565. kCFAllocatorDefault, reinterpret_cast<UInt8*>(&tp_action_data),
  566. sizeof(tp_action_data)));
  567. if (!action_data_ref)
  568. return ERR_OUT_OF_MEMORY;
  569. status = SecTrustSetParameters(tmp_trust, CSSM_TP_ACTION_DEFAULT,
  570. action_data_ref.get());
  571. if (status)
  572. return NetErrorFromOSStatus(status);
  573. // Verify the certificate. A non-zero result from SecTrustGetResult()
  574. // indicates that some fatal error occurred and the chain couldn't be
  575. // processed, not that the chain contains no errors. We need to examine the
  576. // output of SecTrustGetResult() to determine that.
  577. SecTrustResultType tmp_trust_result;
  578. status = SecTrustEvaluate(tmp_trust, &tmp_trust_result);
  579. if (status)
  580. return NetErrorFromOSStatus(status);
  581. CFArrayRef tmp_verified_chain = nullptr;
  582. CSSM_TP_APPLE_EVIDENCE_INFO* tmp_chain_info;
  583. status = SecTrustGetResult(tmp_trust, &tmp_trust_result, &tmp_verified_chain,
  584. &tmp_chain_info);
  585. if (status)
  586. return NetErrorFromOSStatus(status);
  587. // WARNING: Beginning with OS X 10.13, |tmp_chain_info| may be freed by any
  588. // other accesses via SecTrust APIs to |tmp_trust|, so copy the data.
  589. chain_info->clear();
  590. for (CFIndex i = 0, chain_length = CFArrayGetCount(tmp_verified_chain);
  591. i < chain_length; ++i) {
  592. CertEvidenceInfo info;
  593. info.status_bits = tmp_chain_info[i].StatusBits;
  594. info.status_codes.assign(
  595. tmp_chain_info[i].StatusCodes,
  596. tmp_chain_info[i].StatusCodes + tmp_chain_info[i].NumStatusCodes);
  597. chain_info->push_back(std::move(info));
  598. }
  599. trust_ref->swap(scoped_tmp_trust);
  600. *trust_result = tmp_trust_result;
  601. verified_chain->reset(tmp_verified_chain);
  602. return OK;
  603. }
  604. // Runs path building & verification loop for |cert|, given |flags|. This is
  605. // split into a separate function so verification can be repeated with different
  606. // flags. This function does not handle EV.
  607. int VerifyWithGivenFlags(X509Certificate* cert,
  608. const std::string& hostname,
  609. const std::string& ocsp_response,
  610. const std::string& sct_list,
  611. const int flags,
  612. bool rev_checking_soft_fail,
  613. CRLSet* crl_set,
  614. CertVerifyResult* verify_result,
  615. CRLSetResult* completed_chain_crl_result) {
  616. ScopedCFTypeRef<CFArrayRef> trust_policies;
  617. OSStatus status = CreateTrustPolicies(flags, &trust_policies);
  618. if (status)
  619. return NetErrorFromOSStatus(status);
  620. *completed_chain_crl_result = kCRLSetUnknown;
  621. ScopedCFTypeRef<CFDataRef> ocsp_response_ref;
  622. if (!ocsp_response.empty()) {
  623. ocsp_response_ref.reset(
  624. CFDataCreate(kCFAllocatorDefault,
  625. reinterpret_cast<const UInt8*>(ocsp_response.data()),
  626. base::checked_cast<CFIndex>(ocsp_response.size())));
  627. if (!ocsp_response_ref)
  628. return ERR_OUT_OF_MEMORY;
  629. }
  630. ScopedCFTypeRef<CFMutableArrayRef> sct_array_ref;
  631. if (!sct_list.empty()) {
  632. if (__builtin_available(macOS 10.14.2, *)) {
  633. std::vector<base::StringPiece> decoded_sct_list;
  634. if (ct::DecodeSCTList(sct_list, &decoded_sct_list)) {
  635. sct_array_ref.reset(CFArrayCreateMutable(kCFAllocatorDefault,
  636. decoded_sct_list.size(),
  637. &kCFTypeArrayCallBacks));
  638. if (!sct_array_ref)
  639. return ERR_OUT_OF_MEMORY;
  640. for (const auto& sct : decoded_sct_list) {
  641. ScopedCFTypeRef<CFDataRef> sct_ref(CFDataCreate(
  642. kCFAllocatorDefault, reinterpret_cast<const UInt8*>(sct.data()),
  643. base::checked_cast<CFIndex>(sct.size())));
  644. if (!sct_ref)
  645. return ERR_OUT_OF_MEMORY;
  646. CFArrayAppendValue(sct_array_ref.get(), sct_ref.get());
  647. }
  648. }
  649. }
  650. }
  651. // Serialize all calls that may use the Keychain, to work around various
  652. // issues in OS X 10.6+ with multi-threaded access to Security.framework.
  653. base::AutoLock lock(crypto::GetMacSecurityServicesLock());
  654. ScopedCFTypeRef<SecTrustRef> trust_ref;
  655. SecTrustResultType trust_result = kSecTrustResultDeny;
  656. ScopedCFTypeRef<CFArrayRef> completed_chain;
  657. std::vector<CertEvidenceInfo> chain_info;
  658. bool candidate_untrusted = true;
  659. bool candidate_weak = false;
  660. // OS X lacks proper path discovery; it will take the input certs and never
  661. // backtrack the graph attempting to discover valid paths.
  662. // This can create issues in some situations:
  663. // - When OS X changes the trust store, there may be a chain
  664. // A -> B -> C -> D
  665. // where OS X trusts D (on some versions) and trusts C (on some versions).
  666. // If a server supplies a chain A, B, C (cross-signed by D), then this chain
  667. // will successfully validate on systems that trust D, but fail for systems
  668. // that trust C. If the server supplies a chain of A -> B, then it forces
  669. // all clients to fetch C (via AIA) if they trust D, and not all clients
  670. // (notably, Firefox and Android) will do this, thus breaking them.
  671. // An example of this is the Verizon Business Services root - GTE CyberTrust
  672. // and Baltimore CyberTrust roots represent old and new roots that cause
  673. // issues depending on which version of OS X being used.
  674. //
  675. // - A server may be (misconfigured) to send an expired intermediate
  676. // certificate. On platforms with path discovery, the graph traversal
  677. // will back up to immediately before this intermediate, and then
  678. // attempt an AIA fetch or retrieval from local store. However, OS X
  679. // does not do this, and thus prevents access. While this is ostensibly
  680. // a server misconfiguration issue, the fact that it works on other
  681. // platforms is a jarring inconsistency for users.
  682. //
  683. // - When OS X trusts both C and D (simultaneously), it's possible that the
  684. // version of C signed by D is signed using a weak algorithm (e.g. SHA-1),
  685. // while the version of C in the trust store's signature doesn't matter.
  686. // Since a 'strong' chain exists, it would be desirable to prefer this
  687. // chain.
  688. //
  689. // - A variant of the above example, it may be that the version of B sent by
  690. // the server is signed using a weak algorithm, but the version of B
  691. // present in the AIA of A is signed using a strong algorithm. Since a
  692. // 'strong' chain exists, it would be desirable to prefer this chain.
  693. //
  694. // - A user keychain may contain a less desirable intermediate or root.
  695. // OS X gives the user keychains higher priority than the system keychain,
  696. // so it may build a weak chain.
  697. //
  698. // Because of this, the code below first attempts to validate the peer's
  699. // identity using the supplied chain. If it is not trusted (e.g. the OS only
  700. // trusts C, but the version of C signed by D was sent, and D is not trusted),
  701. // or if it contains a weak chain, it will begin lopping off certificates
  702. // from the end of the chain and attempting to verify. If a stronger, trusted
  703. // chain is found, it is used, otherwise, the algorithm continues until only
  704. // the peer's certificate remains.
  705. //
  706. // If the loop does not find a trusted chain, the loop will be repeated with
  707. // the keychain search order altered to give priority to the System Roots
  708. // keychain.
  709. //
  710. // This does cause a performance hit for these users, but only in cases where
  711. // OS X is building weaker chains than desired, or when it would otherwise
  712. // fail the connection.
  713. for (bool try_reordered_keychain : {false, true}) {
  714. ScopedCFTypeRef<CFArrayRef> scoped_alternate_keychain_search_list;
  715. if (TestKeychainSearchList::HasInstance()) {
  716. // Unit tests need to be able to hermetically simulate situations where a
  717. // user has an undesirable certificate in a per-user keychain.
  718. // Adding/Removing a Keychain using SecKeychainCreate/SecKeychainDelete
  719. // has global side effects, which would break other tests and processes
  720. // running on the same machine, so instead tests may load pre-created
  721. // keychains using SecKeychainOpen and then inject them through
  722. // TestKeychainSearchList.
  723. CFArrayRef keychain_search_list;
  724. status = TestKeychainSearchList::GetInstance()->CopySearchList(
  725. &keychain_search_list);
  726. if (status)
  727. return NetErrorFromOSStatus(status);
  728. scoped_alternate_keychain_search_list.reset(keychain_search_list);
  729. }
  730. if (try_reordered_keychain) {
  731. // If a TestKeychainSearchList is present, it will have already set
  732. // |scoped_alternate_keychain_search_list|, which will be used as the
  733. // basis for reordering the keychain. Otherwise, get the current keychain
  734. // search list and use that.
  735. if (!scoped_alternate_keychain_search_list) {
  736. CFArrayRef keychain_search_list;
  737. status = SecKeychainCopySearchList(&keychain_search_list);
  738. if (status)
  739. return NetErrorFromOSStatus(status);
  740. scoped_alternate_keychain_search_list.reset(keychain_search_list);
  741. }
  742. CFMutableArrayRef mutable_keychain_search_list = CFArrayCreateMutableCopy(
  743. kCFAllocatorDefault,
  744. CFArrayGetCount(scoped_alternate_keychain_search_list.get()) + 1,
  745. scoped_alternate_keychain_search_list.get());
  746. if (!mutable_keychain_search_list)
  747. return ERR_OUT_OF_MEMORY;
  748. scoped_alternate_keychain_search_list.reset(mutable_keychain_search_list);
  749. SecKeychainRef keychain;
  750. // Get a reference to the System Roots keychain. The System Roots
  751. // keychain is not normally present in the keychain search list, but is
  752. // implicitly checked after the keychains in the search list. By
  753. // including it directly, force it to be checked first. This is a gross
  754. // hack, but the path is known to be valid through macOS 12.
  755. status = SecKeychainOpen(
  756. "/System/Library/Keychains/SystemRootCertificates.keychain",
  757. &keychain);
  758. if (status)
  759. return NetErrorFromOSStatus(status);
  760. ScopedCFTypeRef<SecKeychainRef> scoped_keychain(keychain);
  761. CFArrayInsertValueAtIndex(mutable_keychain_search_list, 0, keychain);
  762. }
  763. ScopedCFTypeRef<CFMutableArrayRef> cert_array(
  764. x509_util::CreateSecCertificateArrayForX509Certificate(
  765. cert, x509_util::InvalidIntermediateBehavior::kIgnore));
  766. if (!cert_array) {
  767. verify_result->cert_status |= CERT_STATUS_INVALID;
  768. return ERR_CERT_INVALID;
  769. }
  770. // Beginning with the certificate chain as supplied by the server, attempt
  771. // to verify the chain. If a failure is encountered, trim a certificate
  772. // from the end (so long as one remains) and retry, in the hope of forcing
  773. // OS X to find a better path.
  774. while (CFArrayGetCount(cert_array) > 0) {
  775. ScopedCFTypeRef<SecTrustRef> temp_ref;
  776. SecTrustResultType temp_trust_result = kSecTrustResultDeny;
  777. ScopedCFTypeRef<CFArrayRef> temp_chain;
  778. std::vector<CertEvidenceInfo> temp_chain_info;
  779. int rv = BuildAndEvaluateSecTrustRef(
  780. cert_array, trust_policies, ocsp_response_ref.get(),
  781. sct_array_ref.get(), flags,
  782. scoped_alternate_keychain_search_list.get(), &temp_ref,
  783. &temp_trust_result, &temp_chain, &temp_chain_info);
  784. if (rv != OK)
  785. return rv;
  786. // Check to see if the path |temp_chain| has been revoked. This is less
  787. // than ideal to perform after path building, rather than during, because
  788. // there may be multiple paths to trust anchors, and only some of them
  789. // are revoked. Ideally, CRLSets would be part of path building, which
  790. // they are when using NSS (Linux) or CryptoAPI (Windows).
  791. //
  792. // The CRLSet checking is performed inside the loop in the hope that if a
  793. // path is revoked, it's an older path, and the only reason it was built
  794. // is because the server forced it (by supplying an older or less
  795. // desirable intermediate) or because the user had installed a
  796. // certificate in their Keychain forcing this path. However, this means
  797. // its still possible for a CRLSet block of an intermediate to prevent
  798. // access, even when there is a 'good' chain. To fully remedy this, a
  799. // solution might be to have CRLSets contain enough knowledge about what
  800. // the 'desired' path might be, but for the time being, the
  801. // implementation is kept as 'simple' as it can be.
  802. CRLSetResult crl_result = CheckRevocationWithCRLSet(temp_chain, crl_set);
  803. bool untrusted = (temp_trust_result != kSecTrustResultUnspecified &&
  804. temp_trust_result != kSecTrustResultProceed) ||
  805. crl_result == kCRLSetRevoked;
  806. bool weak_chain = false;
  807. if (CFArrayGetCount(temp_chain) == 0) {
  808. // If the chain is empty, it cannot be trusted or have recoverable
  809. // errors.
  810. DCHECK(untrusted);
  811. DCHECK_NE(kSecTrustResultRecoverableTrustFailure, temp_trust_result);
  812. } else {
  813. weak_chain =
  814. IsWeakChainBasedOnHashingAlgorithms(temp_chain, temp_chain_info);
  815. }
  816. // Set the result to the current chain if:
  817. // - This is the first verification attempt. This ensures that if
  818. // everything is awful (e.g. it may just be an untrusted cert), that
  819. // what is reported is exactly what was sent by the server
  820. // - If the current chain is trusted, and the old chain was not trusted,
  821. // then prefer this chain. This ensures that if there is at least a
  822. // valid path to a trust anchor, it's preferred over reporting an error.
  823. // - If the current chain is trusted, and the old chain is trusted, but
  824. // the old chain contained weak algorithms while the current chain only
  825. // contains strong algorithms, then prefer the current chain over the
  826. // old chain.
  827. //
  828. // Note: If the leaf certificate itself is weak, then the only
  829. // consideration is whether or not there is a trusted chain. That's
  830. // because no amount of path discovery will fix a weak leaf.
  831. if (!trust_ref || (!untrusted && (candidate_untrusted ||
  832. (candidate_weak && !weak_chain)))) {
  833. trust_ref = temp_ref;
  834. trust_result = temp_trust_result;
  835. completed_chain = temp_chain;
  836. *completed_chain_crl_result = crl_result;
  837. chain_info = std::move(temp_chain_info);
  838. candidate_untrusted = untrusted;
  839. candidate_weak = weak_chain;
  840. }
  841. // Short-circuit when a current, trusted chain is found.
  842. if (!untrusted && !weak_chain)
  843. break;
  844. // Trim a cert off the end of chain, but if the chain is longer that 10
  845. // certs, trim to at most 10 certs.
  846. constexpr int kMaxTrimmedChainLength = 10;
  847. if (CFArrayGetCount(cert_array) > kMaxTrimmedChainLength) {
  848. CFArrayReplaceValues(
  849. cert_array,
  850. CFRangeMake(kMaxTrimmedChainLength,
  851. CFArrayGetCount(cert_array) - kMaxTrimmedChainLength),
  852. /*newValues=*/nullptr, /*newCount=*/0);
  853. } else {
  854. CFArrayRemoveValueAtIndex(cert_array, CFArrayGetCount(cert_array) - 1);
  855. }
  856. }
  857. // Short-circuit when a current, trusted chain is found.
  858. if (!candidate_untrusted && !candidate_weak)
  859. break;
  860. }
  861. if (flags & CertVerifyProc::VERIFY_REV_CHECKING_ENABLED)
  862. verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
  863. if (*completed_chain_crl_result == kCRLSetRevoked)
  864. verify_result->cert_status |= CERT_STATUS_REVOKED;
  865. if (CFArrayGetCount(completed_chain) > 0) {
  866. CopyCertChainToVerifyResult(completed_chain, verify_result);
  867. }
  868. // As of macOS 10.13, if |trust_result| (from SecTrustGetResult) returns
  869. // kSecTrustResultInvalid, subsequent invocations of SecTrust APIs may
  870. // result in revalidating the SecTrust. In releases earlier than 10.13, this
  871. // call would have additional information, except that information is unused
  872. // and irrelevant if the result was invalid, so the placeholder
  873. // errSecInternalError is fine.
  874. OSStatus cssm_result = errSecInternalError;
  875. if (trust_result != kSecTrustResultInvalid) {
  876. status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
  877. if (status)
  878. return NetErrorFromOSStatus(status);
  879. }
  880. // Evaluate the results
  881. switch (trust_result) {
  882. case kSecTrustResultUnspecified:
  883. case kSecTrustResultProceed:
  884. // Certificate chain is valid and trusted ("unspecified" indicates that
  885. // the user has not explicitly set a trust setting)
  886. break;
  887. // According to SecTrust.h, kSecTrustResultConfirm isn't returned on 10.5+,
  888. // and it is marked deprecated in the 10.9 SDK.
  889. case kSecTrustResultDeny:
  890. // Certificate chain is explicitly untrusted.
  891. verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
  892. break;
  893. case kSecTrustResultFatalTrustFailure:
  894. // Certificate chain has a failure that cannot be overridden by the user.
  895. case kSecTrustResultRecoverableTrustFailure:
  896. // Certificate chain has a failure that can be overridden by the user.
  897. // Prior to 10.13, a violation of key size restrictions would, at minimum,
  898. // result in a TP_VERIFY_ACTION_FAILED error. In 10.13+, this error has
  899. // different semantics, and weak keys can no longer be distinguished
  900. // as such.
  901. verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
  902. // Walk the chain of error codes in the CSSM_TP_APPLE_EVIDENCE_INFO
  903. // structure which can catch multiple errors from each certificate.
  904. for (CFIndex index = 0, chain_count = CFArrayGetCount(completed_chain);
  905. index < chain_count; ++index) {
  906. if (chain_info[index].status_bits & CSSM_CERT_STATUS_EXPIRED ||
  907. chain_info[index].status_bits & CSSM_CERT_STATUS_NOT_VALID_YET)
  908. verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
  909. if (!IsCertStatusError(verify_result->cert_status) &&
  910. chain_info[index].status_codes.empty()) {
  911. LOG(WARNING) << "chain_info[" << index
  912. << "].status_codes is empty, chain_info[" << index
  913. << "].status_bits is " << chain_info[index].status_bits;
  914. }
  915. for (int32_t status_code : chain_info[index].status_codes) {
  916. verify_result->cert_status |= CertStatusFromOSStatus(status_code);
  917. }
  918. }
  919. if (!IsCertStatusError(verify_result->cert_status)) {
  920. LOG(ERROR) << "cssm_result=" << cssm_result;
  921. verify_result->cert_status |= CERT_STATUS_INVALID;
  922. NOTREACHED();
  923. }
  924. break;
  925. default:
  926. verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
  927. if (!IsCertStatusError(verify_result->cert_status)) {
  928. LOG(WARNING) << "trust_result=" << trust_result;
  929. verify_result->cert_status |= CERT_STATUS_INVALID;
  930. }
  931. break;
  932. }
  933. // Hostname validation is handled by CertVerifyProc, so mask off any errors
  934. // that SecTrustEvaluate may have set, as its results are not used.
  935. verify_result->cert_status &= ~CERT_STATUS_COMMON_NAME_INVALID;
  936. if (rev_checking_soft_fail) {
  937. verify_result->cert_status &= ~(CERT_STATUS_NO_REVOCATION_MECHANISM |
  938. CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
  939. }
  940. AppendPublicKeyHashesAndUpdateKnownRoot(
  941. completed_chain, &verify_result->public_key_hashes,
  942. &verify_result->is_issued_by_known_root);
  943. CertVerifyProcMac::ResultDebugData::Create(
  944. trust_result, cssm_result, std::move(chain_info), verify_result);
  945. if (IsCertStatusError(verify_result->cert_status))
  946. return MapCertStatusToNetError(verify_result->cert_status);
  947. return OK;
  948. }
  949. } // namespace
  950. CertVerifyProcMac::ResultDebugData::CertEvidenceInfo::CertEvidenceInfo() =
  951. default;
  952. CertVerifyProcMac::ResultDebugData::CertEvidenceInfo::~CertEvidenceInfo() =
  953. default;
  954. CertVerifyProcMac::ResultDebugData::CertEvidenceInfo::CertEvidenceInfo(
  955. const CertEvidenceInfo&) = default;
  956. CertVerifyProcMac::ResultDebugData::CertEvidenceInfo::CertEvidenceInfo(
  957. CertEvidenceInfo&&) = default;
  958. CertVerifyProcMac::ResultDebugData::ResultDebugData(
  959. uint32_t trust_result,
  960. int32_t result_code,
  961. std::vector<CertEvidenceInfo> status_chain)
  962. : trust_result_(trust_result),
  963. result_code_(result_code),
  964. status_chain_(std::move(status_chain)) {}
  965. CertVerifyProcMac::ResultDebugData::~ResultDebugData() = default;
  966. CertVerifyProcMac::ResultDebugData::ResultDebugData(const ResultDebugData&) =
  967. default;
  968. // static
  969. const CertVerifyProcMac::ResultDebugData*
  970. CertVerifyProcMac::ResultDebugData::Get(
  971. const base::SupportsUserData* debug_data) {
  972. return static_cast<ResultDebugData*>(
  973. debug_data->GetUserData(kResultDebugDataKey));
  974. }
  975. // static
  976. void CertVerifyProcMac::ResultDebugData::Create(
  977. uint32_t trust_result,
  978. int32_t result_code,
  979. std::vector<CertEvidenceInfo> status_chain,
  980. base::SupportsUserData* debug_data) {
  981. debug_data->SetUserData(kResultDebugDataKey,
  982. std::make_unique<ResultDebugData>(
  983. trust_result, result_code, status_chain));
  984. }
  985. std::unique_ptr<base::SupportsUserData::Data>
  986. CertVerifyProcMac::ResultDebugData::Clone() {
  987. return std::make_unique<ResultDebugData>(*this);
  988. }
  989. CertVerifyProcMac::CertVerifyProcMac() = default;
  990. CertVerifyProcMac::~CertVerifyProcMac() = default;
  991. bool CertVerifyProcMac::SupportsAdditionalTrustAnchors() const {
  992. return false;
  993. }
  994. int CertVerifyProcMac::VerifyInternal(
  995. X509Certificate* cert,
  996. const std::string& hostname,
  997. const std::string& ocsp_response,
  998. const std::string& sct_list,
  999. int flags,
  1000. CRLSet* crl_set,
  1001. const CertificateList& additional_trust_anchors,
  1002. CertVerifyResult* verify_result,
  1003. const NetLogWithSource& net_log) {
  1004. // Save the input state of |*verify_result|, which may be needed to re-do
  1005. // verification with different flags.
  1006. const CertVerifyResult input_verify_result(*verify_result);
  1007. // Check for EV policy in leaf cert.
  1008. std::string candidate_ev_policy_oid;
  1009. GetCandidateEVPolicy(cert, &candidate_ev_policy_oid);
  1010. CRLSetResult completed_chain_crl_result;
  1011. int rv = VerifyWithGivenFlags(cert, hostname, ocsp_response, sct_list, flags,
  1012. /*rev_checking_soft_fail=*/true, crl_set,
  1013. verify_result, &completed_chain_crl_result);
  1014. if (rv != OK)
  1015. return rv;
  1016. if (!candidate_ev_policy_oid.empty() &&
  1017. CheckCertChainEV(verify_result->verified_cert.get(),
  1018. candidate_ev_policy_oid)) {
  1019. // EV policies check out and the verification succeeded. Revocation checking
  1020. // may have been done, but revocation checking is not required for EV certs
  1021. // (see https://crbug.com/705285).
  1022. verify_result->cert_status |= CERT_STATUS_IS_EV;
  1023. }
  1024. LogNameNormalizationMetrics(".Mac", verify_result->verified_cert.get(),
  1025. verify_result->is_issued_by_known_root);
  1026. return OK;
  1027. }
  1028. } // namespace net
  1029. #pragma clang diagnostic pop // "-Wdeprecated-declarations"