Sorted include files.
[chromium-blink-merge.git] / net / cert / cert_verify_proc_mac.cc
blob97c0bf13de63aa81d39a77790a233eb90426aa3c
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 // Saves some information about the certificate chain |cert_chain| in
179 // |*verify_result|. The caller MUST initialize |*verify_result| before
180 // calling this function.
181 void GetCertChainInfo(CFArrayRef cert_chain,
182 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info,
183 CertVerifyResult* verify_result) {
184 SecCertificateRef verified_cert = NULL;
185 std::vector<SecCertificateRef> verified_chain;
186 for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
187 SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
188 const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
189 if (i == 0) {
190 verified_cert = chain_cert;
191 } else {
192 verified_chain.push_back(chain_cert);
195 if ((chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_IN_ANCHORS) ||
196 (chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_ROOT)) {
197 // The current certificate is either in the user's trusted store or is
198 // a root (self-signed) certificate. Ignore the signature algorithm for
199 // these certificates, as it is meaningless for security. We allow
200 // self-signed certificates (i == 0 & IS_ROOT), since we accept that
201 // any security assertions by such a cert are inherently meaningless.
202 continue;
205 x509_util::CSSMCachedCertificate cached_cert;
206 OSStatus status = cached_cert.Init(chain_cert);
207 if (status)
208 continue;
209 x509_util::CSSMFieldValue signature_field;
210 status = cached_cert.GetField(&CSSMOID_X509V1SignatureAlgorithm,
211 &signature_field);
212 if (status || !signature_field.field())
213 continue;
214 // Match the behaviour of OS X system tools and defensively check that
215 // sizes are appropriate. This would indicate a critical failure of the
216 // OS X certificate library, but based on history, it is best to play it
217 // safe.
218 const CSSM_X509_ALGORITHM_IDENTIFIER* sig_algorithm =
219 signature_field.GetAs<CSSM_X509_ALGORITHM_IDENTIFIER>();
220 if (!sig_algorithm)
221 continue;
223 const CSSM_OID* alg_oid = &sig_algorithm->algorithm;
224 if (CSSMOIDEqual(alg_oid, &CSSMOID_MD2WithRSA)) {
225 verify_result->has_md2 = true;
226 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD4WithRSA)) {
227 verify_result->has_md4 = true;
228 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD5WithRSA)) {
229 verify_result->has_md5 = true;
232 if (!verified_cert)
233 return;
235 verify_result->verified_cert =
236 X509Certificate::CreateFromHandle(verified_cert, verified_chain);
239 void AppendPublicKeyHashes(CFArrayRef chain,
240 HashValueVector* hashes) {
241 const CFIndex n = CFArrayGetCount(chain);
242 for (CFIndex i = 0; i < n; i++) {
243 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
244 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
246 CSSM_DATA cert_data;
247 OSStatus err = SecCertificateGetData(cert, &cert_data);
248 DCHECK_EQ(err, noErr);
249 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
250 cert_data.Length);
251 base::StringPiece spki_bytes;
252 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes))
253 continue;
255 HashValue sha1(HASH_VALUE_SHA1);
256 CC_SHA1(spki_bytes.data(), spki_bytes.size(), sha1.data());
257 hashes->push_back(sha1);
259 HashValue sha256(HASH_VALUE_SHA256);
260 CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data());
261 hashes->push_back(sha256);
265 bool CheckRevocationWithCRLSet(CFArrayRef chain, CRLSet* crl_set) {
266 if (CFArrayGetCount(chain) == 0)
267 return true;
269 // We iterate from the root certificate down to the leaf, keeping track of
270 // the issuer's SPKI at each step.
271 std::string issuer_spki_hash;
272 for (CFIndex i = CFArrayGetCount(chain) - 1; i >= 0; i--) {
273 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
274 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
276 CSSM_DATA cert_data;
277 OSStatus err = SecCertificateGetData(cert, &cert_data);
278 if (err != noErr) {
279 NOTREACHED();
280 continue;
282 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
283 cert_data.Length);
284 base::StringPiece spki;
285 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki)) {
286 NOTREACHED();
287 continue;
290 const std::string spki_hash = crypto::SHA256HashString(spki);
291 x509_util::CSSMCachedCertificate cached_cert;
292 if (cached_cert.Init(cert) != CSSM_OK) {
293 NOTREACHED();
294 continue;
296 x509_util::CSSMFieldValue serial_number;
297 err = cached_cert.GetField(&CSSMOID_X509V1SerialNumber, &serial_number);
298 if (err || !serial_number.field()) {
299 NOTREACHED();
300 continue;
303 base::StringPiece serial(
304 reinterpret_cast<const char*>(serial_number.field()->Data),
305 serial_number.field()->Length);
307 CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
309 if (result != CRLSet::REVOKED && !issuer_spki_hash.empty())
310 result = crl_set->CheckSerial(serial, issuer_spki_hash);
312 issuer_spki_hash = spki_hash;
314 switch (result) {
315 case CRLSet::REVOKED:
316 return false;
317 case CRLSet::UNKNOWN:
318 case CRLSet::GOOD:
319 continue;
320 default:
321 NOTREACHED();
322 return false;
326 return true;
329 // IsIssuedByKnownRoot returns true if the given chain is rooted at a root CA
330 // that we recognise as a standard root.
331 // static
332 bool IsIssuedByKnownRoot(CFArrayRef chain) {
333 int n = CFArrayGetCount(chain);
334 if (n < 1)
335 return false;
336 SecCertificateRef root_ref = reinterpret_cast<SecCertificateRef>(
337 const_cast<void*>(CFArrayGetValueAtIndex(chain, n - 1)));
338 SHA1HashValue hash = X509Certificate::CalculateFingerprint(root_ref);
339 return IsSHA1HashInSortedArray(
340 hash, &kKnownRootCertSHA1Hashes[0][0], sizeof(kKnownRootCertSHA1Hashes));
343 // Builds and evaluates a SecTrustRef for the certificate chain contained
344 // in |cert_array|, using the verification policies in |trust_policies|. On
345 // success, returns OK, and updates |trust_ref|, |trust_result|,
346 // |verified_chain|, and |chain_info| with the verification results. On
347 // failure, no output parameters are modified.
349 // Note: An OK return does not mean that |cert_array| is trusted, merely that
350 // verification was performed successfully.
352 // This function should only be called while the Mac Security Services lock is
353 // held.
354 int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array,
355 CFArrayRef trust_policies,
356 int flags,
357 ScopedCFTypeRef<SecTrustRef>* trust_ref,
358 SecTrustResultType* trust_result,
359 ScopedCFTypeRef<CFArrayRef>* verified_chain,
360 CSSM_TP_APPLE_EVIDENCE_INFO** chain_info) {
361 SecTrustRef tmp_trust = NULL;
362 OSStatus status = SecTrustCreateWithCertificates(cert_array, trust_policies,
363 &tmp_trust);
364 if (status)
365 return NetErrorFromOSStatus(status);
366 ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust);
368 if (TestRootCerts::HasInstance()) {
369 status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust);
370 if (status)
371 return NetErrorFromOSStatus(status);
374 CSSM_APPLE_TP_ACTION_DATA tp_action_data;
375 memset(&tp_action_data, 0, sizeof(tp_action_data));
376 tp_action_data.Version = CSSM_APPLE_TP_ACTION_VERSION;
377 // Allow CSSM to download any missing intermediate certificates if an
378 // authorityInfoAccess extension or issuerAltName extension is present.
379 tp_action_data.ActionFlags = CSSM_TP_ACTION_FETCH_CERT_FROM_NET |
380 CSSM_TP_ACTION_TRUST_SETTINGS;
382 // Note: For EV certificates, the Apple TP will handle setting these flags
383 // as part of EV evaluation.
384 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) {
385 // Require a positive result from an OCSP responder or a CRL (or both)
386 // for every certificate in the chain. The Apple TP automatically
387 // excludes the self-signed root from this requirement. If a certificate
388 // is missing both a crlDistributionPoints extension and an
389 // authorityInfoAccess extension with an OCSP responder URL, then we
390 // will get a kSecTrustResultRecoverableTrustFailure back from
391 // SecTrustEvaluate(), with a
392 // CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK error code. In that case,
393 // we'll set our own result to include
394 // CERT_STATUS_NO_REVOCATION_MECHANISM. If one or both extensions are
395 // present, and a check fails (server unavailable, OCSP retry later,
396 // signature mismatch), then we'll set our own result to include
397 // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION.
398 tp_action_data.ActionFlags |= CSSM_TP_ACTION_REQUIRE_REV_PER_CERT;
400 // Note, even if revocation checking is disabled, SecTrustEvaluate() will
401 // modify the OCSP options so as to attempt OCSP checking if it believes a
402 // certificate may chain to an EV root. However, because network fetches
403 // are disabled in CreateTrustPolicies() when revocation checking is
404 // disabled, these will only go against the local cache.
407 CFDataRef action_data_ref =
408 CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
409 reinterpret_cast<UInt8*>(&tp_action_data),
410 sizeof(tp_action_data), kCFAllocatorNull);
411 if (!action_data_ref)
412 return ERR_OUT_OF_MEMORY;
413 ScopedCFTypeRef<CFDataRef> scoped_action_data_ref(action_data_ref);
414 status = SecTrustSetParameters(tmp_trust, CSSM_TP_ACTION_DEFAULT,
415 action_data_ref);
416 if (status)
417 return NetErrorFromOSStatus(status);
419 // Verify the certificate. A non-zero result from SecTrustGetResult()
420 // indicates that some fatal error occurred and the chain couldn't be
421 // processed, not that the chain contains no errors. We need to examine the
422 // output of SecTrustGetResult() to determine that.
423 SecTrustResultType tmp_trust_result;
424 status = SecTrustEvaluate(tmp_trust, &tmp_trust_result);
425 if (status)
426 return NetErrorFromOSStatus(status);
427 CFArrayRef tmp_verified_chain = NULL;
428 CSSM_TP_APPLE_EVIDENCE_INFO* tmp_chain_info;
429 status = SecTrustGetResult(tmp_trust, &tmp_trust_result, &tmp_verified_chain,
430 &tmp_chain_info);
431 if (status)
432 return NetErrorFromOSStatus(status);
434 trust_ref->swap(scoped_tmp_trust);
435 *trust_result = tmp_trust_result;
436 verified_chain->reset(tmp_verified_chain);
437 *chain_info = tmp_chain_info;
439 return OK;
442 // OS X ships with both "GTE CyberTrust Global Root" and "Baltimore CyberTrust
443 // Root" as part of its trusted root store. However, a cross-certified version
444 // of the "Baltimore CyberTrust Root" exists that chains to "GTE CyberTrust
445 // Global Root". When OS X/Security.framework attempts to evaluate such a
446 // certificate chain, it disregards the "Baltimore CyberTrust Root" that exists
447 // within Keychain and instead attempts to terminate the chain in the "GTE
448 // CyberTrust Global Root". However, the GTE root is scheduled to be removed in
449 // a future OS X update (for sunsetting purposes), and once removed, such
450 // chains will fail validation, even though a trust anchor still exists.
452 // Rather than over-generalizing a solution that may mask a number of TLS
453 // misconfigurations, attempt to specifically match the affected
454 // cross-certified certificate and remove it from certificate chain processing.
455 bool IsBadBaltimoreGTECertificate(SecCertificateRef cert) {
456 // Matches the GTE-signed Baltimore CyberTrust Root
457 // https://cacert.omniroot.com/Baltimore-to-GTE-04-12.pem
458 static const SHA1HashValue kBadBaltimoreHashNew =
459 { { 0x4D, 0x34, 0xEA, 0x92, 0x76, 0x4B, 0x3A, 0x31, 0x49, 0x11,
460 0x99, 0x52, 0xF4, 0x19, 0x30, 0xCA, 0x11, 0x34, 0x83, 0x61 } };
461 // Matches the legacy GTE-signed Baltimore CyberTrust Root
462 // https://cacert.omniroot.com/gte-2-2025.pem
463 static const SHA1HashValue kBadBaltimoreHashOld =
464 { { 0x54, 0xD8, 0xCB, 0x49, 0x1F, 0xA1, 0x6D, 0xF8, 0x87, 0xDC,
465 0x94, 0xA9, 0x34, 0xCC, 0x83, 0x6B, 0xDA, 0xA8, 0xA3, 0x69 } };
467 SHA1HashValue fingerprint = X509Certificate::CalculateFingerprint(cert);
469 return fingerprint.Equals(kBadBaltimoreHashNew) ||
470 fingerprint.Equals(kBadBaltimoreHashOld);
473 // Attempts to re-verify |cert_array| after adjusting the inputs to work around
474 // known issues in OS X. To be used if BuildAndEvaluateSecTrustRef fails to
475 // return a positive result for verification.
477 // This function should only be called while the Mac Security Services lock is
478 // held.
479 void RetrySecTrustEvaluateWithAdjustedChain(
480 CFArrayRef cert_array,
481 CFArrayRef trust_policies,
482 int flags,
483 ScopedCFTypeRef<SecTrustRef>* trust_ref,
484 SecTrustResultType* trust_result,
485 ScopedCFTypeRef<CFArrayRef>* verified_chain,
486 CSSM_TP_APPLE_EVIDENCE_INFO** chain_info) {
487 CFIndex count = CFArrayGetCount(*verified_chain);
488 CFIndex slice_point = 0;
490 for (CFIndex i = 1; i < count; ++i) {
491 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
492 const_cast<void*>(CFArrayGetValueAtIndex(*verified_chain, i)));
493 if (cert == NULL)
494 return; // Strange times; can't fix things up.
496 if (IsBadBaltimoreGTECertificate(cert)) {
497 slice_point = i;
498 break;
501 if (slice_point == 0)
502 return; // Nothing to do.
504 ScopedCFTypeRef<CFMutableArrayRef> adjusted_cert_array(
505 CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks));
506 // Note: This excludes the certificate at |slice_point|.
507 CFArrayAppendArray(adjusted_cert_array, cert_array,
508 CFRangeMake(0, slice_point));
510 // Ignore the result; failure will preserve the old verification results.
511 BuildAndEvaluateSecTrustRef(
512 adjusted_cert_array, trust_policies, flags, trust_ref, trust_result,
513 verified_chain, chain_info);
516 } // namespace
518 CertVerifyProcMac::CertVerifyProcMac() {}
520 CertVerifyProcMac::~CertVerifyProcMac() {}
522 bool CertVerifyProcMac::SupportsAdditionalTrustAnchors() const {
523 return false;
526 int CertVerifyProcMac::VerifyInternal(
527 X509Certificate* cert,
528 const std::string& hostname,
529 int flags,
530 CRLSet* crl_set,
531 const CertificateList& additional_trust_anchors,
532 CertVerifyResult* verify_result) {
533 ScopedCFTypeRef<CFArrayRef> trust_policies;
534 OSStatus status = CreateTrustPolicies(hostname, flags, &trust_policies);
535 if (status)
536 return NetErrorFromOSStatus(status);
538 // Create and configure a SecTrustRef, which takes our certificate(s)
539 // and our SSL SecPolicyRef. SecTrustCreateWithCertificates() takes an
540 // array of certificates, the first of which is the certificate we're
541 // verifying, and the subsequent (optional) certificates are used for
542 // chain building.
543 ScopedCFTypeRef<CFArrayRef> cert_array(cert->CreateOSCertChainForCert());
545 // Serialize all calls that may use the Keychain, to work around various
546 // issues in OS X 10.6+ with multi-threaded access to Security.framework.
547 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
549 ScopedCFTypeRef<SecTrustRef> trust_ref;
550 SecTrustResultType trust_result = kSecTrustResultDeny;
551 ScopedCFTypeRef<CFArrayRef> completed_chain;
552 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info = NULL;
554 int rv = BuildAndEvaluateSecTrustRef(
555 cert_array, trust_policies, flags, &trust_ref, &trust_result,
556 &completed_chain, &chain_info);
557 if (rv != OK)
558 return rv;
559 if (trust_result != kSecTrustResultUnspecified &&
560 trust_result != kSecTrustResultProceed) {
561 RetrySecTrustEvaluateWithAdjustedChain(
562 cert_array, trust_policies, flags, &trust_ref, &trust_result,
563 &completed_chain, &chain_info);
566 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED)
567 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
569 if (crl_set && !CheckRevocationWithCRLSet(completed_chain, crl_set))
570 verify_result->cert_status |= CERT_STATUS_REVOKED;
572 GetCertChainInfo(completed_chain, chain_info, verify_result);
574 // As of Security Update 2012-002/OS X 10.7.4, when an RSA key < 1024 bits
575 // is encountered, CSSM returns CSSMERR_TP_VERIFY_ACTION_FAILED and adds
576 // CSSMERR_CSP_UNSUPPORTED_KEY_SIZE as a certificate status. Avoid mapping
577 // the CSSMERR_TP_VERIFY_ACTION_FAILED to CERT_STATUS_INVALID if the only
578 // error was due to an unsupported key size.
579 bool policy_failed = false;
580 bool weak_key_or_signature_algorithm = false;
582 // Evaluate the results
583 OSStatus cssm_result;
584 switch (trust_result) {
585 case kSecTrustResultUnspecified:
586 case kSecTrustResultProceed:
587 // Certificate chain is valid and trusted ("unspecified" indicates that
588 // the user has not explicitly set a trust setting)
589 break;
591 // According to SecTrust.h, kSecTrustResultConfirm isn't returned on 10.5+,
592 // and it is marked deprecated in the 10.9 SDK.
593 case kSecTrustResultDeny:
594 // Certificate chain is explicitly untrusted.
595 verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
596 break;
598 case kSecTrustResultRecoverableTrustFailure:
599 // Certificate chain has a failure that can be overridden by the user.
600 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
601 if (status)
602 return NetErrorFromOSStatus(status);
603 if (cssm_result == CSSMERR_TP_VERIFY_ACTION_FAILED) {
604 policy_failed = true;
605 } else {
606 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
608 // Walk the chain of error codes in the CSSM_TP_APPLE_EVIDENCE_INFO
609 // structure which can catch multiple errors from each certificate.
610 for (CFIndex index = 0, chain_count = CFArrayGetCount(completed_chain);
611 index < chain_count; ++index) {
612 if (chain_info[index].StatusBits & CSSM_CERT_STATUS_EXPIRED ||
613 chain_info[index].StatusBits & CSSM_CERT_STATUS_NOT_VALID_YET)
614 verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
615 if (!IsCertStatusError(verify_result->cert_status) &&
616 chain_info[index].NumStatusCodes == 0) {
617 LOG(WARNING) << "chain_info[" << index << "].NumStatusCodes is 0"
618 ", chain_info[" << index << "].StatusBits is "
619 << chain_info[index].StatusBits;
621 for (uint32 status_code_index = 0;
622 status_code_index < chain_info[index].NumStatusCodes;
623 ++status_code_index) {
624 // As of OS X 10.9, attempting to verify a certificate chain that
625 // contains a weak signature algorithm (MD2, MD5) in an intermediate
626 // or leaf cert will be treated as a (recoverable) policy validation
627 // failure, with the status code CSSMERR_TP_INVALID_CERTIFICATE
628 // added to the Status Codes. Don't treat this code as an invalid
629 // certificate; instead, map it to a weak key. Any truly invalid
630 // certificates will have the major error (cssm_result) set to
631 // CSSMERR_TP_INVALID_CERTIFICATE, rather than
632 // CSSMERR_TP_VERIFY_ACTION_FAILED.
633 CertStatus mapped_status = 0;
634 if (policy_failed &&
635 chain_info[index].StatusCodes[status_code_index] ==
636 CSSMERR_TP_INVALID_CERTIFICATE) {
637 mapped_status = CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;
638 weak_key_or_signature_algorithm = true;
639 } else {
640 mapped_status = CertStatusFromOSStatus(
641 chain_info[index].StatusCodes[status_code_index]);
642 if (mapped_status == CERT_STATUS_WEAK_KEY)
643 weak_key_or_signature_algorithm = true;
645 verify_result->cert_status |= mapped_status;
648 if (policy_failed && !weak_key_or_signature_algorithm) {
649 // If CSSMERR_TP_VERIFY_ACTION_FAILED wasn't returned due to a weak
650 // key, map it back to an appropriate error code.
651 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
653 if (!IsCertStatusError(verify_result->cert_status)) {
654 LOG(ERROR) << "cssm_result=" << cssm_result;
655 verify_result->cert_status |= CERT_STATUS_INVALID;
656 NOTREACHED();
658 break;
660 default:
661 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
662 if (status)
663 return NetErrorFromOSStatus(status);
664 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
665 if (!IsCertStatusError(verify_result->cert_status)) {
666 LOG(WARNING) << "trust_result=" << trust_result;
667 verify_result->cert_status |= CERT_STATUS_INVALID;
669 break;
672 // Perform hostname verification independent of SecTrustEvaluate. In order to
673 // do so, mask off any reported name errors first.
674 verify_result->cert_status &= ~CERT_STATUS_COMMON_NAME_INVALID;
675 if (!cert->VerifyNameMatch(hostname,
676 &verify_result->common_name_fallback_used)) {
677 verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
680 // TODO(wtc): Suppress CERT_STATUS_NO_REVOCATION_MECHANISM for now to be
681 // compatible with Windows, which in turn implements this behavior to be
682 // compatible with WinHTTP, which doesn't report this error (bug 3004).
683 verify_result->cert_status &= ~CERT_STATUS_NO_REVOCATION_MECHANISM;
685 AppendPublicKeyHashes(completed_chain, &verify_result->public_key_hashes);
686 verify_result->is_issued_by_known_root = IsIssuedByKnownRoot(completed_chain);
688 if (IsCertStatusError(verify_result->cert_status))
689 return MapCertStatusToNetError(verify_result->cert_status);
691 if (flags & CertVerifier::VERIFY_EV_CERT) {
692 // Determine the certificate's EV status using SecTrustCopyExtendedResult(),
693 // which is an internal/private API function added in OS X 10.5.7.
694 // Note: "ExtendedResult" means extended validation results.
695 CFBundleRef bundle =
696 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"));
697 if (bundle) {
698 SecTrustCopyExtendedResultFuncPtr copy_extended_result =
699 reinterpret_cast<SecTrustCopyExtendedResultFuncPtr>(
700 CFBundleGetFunctionPointerForName(bundle,
701 CFSTR("SecTrustCopyExtendedResult")));
702 if (copy_extended_result) {
703 CFDictionaryRef ev_dict_temp = NULL;
704 status = copy_extended_result(trust_ref, &ev_dict_temp);
705 ScopedCFTypeRef<CFDictionaryRef> ev_dict(ev_dict_temp);
706 ev_dict_temp = NULL;
707 if (status == noErr && ev_dict) {
708 // In 10.7.3, SecTrustCopyExtendedResult returns noErr and populates
709 // ev_dict even for non-EV certificates, but only EV certificates
710 // will cause ev_dict to contain kSecEVOrganizationName. In previous
711 // releases, SecTrustCopyExtendedResult would only return noErr and
712 // populate ev_dict for EV certificates, but would always include
713 // kSecEVOrganizationName in that case, so checking for this key is
714 // appropriate for all known versions of SecTrustCopyExtendedResult.
715 // The actual organization name is unneeded here and can be accessed
716 // through other means. All that matters here is the OS' conception
717 // of whether or not the certificate is EV.
718 if (CFDictionaryContainsKey(ev_dict,
719 kSecEVOrganizationName)) {
720 verify_result->cert_status |= CERT_STATUS_IS_EV;
721 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY)
722 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
729 return OK;
732 } // namespace net