Remove linux_chromium_gn_dbg from the chromium CQ.
[chromium-blink-merge.git] / net / cert / cert_verify_proc_mac.cc
blobc0eb0683ffaf2704641960d6b7b1756295c1bd61
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.
5 #include "net/cert/cert_verify_proc_mac.h"
7 #include <CommonCrypto/CommonDigest.h>
8 #include <CoreServices/CoreServices.h>
9 #include <Security/Security.h>
11 #include <string>
12 #include <vector>
14 #include "base/logging.h"
15 #include "base/mac/mac_logging.h"
16 #include "base/mac/scoped_cftyperef.h"
17 #include "base/sha1.h"
18 #include "base/strings/string_piece.h"
19 #include "base/synchronization/lock.h"
20 #include "crypto/mac_security_services_lock.h"
21 #include "crypto/sha2.h"
22 #include "net/base/net_errors.h"
23 #include "net/cert/asn1_util.h"
24 #include "net/cert/cert_status_flags.h"
25 #include "net/cert/cert_verifier.h"
26 #include "net/cert/cert_verify_result.h"
27 #include "net/cert/crl_set.h"
28 #include "net/cert/test_root_certs.h"
29 #include "net/cert/x509_certificate.h"
30 #include "net/cert/x509_certificate_known_roots_mac.h"
31 #include "net/cert/x509_util_mac.h"
33 // From 10.7.2 libsecurity_keychain-55035/lib/SecTrustPriv.h, for use with
34 // SecTrustCopyExtendedResult.
35 #ifndef kSecEVOrganizationName
36 #define kSecEVOrganizationName CFSTR("Organization")
37 #endif
39 using base::ScopedCFTypeRef;
41 namespace net {
43 namespace {
45 typedef OSStatus (*SecTrustCopyExtendedResultFuncPtr)(SecTrustRef,
46 CFDictionaryRef*);
48 int NetErrorFromOSStatus(OSStatus status) {
49 switch (status) {
50 case noErr:
51 return OK;
52 case errSecNotAvailable:
53 case errSecNoCertificateModule:
54 case errSecNoPolicyModule:
55 return ERR_NOT_IMPLEMENTED;
56 case errSecAuthFailed:
57 return ERR_ACCESS_DENIED;
58 default: {
59 OSSTATUS_LOG(ERROR, status) << "Unknown error mapped to ERR_FAILED";
60 return ERR_FAILED;
65 CertStatus CertStatusFromOSStatus(OSStatus status) {
66 switch (status) {
67 case noErr:
68 return 0;
70 case CSSMERR_TP_INVALID_ANCHOR_CERT:
71 case CSSMERR_TP_NOT_TRUSTED:
72 case CSSMERR_TP_INVALID_CERT_AUTHORITY:
73 return CERT_STATUS_AUTHORITY_INVALID;
75 case CSSMERR_TP_CERT_EXPIRED:
76 case CSSMERR_TP_CERT_NOT_VALID_YET:
77 // "Expired" and "not yet valid" collapse into a single status.
78 return CERT_STATUS_DATE_INVALID;
80 case CSSMERR_TP_CERT_REVOKED:
81 case CSSMERR_TP_CERT_SUSPENDED:
82 return CERT_STATUS_REVOKED;
84 case CSSMERR_APPLETP_HOSTNAME_MISMATCH:
85 return CERT_STATUS_COMMON_NAME_INVALID;
87 case CSSMERR_APPLETP_CRL_NOT_FOUND:
88 case CSSMERR_APPLETP_OCSP_UNAVAILABLE:
89 case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
90 return CERT_STATUS_NO_REVOCATION_MECHANISM;
92 case CSSMERR_APPLETP_CRL_EXPIRED:
93 case CSSMERR_APPLETP_CRL_NOT_VALID_YET:
94 case CSSMERR_APPLETP_CRL_SERVER_DOWN:
95 case CSSMERR_APPLETP_CRL_NOT_TRUSTED:
96 case CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT:
97 case CSSMERR_APPLETP_CRL_POLICY_FAIL:
98 case CSSMERR_APPLETP_OCSP_BAD_RESPONSE:
99 case CSSMERR_APPLETP_OCSP_BAD_REQUEST:
100 case CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED:
101 case CSSMERR_APPLETP_NETWORK_FAILURE:
102 case CSSMERR_APPLETP_OCSP_NOT_TRUSTED:
103 case CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT:
104 case CSSMERR_APPLETP_OCSP_SIG_ERROR:
105 case CSSMERR_APPLETP_OCSP_NO_SIGNER:
106 case CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ:
107 case CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR:
108 case CSSMERR_APPLETP_OCSP_RESP_TRY_LATER:
109 case CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED:
110 case CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED:
111 case CSSMERR_APPLETP_OCSP_NONCE_MISMATCH:
112 // We asked for a revocation check, but didn't get it.
113 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
115 case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE:
116 // TODO(wtc): Should we add CERT_STATUS_WRONG_USAGE?
117 return CERT_STATUS_INVALID;
119 case CSSMERR_APPLETP_CRL_BAD_URI:
120 case CSSMERR_APPLETP_IDP_FAIL:
121 return CERT_STATUS_INVALID;
123 case CSSMERR_CSP_UNSUPPORTED_KEY_SIZE:
124 // Mapping UNSUPPORTED_KEY_SIZE to CERT_STATUS_WEAK_KEY is not strictly
125 // accurate, as the error may have been returned due to a key size
126 // that exceeded the maximum supported. However, within
127 // CertVerifyProcMac::VerifyInternal(), this code should only be
128 // encountered as a certificate status code, and only when the key size
129 // is smaller than the minimum required (1024 bits).
130 return CERT_STATUS_WEAK_KEY;
132 default: {
133 // Failure was due to something Chromium doesn't define a
134 // specific status for (such as basic constraints violation, or
135 // unknown critical extension)
136 OSSTATUS_LOG(WARNING, status)
137 << "Unknown error mapped to CERT_STATUS_INVALID";
138 return CERT_STATUS_INVALID;
143 // Creates a series of SecPolicyRefs to be added to a SecTrustRef used to
144 // validate a certificate for an SSL server. |hostname| contains the name of
145 // the SSL server that the certificate should be verified against. |flags| is
146 // a bitwise-OR of VerifyFlags that can further alter how trust is validated,
147 // such as how revocation is checked. If successful, returns noErr, and
148 // stores the resultant array of SecPolicyRefs in |policies|.
149 OSStatus CreateTrustPolicies(const std::string& hostname,
150 int flags,
151 ScopedCFTypeRef<CFArrayRef>* policies) {
152 ScopedCFTypeRef<CFMutableArrayRef> local_policies(
153 CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
154 if (!local_policies)
155 return memFullErr;
157 SecPolicyRef ssl_policy;
158 OSStatus status = x509_util::CreateSSLServerPolicy(hostname, &ssl_policy);
159 if (status)
160 return status;
161 CFArrayAppendValue(local_policies, ssl_policy);
162 CFRelease(ssl_policy);
164 // Explicitly add revocation policies, in order to override system
165 // revocation checking policies and instead respect the application-level
166 // revocation preference.
167 status = x509_util::CreateRevocationPolicies(
168 (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED),
169 (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY),
170 local_policies);
171 if (status)
172 return status;
174 policies->reset(local_policies.release());
175 return noErr;
178 // Stores the constructed certificate chain |cert_chain| and information about
179 // the signature algorithms used into |*verify_result|. If the leaf cert in
180 // |cert_chain| contains a weak (MD2, MD4, MD5, SHA-1) signature, stores that
181 // in |*leaf_is_weak|. |cert_chain| must not be empty.
182 void GetCertChainInfo(CFArrayRef cert_chain,
183 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info,
184 CertVerifyResult* verify_result,
185 bool* leaf_is_weak) {
186 DCHECK_LT(0, CFArrayGetCount(cert_chain));
188 *leaf_is_weak = false;
189 verify_result->has_md2 = false;
190 verify_result->has_md4 = false;
191 verify_result->has_md5 = false;
192 verify_result->has_sha1 = false;
194 SecCertificateRef verified_cert = NULL;
195 std::vector<SecCertificateRef> verified_chain;
196 for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
197 SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
198 const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
199 if (i == 0) {
200 verified_cert = chain_cert;
201 } else {
202 verified_chain.push_back(chain_cert);
205 if ((chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_IN_ANCHORS) ||
206 (chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_ROOT)) {
207 // The current certificate is either in the user's trusted store or is
208 // a root (self-signed) certificate. Ignore the signature algorithm for
209 // these certificates, as it is meaningless for security. We allow
210 // self-signed certificates (i == 0 & IS_ROOT), since we accept that
211 // any security assertions by such a cert are inherently meaningless.
212 continue;
215 x509_util::CSSMCachedCertificate cached_cert;
216 OSStatus status = cached_cert.Init(chain_cert);
217 if (status)
218 continue;
219 x509_util::CSSMFieldValue signature_field;
220 status = cached_cert.GetField(&CSSMOID_X509V1SignatureAlgorithm,
221 &signature_field);
222 if (status || !signature_field.field())
223 continue;
224 // Match the behaviour of OS X system tools and defensively check that
225 // sizes are appropriate. This would indicate a critical failure of the
226 // OS X certificate library, but based on history, it is best to play it
227 // safe.
228 const CSSM_X509_ALGORITHM_IDENTIFIER* sig_algorithm =
229 signature_field.GetAs<CSSM_X509_ALGORITHM_IDENTIFIER>();
230 if (!sig_algorithm)
231 continue;
233 const CSSM_OID* alg_oid = &sig_algorithm->algorithm;
234 if (CSSMOIDEqual(alg_oid, &CSSMOID_MD2WithRSA)) {
235 verify_result->has_md2 = true;
236 if (i == 0)
237 *leaf_is_weak = true;
238 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD4WithRSA)) {
239 verify_result->has_md4 = true;
240 if (i == 0)
241 *leaf_is_weak = true;
242 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD5WithRSA)) {
243 verify_result->has_md5 = true;
244 if (i == 0)
245 *leaf_is_weak = true;
246 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithRSA) ||
247 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithRSA_OIW) ||
248 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA) ||
249 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA_CMS) ||
250 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA_JDK) ||
251 CSSMOIDEqual(alg_oid, &CSSMOID_ECDSA_WithSHA1)) {
252 verify_result->has_sha1 = true;
253 if (i == 0)
254 *leaf_is_weak = true;
257 if (!verified_cert) {
258 NOTREACHED();
259 return;
262 verify_result->verified_cert =
263 X509Certificate::CreateFromHandle(verified_cert, verified_chain);
266 void AppendPublicKeyHashes(CFArrayRef chain,
267 HashValueVector* hashes) {
268 const CFIndex n = CFArrayGetCount(chain);
269 for (CFIndex i = 0; i < n; i++) {
270 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
271 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
273 CSSM_DATA cert_data;
274 OSStatus err = SecCertificateGetData(cert, &cert_data);
275 DCHECK_EQ(err, noErr);
276 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
277 cert_data.Length);
278 base::StringPiece spki_bytes;
279 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes))
280 continue;
282 HashValue sha1(HASH_VALUE_SHA1);
283 CC_SHA1(spki_bytes.data(), spki_bytes.size(), sha1.data());
284 hashes->push_back(sha1);
286 HashValue sha256(HASH_VALUE_SHA256);
287 CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data());
288 hashes->push_back(sha256);
292 bool CheckRevocationWithCRLSet(CFArrayRef chain, CRLSet* crl_set) {
293 if (CFArrayGetCount(chain) == 0)
294 return true;
296 // We iterate from the root certificate down to the leaf, keeping track of
297 // the issuer's SPKI at each step.
298 std::string issuer_spki_hash;
299 for (CFIndex i = CFArrayGetCount(chain) - 1; i >= 0; i--) {
300 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
301 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
303 CSSM_DATA cert_data;
304 OSStatus err = SecCertificateGetData(cert, &cert_data);
305 if (err != noErr) {
306 NOTREACHED();
307 continue;
309 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
310 cert_data.Length);
311 base::StringPiece spki;
312 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki)) {
313 NOTREACHED();
314 continue;
317 const std::string spki_hash = crypto::SHA256HashString(spki);
318 x509_util::CSSMCachedCertificate cached_cert;
319 if (cached_cert.Init(cert) != CSSM_OK) {
320 NOTREACHED();
321 continue;
323 x509_util::CSSMFieldValue serial_number;
324 err = cached_cert.GetField(&CSSMOID_X509V1SerialNumber, &serial_number);
325 if (err || !serial_number.field()) {
326 NOTREACHED();
327 continue;
330 base::StringPiece serial(
331 reinterpret_cast<const char*>(serial_number.field()->Data),
332 serial_number.field()->Length);
334 CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
336 if (result != CRLSet::REVOKED && !issuer_spki_hash.empty())
337 result = crl_set->CheckSerial(serial, issuer_spki_hash);
339 issuer_spki_hash = spki_hash;
341 switch (result) {
342 case CRLSet::REVOKED:
343 return false;
344 case CRLSet::UNKNOWN:
345 case CRLSet::GOOD:
346 continue;
347 default:
348 NOTREACHED();
349 return false;
353 return true;
356 // IsIssuedByKnownRoot returns true if the given chain is rooted at a root CA
357 // that we recognise as a standard root.
358 // static
359 bool IsIssuedByKnownRoot(CFArrayRef chain) {
360 int n = CFArrayGetCount(chain);
361 if (n < 1)
362 return false;
363 SecCertificateRef root_ref = reinterpret_cast<SecCertificateRef>(
364 const_cast<void*>(CFArrayGetValueAtIndex(chain, n - 1)));
365 SHA1HashValue hash = X509Certificate::CalculateFingerprint(root_ref);
366 return IsSHA1HashInSortedArray(
367 hash, &kKnownRootCertSHA1Hashes[0][0], sizeof(kKnownRootCertSHA1Hashes));
370 // Builds and evaluates a SecTrustRef for the certificate chain contained
371 // in |cert_array|, using the verification policies in |trust_policies|. On
372 // success, returns OK, and updates |trust_ref|, |trust_result|,
373 // |verified_chain|, and |chain_info| with the verification results. On
374 // failure, no output parameters are modified.
376 // Note: An OK return does not mean that |cert_array| is trusted, merely that
377 // verification was performed successfully.
379 // This function should only be called while the Mac Security Services lock is
380 // held.
381 int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array,
382 CFArrayRef trust_policies,
383 int flags,
384 ScopedCFTypeRef<SecTrustRef>* trust_ref,
385 SecTrustResultType* trust_result,
386 ScopedCFTypeRef<CFArrayRef>* verified_chain,
387 CSSM_TP_APPLE_EVIDENCE_INFO** chain_info) {
388 SecTrustRef tmp_trust = NULL;
389 OSStatus status = SecTrustCreateWithCertificates(cert_array, trust_policies,
390 &tmp_trust);
391 if (status)
392 return NetErrorFromOSStatus(status);
393 ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust);
395 if (TestRootCerts::HasInstance()) {
396 status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust);
397 if (status)
398 return NetErrorFromOSStatus(status);
401 CSSM_APPLE_TP_ACTION_DATA tp_action_data;
402 memset(&tp_action_data, 0, sizeof(tp_action_data));
403 tp_action_data.Version = CSSM_APPLE_TP_ACTION_VERSION;
404 // Allow CSSM to download any missing intermediate certificates if an
405 // authorityInfoAccess extension or issuerAltName extension is present.
406 tp_action_data.ActionFlags = CSSM_TP_ACTION_FETCH_CERT_FROM_NET |
407 CSSM_TP_ACTION_TRUST_SETTINGS;
409 // Note: For EV certificates, the Apple TP will handle setting these flags
410 // as part of EV evaluation.
411 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) {
412 // Require a positive result from an OCSP responder or a CRL (or both)
413 // for every certificate in the chain. The Apple TP automatically
414 // excludes the self-signed root from this requirement. If a certificate
415 // is missing both a crlDistributionPoints extension and an
416 // authorityInfoAccess extension with an OCSP responder URL, then we
417 // will get a kSecTrustResultRecoverableTrustFailure back from
418 // SecTrustEvaluate(), with a
419 // CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK error code. In that case,
420 // we'll set our own result to include
421 // CERT_STATUS_NO_REVOCATION_MECHANISM. If one or both extensions are
422 // present, and a check fails (server unavailable, OCSP retry later,
423 // signature mismatch), then we'll set our own result to include
424 // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION.
425 tp_action_data.ActionFlags |= CSSM_TP_ACTION_REQUIRE_REV_PER_CERT;
427 // Note, even if revocation checking is disabled, SecTrustEvaluate() will
428 // modify the OCSP options so as to attempt OCSP checking if it believes a
429 // certificate may chain to an EV root. However, because network fetches
430 // are disabled in CreateTrustPolicies() when revocation checking is
431 // disabled, these will only go against the local cache.
434 CFDataRef action_data_ref =
435 CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
436 reinterpret_cast<UInt8*>(&tp_action_data),
437 sizeof(tp_action_data), kCFAllocatorNull);
438 if (!action_data_ref)
439 return ERR_OUT_OF_MEMORY;
440 ScopedCFTypeRef<CFDataRef> scoped_action_data_ref(action_data_ref);
441 status = SecTrustSetParameters(tmp_trust, CSSM_TP_ACTION_DEFAULT,
442 action_data_ref);
443 if (status)
444 return NetErrorFromOSStatus(status);
446 // Verify the certificate. A non-zero result from SecTrustGetResult()
447 // indicates that some fatal error occurred and the chain couldn't be
448 // processed, not that the chain contains no errors. We need to examine the
449 // output of SecTrustGetResult() to determine that.
450 SecTrustResultType tmp_trust_result;
451 status = SecTrustEvaluate(tmp_trust, &tmp_trust_result);
452 if (status)
453 return NetErrorFromOSStatus(status);
454 CFArrayRef tmp_verified_chain = NULL;
455 CSSM_TP_APPLE_EVIDENCE_INFO* tmp_chain_info;
456 status = SecTrustGetResult(tmp_trust, &tmp_trust_result, &tmp_verified_chain,
457 &tmp_chain_info);
458 if (status)
459 return NetErrorFromOSStatus(status);
461 trust_ref->swap(scoped_tmp_trust);
462 *trust_result = tmp_trust_result;
463 verified_chain->reset(tmp_verified_chain);
464 *chain_info = tmp_chain_info;
466 return OK;
469 } // namespace
471 CertVerifyProcMac::CertVerifyProcMac() {}
473 CertVerifyProcMac::~CertVerifyProcMac() {}
475 bool CertVerifyProcMac::SupportsAdditionalTrustAnchors() const {
476 return false;
479 bool CertVerifyProcMac::SupportsOCSPStapling() const {
480 // TODO(rsleevi): Plumb an OCSP response into the Mac system library.
481 // https://crbug.com/430714
482 return false;
485 int CertVerifyProcMac::VerifyInternal(
486 X509Certificate* cert,
487 const std::string& hostname,
488 const std::string& ocsp_response,
489 int flags,
490 CRLSet* crl_set,
491 const CertificateList& additional_trust_anchors,
492 CertVerifyResult* verify_result) {
493 ScopedCFTypeRef<CFArrayRef> trust_policies;
494 OSStatus status = CreateTrustPolicies(hostname, flags, &trust_policies);
495 if (status)
496 return NetErrorFromOSStatus(status);
498 // Create and configure a SecTrustRef, which takes our certificate(s)
499 // and our SSL SecPolicyRef. SecTrustCreateWithCertificates() takes an
500 // array of certificates, the first of which is the certificate we're
501 // verifying, and the subsequent (optional) certificates are used for
502 // chain building.
503 ScopedCFTypeRef<CFMutableArrayRef> cert_array(
504 cert->CreateOSCertChainForCert());
506 // Serialize all calls that may use the Keychain, to work around various
507 // issues in OS X 10.6+ with multi-threaded access to Security.framework.
508 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
510 ScopedCFTypeRef<SecTrustRef> trust_ref;
511 SecTrustResultType trust_result = kSecTrustResultDeny;
512 ScopedCFTypeRef<CFArrayRef> completed_chain;
513 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info = NULL;
514 bool candidate_untrusted = true;
515 bool candidate_weak = false;
517 // OS X lacks proper path discovery; it will take the input certs and never
518 // backtrack the graph attempting to discover valid paths.
519 // This can create issues in some situations:
520 // - When OS X changes the trust store, there may be a chain
521 // A -> B -> C -> D
522 // where OS X trusts D (on some versions) and trusts C (on some versions).
523 // If a server supplies a chain A, B, C (cross-signed by D), then this chain
524 // will successfully validate on systems that trust D, but fail for systems
525 // that trust C. If the server supplies a chain of A -> B, then it forces
526 // all clients to fetch C (via AIA) if they trust D, and not all clients
527 // (notably, Firefox and Android) will do this, thus breaking them.
528 // An example of this is the Verizon Business Services root - GTE CyberTrust
529 // and Baltimore CyberTrust roots represent old and new roots that cause
530 // issues depending on which version of OS X being used.
532 // - A server may be (misconfigured) to send an expired intermediate
533 // certificate. On platforms with path discovery, the graph traversal
534 // will back up to immediately before this intermediate, and then
535 // attempt an AIA fetch or retrieval from local store. However, OS X
536 // does not do this, and thus prevents access. While this is ostensibly
537 // a server misconfiguration issue, the fact that it works on other
538 // platforms is a jarring inconsistency for users.
540 // - When OS X trusts both C and D (simultaneously), it's possible that the
541 // version of C signed by D is signed using a weak algorithm (e.g. SHA-1),
542 // while the version of C in the trust store's signature doesn't matter.
543 // Since a 'strong' chain exists, it would be desirable to prefer this
544 // chain.
546 // - A variant of the above example, it may be that the version of B sent by
547 // the server is signed using a weak algorithm, but the version of B
548 // present in the AIA of A is signed using a strong algorithm. Since a
549 // 'strong' chain exists, it would be desirable to prefer this chain.
551 // Because of this, the code below first attempts to validate the peer's
552 // identity using the supplied chain. If it is not trusted (e.g. the OS only
553 // trusts C, but the version of C signed by D was sent, and D is not trusted),
554 // or if it contains a weak chain, it will begin lopping off certificates
555 // from the end of the chain and attempting to verify. If a stronger, trusted
556 // chain is found, it is used, otherwise, the algorithm continues until only
557 // the peer's certificate remains.
559 // This does cause a performance hit for these users, but only in cases where
560 // OS X is building weaker chains than desired, or when it would otherwise
561 // fail the connection.
562 while (CFArrayGetCount(cert_array) > 0) {
563 ScopedCFTypeRef<SecTrustRef> temp_ref;
564 SecTrustResultType temp_trust_result = kSecTrustResultDeny;
565 ScopedCFTypeRef<CFArrayRef> temp_chain;
566 CSSM_TP_APPLE_EVIDENCE_INFO* temp_chain_info = NULL;
568 int rv = BuildAndEvaluateSecTrustRef(cert_array, trust_policies, flags,
569 &temp_ref, &temp_trust_result,
570 &temp_chain, &temp_chain_info);
571 if (rv != OK)
572 return rv;
574 bool untrusted = (temp_trust_result != kSecTrustResultUnspecified &&
575 temp_trust_result != kSecTrustResultProceed);
576 bool weak_chain = false;
577 if (CFArrayGetCount(temp_chain) == 0) {
578 // If the chain is empty, it cannot be trusted or have recoverable
579 // errors.
580 DCHECK(untrusted);
581 DCHECK_NE(kSecTrustResultRecoverableTrustFailure, temp_trust_result);
582 } else {
583 CertVerifyResult temp_verify_result;
584 bool leaf_is_weak = false;
585 GetCertChainInfo(temp_chain, temp_chain_info, &temp_verify_result,
586 &leaf_is_weak);
587 weak_chain = !leaf_is_weak &&
588 (temp_verify_result.has_md2 || temp_verify_result.has_md4 ||
589 temp_verify_result.has_md5 || temp_verify_result.has_sha1);
591 // Set the result to the current chain if:
592 // - This is the first verification attempt. This ensures that if
593 // everything is awful (e.g. it may just be an untrusted cert), that
594 // what is reported is exactly what was sent by the server
595 // - If the current chain is trusted, and the old chain was not trusted,
596 // then prefer this chain. This ensures that if there is at least a
597 // valid path to a trust anchor, it's preferred over reporting an error.
598 // - If the current chain is trusted, and the old chain is trusted, but
599 // the old chain contained weak algorithms while the current chain only
600 // contains strong algorithms, then prefer the current chain over the
601 // old chain.
603 // Note: If the leaf certificate itself is weak, then the only
604 // consideration is whether or not there is a trusted chain. That's
605 // because no amount of path discovery will fix a weak leaf.
606 if (!trust_ref || (!untrusted && (candidate_untrusted ||
607 (candidate_weak && !weak_chain)))) {
608 trust_ref = temp_ref;
609 trust_result = temp_trust_result;
610 completed_chain = temp_chain;
611 chain_info = temp_chain_info;
613 candidate_untrusted = untrusted;
614 candidate_weak = weak_chain;
616 // Short-circuit when a current, trusted chain is found.
617 if (!untrusted && !weak_chain)
618 break;
619 CFArrayRemoveValueAtIndex(cert_array, CFArrayGetCount(cert_array) - 1);
622 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED)
623 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
625 if (crl_set && !CheckRevocationWithCRLSet(completed_chain, crl_set))
626 verify_result->cert_status |= CERT_STATUS_REVOKED;
628 if (CFArrayGetCount(completed_chain) > 0) {
629 bool leaf_is_weak_unused = false;
630 GetCertChainInfo(completed_chain, chain_info, verify_result,
631 &leaf_is_weak_unused);
634 // As of Security Update 2012-002/OS X 10.7.4, when an RSA key < 1024 bits
635 // is encountered, CSSM returns CSSMERR_TP_VERIFY_ACTION_FAILED and adds
636 // CSSMERR_CSP_UNSUPPORTED_KEY_SIZE as a certificate status. Avoid mapping
637 // the CSSMERR_TP_VERIFY_ACTION_FAILED to CERT_STATUS_INVALID if the only
638 // error was due to an unsupported key size.
639 bool policy_failed = false;
640 bool weak_key_or_signature_algorithm = false;
642 // Evaluate the results
643 OSStatus cssm_result;
644 switch (trust_result) {
645 case kSecTrustResultUnspecified:
646 case kSecTrustResultProceed:
647 // Certificate chain is valid and trusted ("unspecified" indicates that
648 // the user has not explicitly set a trust setting)
649 break;
651 // According to SecTrust.h, kSecTrustResultConfirm isn't returned on 10.5+,
652 // and it is marked deprecated in the 10.9 SDK.
653 case kSecTrustResultDeny:
654 // Certificate chain is explicitly untrusted.
655 verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
656 break;
658 case kSecTrustResultRecoverableTrustFailure:
659 // Certificate chain has a failure that can be overridden by the user.
660 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
661 if (status)
662 return NetErrorFromOSStatus(status);
663 if (cssm_result == CSSMERR_TP_VERIFY_ACTION_FAILED) {
664 policy_failed = true;
665 } else {
666 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
668 // Walk the chain of error codes in the CSSM_TP_APPLE_EVIDENCE_INFO
669 // structure which can catch multiple errors from each certificate.
670 for (CFIndex index = 0, chain_count = CFArrayGetCount(completed_chain);
671 index < chain_count; ++index) {
672 if (chain_info[index].StatusBits & CSSM_CERT_STATUS_EXPIRED ||
673 chain_info[index].StatusBits & CSSM_CERT_STATUS_NOT_VALID_YET)
674 verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
675 if (!IsCertStatusError(verify_result->cert_status) &&
676 chain_info[index].NumStatusCodes == 0) {
677 LOG(WARNING) << "chain_info[" << index << "].NumStatusCodes is 0"
678 ", chain_info[" << index << "].StatusBits is "
679 << chain_info[index].StatusBits;
681 for (uint32_t status_code_index = 0;
682 status_code_index < chain_info[index].NumStatusCodes;
683 ++status_code_index) {
684 // As of OS X 10.9, attempting to verify a certificate chain that
685 // contains a weak signature algorithm (MD2, MD5) in an intermediate
686 // or leaf cert will be treated as a (recoverable) policy validation
687 // failure, with the status code CSSMERR_TP_INVALID_CERTIFICATE
688 // added to the Status Codes. Don't treat this code as an invalid
689 // certificate; instead, map it to a weak key. Any truly invalid
690 // certificates will have the major error (cssm_result) set to
691 // CSSMERR_TP_INVALID_CERTIFICATE, rather than
692 // CSSMERR_TP_VERIFY_ACTION_FAILED.
693 CertStatus mapped_status = 0;
694 if (policy_failed &&
695 chain_info[index].StatusCodes[status_code_index] ==
696 CSSMERR_TP_INVALID_CERTIFICATE) {
697 mapped_status = CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;
698 weak_key_or_signature_algorithm = true;
699 } else {
700 mapped_status = CertStatusFromOSStatus(
701 chain_info[index].StatusCodes[status_code_index]);
702 if (mapped_status == CERT_STATUS_WEAK_KEY)
703 weak_key_or_signature_algorithm = true;
705 verify_result->cert_status |= mapped_status;
708 if (policy_failed && !weak_key_or_signature_algorithm) {
709 // If CSSMERR_TP_VERIFY_ACTION_FAILED wasn't returned due to a weak
710 // key, map it back to an appropriate error code.
711 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
713 if (!IsCertStatusError(verify_result->cert_status)) {
714 LOG(ERROR) << "cssm_result=" << cssm_result;
715 verify_result->cert_status |= CERT_STATUS_INVALID;
716 NOTREACHED();
718 break;
720 default:
721 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
722 if (status)
723 return NetErrorFromOSStatus(status);
724 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
725 if (!IsCertStatusError(verify_result->cert_status)) {
726 LOG(WARNING) << "trust_result=" << trust_result;
727 verify_result->cert_status |= CERT_STATUS_INVALID;
729 break;
732 // Perform hostname verification independent of SecTrustEvaluate. In order to
733 // do so, mask off any reported name errors first.
734 verify_result->cert_status &= ~CERT_STATUS_COMMON_NAME_INVALID;
735 if (!cert->VerifyNameMatch(hostname,
736 &verify_result->common_name_fallback_used)) {
737 verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
740 // TODO(wtc): Suppress CERT_STATUS_NO_REVOCATION_MECHANISM for now to be
741 // compatible with Windows, which in turn implements this behavior to be
742 // compatible with WinHTTP, which doesn't report this error (bug 3004).
743 verify_result->cert_status &= ~CERT_STATUS_NO_REVOCATION_MECHANISM;
745 AppendPublicKeyHashes(completed_chain, &verify_result->public_key_hashes);
746 verify_result->is_issued_by_known_root = IsIssuedByKnownRoot(completed_chain);
748 if (IsCertStatusError(verify_result->cert_status))
749 return MapCertStatusToNetError(verify_result->cert_status);
751 if (flags & CertVerifier::VERIFY_EV_CERT) {
752 // Determine the certificate's EV status using SecTrustCopyExtendedResult(),
753 // which is an internal/private API function added in OS X 10.5.7.
754 // Note: "ExtendedResult" means extended validation results.
755 CFBundleRef bundle =
756 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"));
757 if (bundle) {
758 SecTrustCopyExtendedResultFuncPtr copy_extended_result =
759 reinterpret_cast<SecTrustCopyExtendedResultFuncPtr>(
760 CFBundleGetFunctionPointerForName(bundle,
761 CFSTR("SecTrustCopyExtendedResult")));
762 if (copy_extended_result) {
763 CFDictionaryRef ev_dict_temp = NULL;
764 status = copy_extended_result(trust_ref, &ev_dict_temp);
765 ScopedCFTypeRef<CFDictionaryRef> ev_dict(ev_dict_temp);
766 ev_dict_temp = NULL;
767 if (status == noErr && ev_dict) {
768 // In 10.7.3, SecTrustCopyExtendedResult returns noErr and populates
769 // ev_dict even for non-EV certificates, but only EV certificates
770 // will cause ev_dict to contain kSecEVOrganizationName. In previous
771 // releases, SecTrustCopyExtendedResult would only return noErr and
772 // populate ev_dict for EV certificates, but would always include
773 // kSecEVOrganizationName in that case, so checking for this key is
774 // appropriate for all known versions of SecTrustCopyExtendedResult.
775 // The actual organization name is unneeded here and can be accessed
776 // through other means. All that matters here is the OS' conception
777 // of whether or not the certificate is EV.
778 if (CFDictionaryContainsKey(ev_dict,
779 kSecEVOrganizationName)) {
780 verify_result->cert_status |= CERT_STATUS_IS_EV;
781 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY)
782 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
789 return OK;
792 } // namespace net