Update nss_revision to 235242.
[chromium-blink-merge.git] / net / cert / cert_verify_proc_mac.cc
blob542fba1151459814e7629aa12f23fa1ad3022494
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/nss_util.h"
22 #include "crypto/sha2.h"
23 #include "net/base/net_errors.h"
24 #include "net/cert/asn1_util.h"
25 #include "net/cert/cert_status_flags.h"
26 #include "net/cert/cert_verifier.h"
27 #include "net/cert/cert_verify_result.h"
28 #include "net/cert/crl_set.h"
29 #include "net/cert/test_root_certs.h"
30 #include "net/cert/x509_certificate.h"
31 #include "net/cert/x509_certificate_known_roots_mac.h"
32 #include "net/cert/x509_util_mac.h"
34 // From 10.7.2 libsecurity_keychain-55035/lib/SecTrustPriv.h, for use with
35 // SecTrustCopyExtendedResult.
36 #ifndef kSecEVOrganizationName
37 #define kSecEVOrganizationName CFSTR("Organization")
38 #endif
40 using base::ScopedCFTypeRef;
42 namespace net {
44 namespace {
46 typedef OSStatus (*SecTrustCopyExtendedResultFuncPtr)(SecTrustRef,
47 CFDictionaryRef*);
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;
66 CertStatus CertStatusFromOSStatus(OSStatus status) {
67 switch (status) {
68 case noErr:
69 return 0;
71 case CSSMERR_TP_INVALID_ANCHOR_CERT:
72 case CSSMERR_TP_NOT_TRUSTED:
73 case CSSMERR_TP_INVALID_CERT_AUTHORITY:
74 return CERT_STATUS_AUTHORITY_INVALID;
76 case CSSMERR_TP_CERT_EXPIRED:
77 case CSSMERR_TP_CERT_NOT_VALID_YET:
78 // "Expired" and "not yet valid" collapse into a single status.
79 return CERT_STATUS_DATE_INVALID;
81 case CSSMERR_TP_CERT_REVOKED:
82 case CSSMERR_TP_CERT_SUSPENDED:
83 return CERT_STATUS_REVOKED;
85 case CSSMERR_APPLETP_HOSTNAME_MISMATCH:
86 return CERT_STATUS_COMMON_NAME_INVALID;
88 case CSSMERR_APPLETP_CRL_NOT_FOUND:
89 case CSSMERR_APPLETP_OCSP_UNAVAILABLE:
90 case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
91 return CERT_STATUS_NO_REVOCATION_MECHANISM;
93 case CSSMERR_APPLETP_CRL_EXPIRED:
94 case CSSMERR_APPLETP_CRL_NOT_VALID_YET:
95 case CSSMERR_APPLETP_CRL_SERVER_DOWN:
96 case CSSMERR_APPLETP_CRL_NOT_TRUSTED:
97 case CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT:
98 case CSSMERR_APPLETP_CRL_POLICY_FAIL:
99 case CSSMERR_APPLETP_OCSP_BAD_RESPONSE:
100 case CSSMERR_APPLETP_OCSP_BAD_REQUEST:
101 case CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED:
102 case CSSMERR_APPLETP_NETWORK_FAILURE:
103 case CSSMERR_APPLETP_OCSP_NOT_TRUSTED:
104 case CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT:
105 case CSSMERR_APPLETP_OCSP_SIG_ERROR:
106 case CSSMERR_APPLETP_OCSP_NO_SIGNER:
107 case CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ:
108 case CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR:
109 case CSSMERR_APPLETP_OCSP_RESP_TRY_LATER:
110 case CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED:
111 case CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED:
112 case CSSMERR_APPLETP_OCSP_NONCE_MISMATCH:
113 // We asked for a revocation check, but didn't get it.
114 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
116 case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE:
117 // TODO(wtc): Should we add CERT_STATUS_WRONG_USAGE?
118 return CERT_STATUS_INVALID;
120 case CSSMERR_APPLETP_CRL_BAD_URI:
121 case CSSMERR_APPLETP_IDP_FAIL:
122 return CERT_STATUS_INVALID;
124 case CSSMERR_CSP_UNSUPPORTED_KEY_SIZE:
125 // Mapping UNSUPPORTED_KEY_SIZE to CERT_STATUS_WEAK_KEY is not strictly
126 // accurate, as the error may have been returned due to a key size
127 // that exceeded the maximum supported. However, within
128 // CertVerifyProcMac::VerifyInternal(), this code should only be
129 // encountered as a certificate status code, and only when the key size
130 // is smaller than the minimum required (1024 bits).
131 return CERT_STATUS_WEAK_KEY;
133 default: {
134 // Failure was due to something Chromium doesn't define a
135 // specific status for (such as basic constraints violation, or
136 // unknown critical extension)
137 OSSTATUS_LOG(WARNING, status)
138 << "Unknown error mapped to CERT_STATUS_INVALID";
139 return CERT_STATUS_INVALID;
144 // Creates a series of SecPolicyRefs to be added to a SecTrustRef used to
145 // validate a certificate for an SSL server. |hostname| contains the name of
146 // the SSL server that the certificate should be verified against. |flags| is
147 // a bitwise-OR of VerifyFlags that can further alter how trust is validated,
148 // such as how revocation is checked. If successful, returns noErr, and
149 // stores the resultant array of SecPolicyRefs in |policies|.
150 OSStatus CreateTrustPolicies(const std::string& hostname,
151 int flags,
152 ScopedCFTypeRef<CFArrayRef>* policies) {
153 ScopedCFTypeRef<CFMutableArrayRef> local_policies(
154 CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
155 if (!local_policies)
156 return memFullErr;
158 SecPolicyRef ssl_policy;
159 OSStatus status = x509_util::CreateSSLServerPolicy(hostname, &ssl_policy);
160 if (status)
161 return status;
162 CFArrayAppendValue(local_policies, ssl_policy);
163 CFRelease(ssl_policy);
165 // Explicitly add revocation policies, in order to override system
166 // revocation checking policies and instead respect the application-level
167 // revocation preference.
168 status = x509_util::CreateRevocationPolicies(
169 (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED),
170 (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY),
171 local_policies);
172 if (status)
173 return status;
175 policies->reset(local_policies.release());
176 return noErr;
179 // Saves some information about the certificate chain |cert_chain| in
180 // |*verify_result|. The caller MUST initialize |*verify_result| before
181 // calling this function.
182 void GetCertChainInfo(CFArrayRef cert_chain,
183 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info,
184 CertVerifyResult* verify_result) {
185 SecCertificateRef verified_cert = NULL;
186 std::vector<SecCertificateRef> verified_chain;
187 for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
188 SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
189 const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
190 if (i == 0) {
191 verified_cert = chain_cert;
192 } else {
193 verified_chain.push_back(chain_cert);
196 if ((chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_IN_ANCHORS) ||
197 (chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_ROOT)) {
198 // The current certificate is either in the user's trusted store or is
199 // a root (self-signed) certificate. Ignore the signature algorithm for
200 // these certificates, as it is meaningless for security. We allow
201 // self-signed certificates (i == 0 & IS_ROOT), since we accept that
202 // any security assertions by such a cert are inherently meaningless.
203 continue;
206 x509_util::CSSMCachedCertificate cached_cert;
207 OSStatus status = cached_cert.Init(chain_cert);
208 if (status)
209 continue;
210 x509_util::CSSMFieldValue signature_field;
211 status = cached_cert.GetField(&CSSMOID_X509V1SignatureAlgorithm,
212 &signature_field);
213 if (status || !signature_field.field())
214 continue;
215 // Match the behaviour of OS X system tools and defensively check that
216 // sizes are appropriate. This would indicate a critical failure of the
217 // OS X certificate library, but based on history, it is best to play it
218 // safe.
219 const CSSM_X509_ALGORITHM_IDENTIFIER* sig_algorithm =
220 signature_field.GetAs<CSSM_X509_ALGORITHM_IDENTIFIER>();
221 if (!sig_algorithm)
222 continue;
224 const CSSM_OID* alg_oid = &sig_algorithm->algorithm;
225 if (CSSMOIDEqual(alg_oid, &CSSMOID_MD2WithRSA)) {
226 verify_result->has_md2 = true;
227 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD4WithRSA)) {
228 verify_result->has_md4 = true;
229 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD5WithRSA)) {
230 verify_result->has_md5 = true;
233 if (!verified_cert)
234 return;
236 verify_result->verified_cert =
237 X509Certificate::CreateFromHandle(verified_cert, verified_chain);
240 void AppendPublicKeyHashes(CFArrayRef chain,
241 HashValueVector* hashes) {
242 const CFIndex n = CFArrayGetCount(chain);
243 for (CFIndex i = 0; i < n; i++) {
244 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
245 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
247 CSSM_DATA cert_data;
248 OSStatus err = SecCertificateGetData(cert, &cert_data);
249 DCHECK_EQ(err, noErr);
250 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
251 cert_data.Length);
252 base::StringPiece spki_bytes;
253 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes))
254 continue;
256 HashValue sha1(HASH_VALUE_SHA1);
257 CC_SHA1(spki_bytes.data(), spki_bytes.size(), sha1.data());
258 hashes->push_back(sha1);
260 HashValue sha256(HASH_VALUE_SHA256);
261 CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data());
262 hashes->push_back(sha256);
266 bool CheckRevocationWithCRLSet(CFArrayRef chain, CRLSet* crl_set) {
267 if (CFArrayGetCount(chain) == 0)
268 return true;
270 // We iterate from the root certificate down to the leaf, keeping track of
271 // the issuer's SPKI at each step.
272 std::string issuer_spki_hash;
273 for (CFIndex i = CFArrayGetCount(chain) - 1; i >= 0; i--) {
274 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
275 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
277 CSSM_DATA cert_data;
278 OSStatus err = SecCertificateGetData(cert, &cert_data);
279 if (err != noErr) {
280 NOTREACHED();
281 continue;
283 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data),
284 cert_data.Length);
285 base::StringPiece spki;
286 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki)) {
287 NOTREACHED();
288 continue;
291 const std::string spki_hash = crypto::SHA256HashString(spki);
292 x509_util::CSSMCachedCertificate cached_cert;
293 if (cached_cert.Init(cert) != CSSM_OK) {
294 NOTREACHED();
295 continue;
297 x509_util::CSSMFieldValue serial_number;
298 err = cached_cert.GetField(&CSSMOID_X509V1SerialNumber, &serial_number);
299 if (err || !serial_number.field()) {
300 NOTREACHED();
301 continue;
304 base::StringPiece serial(
305 reinterpret_cast<const char*>(serial_number.field()->Data),
306 serial_number.field()->Length);
308 CRLSet::Result result = crl_set->CheckSPKI(spki_hash);
310 if (result != CRLSet::REVOKED && !issuer_spki_hash.empty())
311 result = crl_set->CheckSerial(serial, issuer_spki_hash);
313 issuer_spki_hash = spki_hash;
315 switch (result) {
316 case CRLSet::REVOKED:
317 return false;
318 case CRLSet::UNKNOWN:
319 case CRLSet::GOOD:
320 continue;
321 default:
322 NOTREACHED();
323 return false;
327 return true;
330 // IsIssuedByKnownRoot returns true if the given chain is rooted at a root CA
331 // that we recognise as a standard root.
332 // static
333 bool IsIssuedByKnownRoot(CFArrayRef chain) {
334 int n = CFArrayGetCount(chain);
335 if (n < 1)
336 return false;
337 SecCertificateRef root_ref = reinterpret_cast<SecCertificateRef>(
338 const_cast<void*>(CFArrayGetValueAtIndex(chain, n - 1)));
339 SHA1HashValue hash = X509Certificate::CalculateFingerprint(root_ref);
340 return IsSHA1HashInSortedArray(
341 hash, &kKnownRootCertSHA1Hashes[0][0], sizeof(kKnownRootCertSHA1Hashes));
344 // Builds and evaluates a SecTrustRef for the certificate chain contained
345 // in |cert_array|, using the verification policies in |trust_policies|. On
346 // success, returns OK, and updates |trust_ref|, |trust_result|,
347 // |verified_chain|, and |chain_info| with the verification results. On
348 // failure, no output parameters are modified.
350 // Note: An OK return does not mean that |cert_array| is trusted, merely that
351 // verification was performed successfully.
353 // This function should only be called while the Mac Security Services lock is
354 // held.
355 int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array,
356 CFArrayRef trust_policies,
357 int flags,
358 ScopedCFTypeRef<SecTrustRef>* trust_ref,
359 SecTrustResultType* trust_result,
360 ScopedCFTypeRef<CFArrayRef>* verified_chain,
361 CSSM_TP_APPLE_EVIDENCE_INFO** chain_info) {
362 SecTrustRef tmp_trust = NULL;
363 OSStatus status = SecTrustCreateWithCertificates(cert_array, trust_policies,
364 &tmp_trust);
365 if (status)
366 return NetErrorFromOSStatus(status);
367 ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust);
369 if (TestRootCerts::HasInstance()) {
370 status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust);
371 if (status)
372 return NetErrorFromOSStatus(status);
375 CSSM_APPLE_TP_ACTION_DATA tp_action_data;
376 memset(&tp_action_data, 0, sizeof(tp_action_data));
377 tp_action_data.Version = CSSM_APPLE_TP_ACTION_VERSION;
378 // Allow CSSM to download any missing intermediate certificates if an
379 // authorityInfoAccess extension or issuerAltName extension is present.
380 tp_action_data.ActionFlags = CSSM_TP_ACTION_FETCH_CERT_FROM_NET |
381 CSSM_TP_ACTION_TRUST_SETTINGS;
383 // Note: For EV certificates, the Apple TP will handle setting these flags
384 // as part of EV evaluation.
385 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) {
386 // Require a positive result from an OCSP responder or a CRL (or both)
387 // for every certificate in the chain. The Apple TP automatically
388 // excludes the self-signed root from this requirement. If a certificate
389 // is missing both a crlDistributionPoints extension and an
390 // authorityInfoAccess extension with an OCSP responder URL, then we
391 // will get a kSecTrustResultRecoverableTrustFailure back from
392 // SecTrustEvaluate(), with a
393 // CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK error code. In that case,
394 // we'll set our own result to include
395 // CERT_STATUS_NO_REVOCATION_MECHANISM. If one or both extensions are
396 // present, and a check fails (server unavailable, OCSP retry later,
397 // signature mismatch), then we'll set our own result to include
398 // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION.
399 tp_action_data.ActionFlags |= CSSM_TP_ACTION_REQUIRE_REV_PER_CERT;
401 // Note, even if revocation checking is disabled, SecTrustEvaluate() will
402 // modify the OCSP options so as to attempt OCSP checking if it believes a
403 // certificate may chain to an EV root. However, because network fetches
404 // are disabled in CreateTrustPolicies() when revocation checking is
405 // disabled, these will only go against the local cache.
408 CFDataRef action_data_ref =
409 CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
410 reinterpret_cast<UInt8*>(&tp_action_data),
411 sizeof(tp_action_data), kCFAllocatorNull);
412 if (!action_data_ref)
413 return ERR_OUT_OF_MEMORY;
414 ScopedCFTypeRef<CFDataRef> scoped_action_data_ref(action_data_ref);
415 status = SecTrustSetParameters(tmp_trust, CSSM_TP_ACTION_DEFAULT,
416 action_data_ref);
417 if (status)
418 return NetErrorFromOSStatus(status);
420 // Verify the certificate. A non-zero result from SecTrustGetResult()
421 // indicates that some fatal error occurred and the chain couldn't be
422 // processed, not that the chain contains no errors. We need to examine the
423 // output of SecTrustGetResult() to determine that.
424 SecTrustResultType tmp_trust_result;
425 status = SecTrustEvaluate(tmp_trust, &tmp_trust_result);
426 if (status)
427 return NetErrorFromOSStatus(status);
428 CFArrayRef tmp_verified_chain = NULL;
429 CSSM_TP_APPLE_EVIDENCE_INFO* tmp_chain_info;
430 status = SecTrustGetResult(tmp_trust, &tmp_trust_result, &tmp_verified_chain,
431 &tmp_chain_info);
432 if (status)
433 return NetErrorFromOSStatus(status);
435 trust_ref->swap(scoped_tmp_trust);
436 *trust_result = tmp_trust_result;
437 verified_chain->reset(tmp_verified_chain);
438 *chain_info = tmp_chain_info;
440 return OK;
443 // OS X ships with both "GTE CyberTrust Global Root" and "Baltimore CyberTrust
444 // Root" as part of its trusted root store. However, a cross-certified version
445 // of the "Baltimore CyberTrust Root" exists that chains to "GTE CyberTrust
446 // Global Root". When OS X/Security.framework attempts to evaluate such a
447 // certificate chain, it disregards the "Baltimore CyberTrust Root" that exists
448 // within Keychain and instead attempts to terminate the chain in the "GTE
449 // CyberTrust Global Root". However, the GTE root is scheduled to be removed in
450 // a future OS X update (for sunsetting purposes), and once removed, such
451 // chains will fail validation, even though a trust anchor still exists.
453 // Rather than over-generalizing a solution that may mask a number of TLS
454 // misconfigurations, attempt to specifically match the affected
455 // cross-certified certificate and remove it from certificate chain processing.
456 bool IsBadBaltimoreGTECertificate(SecCertificateRef cert) {
457 // Matches the GTE-signed Baltimore CyberTrust Root
458 // https://cacert.omniroot.com/Baltimore-to-GTE-04-12.pem
459 static const SHA1HashValue kBadBaltimoreHashNew =
460 { { 0x4D, 0x34, 0xEA, 0x92, 0x76, 0x4B, 0x3A, 0x31, 0x49, 0x11,
461 0x99, 0x52, 0xF4, 0x19, 0x30, 0xCA, 0x11, 0x34, 0x83, 0x61 } };
462 // Matches the legacy GTE-signed Baltimore CyberTrust Root
463 // https://cacert.omniroot.com/gte-2-2025.pem
464 static const SHA1HashValue kBadBaltimoreHashOld =
465 { { 0x54, 0xD8, 0xCB, 0x49, 0x1F, 0xA1, 0x6D, 0xF8, 0x87, 0xDC,
466 0x94, 0xA9, 0x34, 0xCC, 0x83, 0x6B, 0xDA, 0xA8, 0xA3, 0x69 } };
468 SHA1HashValue fingerprint = X509Certificate::CalculateFingerprint(cert);
470 return fingerprint.Equals(kBadBaltimoreHashNew) ||
471 fingerprint.Equals(kBadBaltimoreHashOld);
474 // Attempts to re-verify |cert_array| after adjusting the inputs to work around
475 // known issues in OS X. To be used if BuildAndEvaluateSecTrustRef fails to
476 // return a positive result for verification.
478 // This function should only be called while the Mac Security Services lock is
479 // held.
480 void RetrySecTrustEvaluateWithAdjustedChain(
481 CFArrayRef cert_array,
482 CFArrayRef trust_policies,
483 int flags,
484 ScopedCFTypeRef<SecTrustRef>* trust_ref,
485 SecTrustResultType* trust_result,
486 ScopedCFTypeRef<CFArrayRef>* verified_chain,
487 CSSM_TP_APPLE_EVIDENCE_INFO** chain_info) {
488 CFIndex count = CFArrayGetCount(*verified_chain);
489 CFIndex slice_point = 0;
491 for (CFIndex i = 1; i < count; ++i) {
492 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(
493 const_cast<void*>(CFArrayGetValueAtIndex(*verified_chain, i)));
494 if (cert == NULL)
495 return; // Strange times; can't fix things up.
497 if (IsBadBaltimoreGTECertificate(cert)) {
498 slice_point = i;
499 break;
502 if (slice_point == 0)
503 return; // Nothing to do.
505 ScopedCFTypeRef<CFMutableArrayRef> adjusted_cert_array(
506 CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks));
507 // Note: This excludes the certificate at |slice_point|.
508 CFArrayAppendArray(adjusted_cert_array, cert_array,
509 CFRangeMake(0, slice_point));
511 // Ignore the result; failure will preserve the old verification results.
512 BuildAndEvaluateSecTrustRef(
513 adjusted_cert_array, trust_policies, flags, trust_ref, trust_result,
514 verified_chain, chain_info);
517 } // namespace
519 CertVerifyProcMac::CertVerifyProcMac() {}
521 CertVerifyProcMac::~CertVerifyProcMac() {}
523 bool CertVerifyProcMac::SupportsAdditionalTrustAnchors() const {
524 return false;
527 int CertVerifyProcMac::VerifyInternal(
528 X509Certificate* cert,
529 const std::string& hostname,
530 int flags,
531 CRLSet* crl_set,
532 const CertificateList& additional_trust_anchors,
533 CertVerifyResult* verify_result) {
534 ScopedCFTypeRef<CFArrayRef> trust_policies;
535 OSStatus status = CreateTrustPolicies(hostname, flags, &trust_policies);
536 if (status)
537 return NetErrorFromOSStatus(status);
539 // Create and configure a SecTrustRef, which takes our certificate(s)
540 // and our SSL SecPolicyRef. SecTrustCreateWithCertificates() takes an
541 // array of certificates, the first of which is the certificate we're
542 // verifying, and the subsequent (optional) certificates are used for
543 // chain building.
544 ScopedCFTypeRef<CFArrayRef> cert_array(cert->CreateOSCertChainForCert());
546 // Serialize all calls that may use the Keychain, to work around various
547 // issues in OS X 10.6+ with multi-threaded access to Security.framework.
548 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
550 ScopedCFTypeRef<SecTrustRef> trust_ref;
551 SecTrustResultType trust_result = kSecTrustResultDeny;
552 ScopedCFTypeRef<CFArrayRef> completed_chain;
553 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info = NULL;
555 int rv = BuildAndEvaluateSecTrustRef(
556 cert_array, trust_policies, flags, &trust_ref, &trust_result,
557 &completed_chain, &chain_info);
558 if (rv != OK)
559 return rv;
560 if (trust_result != kSecTrustResultUnspecified &&
561 trust_result != kSecTrustResultProceed) {
562 RetrySecTrustEvaluateWithAdjustedChain(
563 cert_array, trust_policies, flags, &trust_ref, &trust_result,
564 &completed_chain, &chain_info);
567 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED)
568 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
570 if (crl_set && !CheckRevocationWithCRLSet(completed_chain, crl_set))
571 verify_result->cert_status |= CERT_STATUS_REVOKED;
573 GetCertChainInfo(completed_chain, chain_info, verify_result);
575 // As of Security Update 2012-002/OS X 10.7.4, when an RSA key < 1024 bits
576 // is encountered, CSSM returns CSSMERR_TP_VERIFY_ACTION_FAILED and adds
577 // CSSMERR_CSP_UNSUPPORTED_KEY_SIZE as a certificate status. Avoid mapping
578 // the CSSMERR_TP_VERIFY_ACTION_FAILED to CERT_STATUS_INVALID if the only
579 // error was due to an unsupported key size.
580 bool policy_failed = false;
581 bool weak_key = false;
583 // Evaluate the results
584 OSStatus cssm_result;
585 switch (trust_result) {
586 case kSecTrustResultUnspecified:
587 case kSecTrustResultProceed:
588 // Certificate chain is valid and trusted ("unspecified" indicates that
589 // the user has not explicitly set a trust setting)
590 break;
592 // According to SecTrust.h, kSecTrustResultConfirm isn't returned on 10.5+,
593 // and it is marked deprecated in the 10.9 SDK.
594 case kSecTrustResultDeny:
595 // Certificate chain is explicitly untrusted.
596 verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
597 break;
599 case kSecTrustResultRecoverableTrustFailure:
600 // Certificate chain has a failure that can be overridden by the user.
601 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
602 if (status)
603 return NetErrorFromOSStatus(status);
604 if (cssm_result == CSSMERR_TP_VERIFY_ACTION_FAILED) {
605 policy_failed = true;
606 } else {
607 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
609 // Walk the chain of error codes in the CSSM_TP_APPLE_EVIDENCE_INFO
610 // structure which can catch multiple errors from each certificate.
611 for (CFIndex index = 0, chain_count = CFArrayGetCount(completed_chain);
612 index < chain_count; ++index) {
613 if (chain_info[index].StatusBits & CSSM_CERT_STATUS_EXPIRED ||
614 chain_info[index].StatusBits & CSSM_CERT_STATUS_NOT_VALID_YET)
615 verify_result->cert_status |= CERT_STATUS_DATE_INVALID;
616 if (!IsCertStatusError(verify_result->cert_status) &&
617 chain_info[index].NumStatusCodes == 0) {
618 LOG(WARNING) << "chain_info[" << index << "].NumStatusCodes is 0"
619 ", chain_info[" << index << "].StatusBits is "
620 << chain_info[index].StatusBits;
622 for (uint32 status_code_index = 0;
623 status_code_index < chain_info[index].NumStatusCodes;
624 ++status_code_index) {
625 CertStatus mapped_status = CertStatusFromOSStatus(
626 chain_info[index].StatusCodes[status_code_index]);
627 if (mapped_status == CERT_STATUS_WEAK_KEY)
628 weak_key = true;
629 verify_result->cert_status |= mapped_status;
632 if (policy_failed && !weak_key) {
633 // If CSSMERR_TP_VERIFY_ACTION_FAILED wasn't returned due to a weak
634 // key, map it back to an appropriate error code.
635 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
637 if (!IsCertStatusError(verify_result->cert_status)) {
638 LOG(ERROR) << "cssm_result=" << cssm_result;
639 verify_result->cert_status |= CERT_STATUS_INVALID;
640 NOTREACHED();
642 break;
644 default:
645 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result);
646 if (status)
647 return NetErrorFromOSStatus(status);
648 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result);
649 if (!IsCertStatusError(verify_result->cert_status)) {
650 LOG(WARNING) << "trust_result=" << trust_result;
651 verify_result->cert_status |= CERT_STATUS_INVALID;
653 break;
656 // Perform hostname verification independent of SecTrustEvaluate. In order to
657 // do so, mask off any reported name errors first.
658 verify_result->cert_status &= ~CERT_STATUS_COMMON_NAME_INVALID;
659 if (!cert->VerifyNameMatch(hostname,
660 &verify_result->common_name_fallback_used)) {
661 verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
664 // TODO(wtc): Suppress CERT_STATUS_NO_REVOCATION_MECHANISM for now to be
665 // compatible with Windows, which in turn implements this behavior to be
666 // compatible with WinHTTP, which doesn't report this error (bug 3004).
667 verify_result->cert_status &= ~CERT_STATUS_NO_REVOCATION_MECHANISM;
669 AppendPublicKeyHashes(completed_chain, &verify_result->public_key_hashes);
670 verify_result->is_issued_by_known_root = IsIssuedByKnownRoot(completed_chain);
672 if (IsCertStatusError(verify_result->cert_status))
673 return MapCertStatusToNetError(verify_result->cert_status);
675 if (flags & CertVerifier::VERIFY_EV_CERT) {
676 // Determine the certificate's EV status using SecTrustCopyExtendedResult(),
677 // which is an internal/private API function added in OS X 10.5.7.
678 // Note: "ExtendedResult" means extended validation results.
679 CFBundleRef bundle =
680 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"));
681 if (bundle) {
682 SecTrustCopyExtendedResultFuncPtr copy_extended_result =
683 reinterpret_cast<SecTrustCopyExtendedResultFuncPtr>(
684 CFBundleGetFunctionPointerForName(bundle,
685 CFSTR("SecTrustCopyExtendedResult")));
686 if (copy_extended_result) {
687 CFDictionaryRef ev_dict_temp = NULL;
688 status = copy_extended_result(trust_ref, &ev_dict_temp);
689 ScopedCFTypeRef<CFDictionaryRef> ev_dict(ev_dict_temp);
690 ev_dict_temp = NULL;
691 if (status == noErr && ev_dict) {
692 // In 10.7.3, SecTrustCopyExtendedResult returns noErr and populates
693 // ev_dict even for non-EV certificates, but only EV certificates
694 // will cause ev_dict to contain kSecEVOrganizationName. In previous
695 // releases, SecTrustCopyExtendedResult would only return noErr and
696 // populate ev_dict for EV certificates, but would always include
697 // kSecEVOrganizationName in that case, so checking for this key is
698 // appropriate for all known versions of SecTrustCopyExtendedResult.
699 // The actual organization name is unneeded here and can be accessed
700 // through other means. All that matters here is the OS' conception
701 // of whether or not the certificate is EV.
702 if (CFDictionaryContainsKey(ev_dict,
703 kSecEVOrganizationName)) {
704 verify_result->cert_status |= CERT_STATUS_IS_EV;
705 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY)
706 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED;
713 return OK;
716 } // namespace net