OLD | NEW |
| (Empty) |
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 | |
5 #include "net/cert/cert_verify_proc_mac.h" | |
6 | |
7 #include <CommonCrypto/CommonDigest.h> | |
8 #include <CoreServices/CoreServices.h> | |
9 #include <Security/Security.h> | |
10 | |
11 #include <string> | |
12 #include <vector> | |
13 | |
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" | |
32 | |
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 | |
38 | |
39 using base::ScopedCFTypeRef; | |
40 | |
41 namespace net { | |
42 | |
43 namespace { | |
44 | |
45 typedef OSStatus (*SecTrustCopyExtendedResultFuncPtr)(SecTrustRef, | |
46 CFDictionaryRef*); | |
47 | |
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; | |
61 } | |
62 } | |
63 } | |
64 | |
65 CertStatus CertStatusFromOSStatus(OSStatus status) { | |
66 switch (status) { | |
67 case noErr: | |
68 return 0; | |
69 | |
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; | |
74 | |
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; | |
79 | |
80 case CSSMERR_TP_CERT_REVOKED: | |
81 case CSSMERR_TP_CERT_SUSPENDED: | |
82 return CERT_STATUS_REVOKED; | |
83 | |
84 case CSSMERR_APPLETP_HOSTNAME_MISMATCH: | |
85 return CERT_STATUS_COMMON_NAME_INVALID; | |
86 | |
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; | |
91 | |
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; | |
114 | |
115 case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE: | |
116 // TODO(wtc): Should we add CERT_STATUS_WRONG_USAGE? | |
117 return CERT_STATUS_INVALID; | |
118 | |
119 case CSSMERR_APPLETP_CRL_BAD_URI: | |
120 case CSSMERR_APPLETP_IDP_FAIL: | |
121 return CERT_STATUS_INVALID; | |
122 | |
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; | |
131 | |
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; | |
139 } | |
140 } | |
141 } | |
142 | |
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; | |
156 | |
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); | |
163 | |
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; | |
173 | |
174 policies->reset(local_policies.release()); | |
175 return noErr; | |
176 } | |
177 | |
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|. | |
182 void GetCertChainInfo(CFArrayRef cert_chain, | |
183 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info, | |
184 CertVerifyResult* verify_result, | |
185 bool* leaf_is_weak) { | |
186 *leaf_is_weak = false; | |
187 verify_result->verified_cert = nullptr; | |
188 verify_result->has_md2 = false; | |
189 verify_result->has_md4 = false; | |
190 verify_result->has_md5 = false; | |
191 verify_result->has_sha1 = false; | |
192 | |
193 SecCertificateRef verified_cert = NULL; | |
194 std::vector<SecCertificateRef> verified_chain; | |
195 for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) { | |
196 SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>( | |
197 const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i))); | |
198 if (i == 0) { | |
199 verified_cert = chain_cert; | |
200 } else { | |
201 verified_chain.push_back(chain_cert); | |
202 } | |
203 | |
204 if ((chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_IN_ANCHORS) || | |
205 (chain_info[i].StatusBits & CSSM_CERT_STATUS_IS_ROOT)) { | |
206 // The current certificate is either in the user's trusted store or is | |
207 // a root (self-signed) certificate. Ignore the signature algorithm for | |
208 // these certificates, as it is meaningless for security. We allow | |
209 // self-signed certificates (i == 0 & IS_ROOT), since we accept that | |
210 // any security assertions by such a cert are inherently meaningless. | |
211 continue; | |
212 } | |
213 | |
214 x509_util::CSSMCachedCertificate cached_cert; | |
215 OSStatus status = cached_cert.Init(chain_cert); | |
216 if (status) | |
217 continue; | |
218 x509_util::CSSMFieldValue signature_field; | |
219 status = cached_cert.GetField(&CSSMOID_X509V1SignatureAlgorithm, | |
220 &signature_field); | |
221 if (status || !signature_field.field()) | |
222 continue; | |
223 // Match the behaviour of OS X system tools and defensively check that | |
224 // sizes are appropriate. This would indicate a critical failure of the | |
225 // OS X certificate library, but based on history, it is best to play it | |
226 // safe. | |
227 const CSSM_X509_ALGORITHM_IDENTIFIER* sig_algorithm = | |
228 signature_field.GetAs<CSSM_X509_ALGORITHM_IDENTIFIER>(); | |
229 if (!sig_algorithm) | |
230 continue; | |
231 | |
232 const CSSM_OID* alg_oid = &sig_algorithm->algorithm; | |
233 if (CSSMOIDEqual(alg_oid, &CSSMOID_MD2WithRSA)) { | |
234 verify_result->has_md2 = true; | |
235 if (i == 0) | |
236 *leaf_is_weak = true; | |
237 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD4WithRSA)) { | |
238 verify_result->has_md4 = true; | |
239 if (i == 0) | |
240 *leaf_is_weak = true; | |
241 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_MD5WithRSA)) { | |
242 verify_result->has_md5 = true; | |
243 if (i == 0) | |
244 *leaf_is_weak = true; | |
245 } else if (CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithRSA) || | |
246 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithRSA_OIW) || | |
247 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA) || | |
248 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA_CMS) || | |
249 CSSMOIDEqual(alg_oid, &CSSMOID_SHA1WithDSA_JDK) || | |
250 CSSMOIDEqual(alg_oid, &CSSMOID_ECDSA_WithSHA1)) { | |
251 verify_result->has_sha1 = true; | |
252 if (i == 0) | |
253 *leaf_is_weak = true; | |
254 } | |
255 } | |
256 if (!verified_cert) | |
257 return; | |
258 | |
259 verify_result->verified_cert = | |
260 X509Certificate::CreateFromHandle(verified_cert, verified_chain); | |
261 } | |
262 | |
263 void AppendPublicKeyHashes(CFArrayRef chain, | |
264 HashValueVector* hashes) { | |
265 const CFIndex n = CFArrayGetCount(chain); | |
266 for (CFIndex i = 0; i < n; i++) { | |
267 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>( | |
268 const_cast<void*>(CFArrayGetValueAtIndex(chain, i))); | |
269 | |
270 CSSM_DATA cert_data; | |
271 OSStatus err = SecCertificateGetData(cert, &cert_data); | |
272 DCHECK_EQ(err, noErr); | |
273 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data), | |
274 cert_data.Length); | |
275 base::StringPiece spki_bytes; | |
276 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes)) | |
277 continue; | |
278 | |
279 HashValue sha1(HASH_VALUE_SHA1); | |
280 CC_SHA1(spki_bytes.data(), spki_bytes.size(), sha1.data()); | |
281 hashes->push_back(sha1); | |
282 | |
283 HashValue sha256(HASH_VALUE_SHA256); | |
284 CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data()); | |
285 hashes->push_back(sha256); | |
286 } | |
287 } | |
288 | |
289 bool CheckRevocationWithCRLSet(CFArrayRef chain, CRLSet* crl_set) { | |
290 if (CFArrayGetCount(chain) == 0) | |
291 return true; | |
292 | |
293 // We iterate from the root certificate down to the leaf, keeping track of | |
294 // the issuer's SPKI at each step. | |
295 std::string issuer_spki_hash; | |
296 for (CFIndex i = CFArrayGetCount(chain) - 1; i >= 0; i--) { | |
297 SecCertificateRef cert = reinterpret_cast<SecCertificateRef>( | |
298 const_cast<void*>(CFArrayGetValueAtIndex(chain, i))); | |
299 | |
300 CSSM_DATA cert_data; | |
301 OSStatus err = SecCertificateGetData(cert, &cert_data); | |
302 if (err != noErr) { | |
303 NOTREACHED(); | |
304 continue; | |
305 } | |
306 base::StringPiece der_bytes(reinterpret_cast<const char*>(cert_data.Data), | |
307 cert_data.Length); | |
308 base::StringPiece spki; | |
309 if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki)) { | |
310 NOTREACHED(); | |
311 continue; | |
312 } | |
313 | |
314 const std::string spki_hash = crypto::SHA256HashString(spki); | |
315 x509_util::CSSMCachedCertificate cached_cert; | |
316 if (cached_cert.Init(cert) != CSSM_OK) { | |
317 NOTREACHED(); | |
318 continue; | |
319 } | |
320 x509_util::CSSMFieldValue serial_number; | |
321 err = cached_cert.GetField(&CSSMOID_X509V1SerialNumber, &serial_number); | |
322 if (err || !serial_number.field()) { | |
323 NOTREACHED(); | |
324 continue; | |
325 } | |
326 | |
327 base::StringPiece serial( | |
328 reinterpret_cast<const char*>(serial_number.field()->Data), | |
329 serial_number.field()->Length); | |
330 | |
331 CRLSet::Result result = crl_set->CheckSPKI(spki_hash); | |
332 | |
333 if (result != CRLSet::REVOKED && !issuer_spki_hash.empty()) | |
334 result = crl_set->CheckSerial(serial, issuer_spki_hash); | |
335 | |
336 issuer_spki_hash = spki_hash; | |
337 | |
338 switch (result) { | |
339 case CRLSet::REVOKED: | |
340 return false; | |
341 case CRLSet::UNKNOWN: | |
342 case CRLSet::GOOD: | |
343 continue; | |
344 default: | |
345 NOTREACHED(); | |
346 return false; | |
347 } | |
348 } | |
349 | |
350 return true; | |
351 } | |
352 | |
353 // IsIssuedByKnownRoot returns true if the given chain is rooted at a root CA | |
354 // that we recognise as a standard root. | |
355 // static | |
356 bool IsIssuedByKnownRoot(CFArrayRef chain) { | |
357 int n = CFArrayGetCount(chain); | |
358 if (n < 1) | |
359 return false; | |
360 SecCertificateRef root_ref = reinterpret_cast<SecCertificateRef>( | |
361 const_cast<void*>(CFArrayGetValueAtIndex(chain, n - 1))); | |
362 SHA1HashValue hash = X509Certificate::CalculateFingerprint(root_ref); | |
363 return IsSHA1HashInSortedArray( | |
364 hash, &kKnownRootCertSHA1Hashes[0][0], sizeof(kKnownRootCertSHA1Hashes)); | |
365 } | |
366 | |
367 // Builds and evaluates a SecTrustRef for the certificate chain contained | |
368 // in |cert_array|, using the verification policies in |trust_policies|. On | |
369 // success, returns OK, and updates |trust_ref|, |trust_result|, | |
370 // |verified_chain|, and |chain_info| with the verification results. On | |
371 // failure, no output parameters are modified. | |
372 // | |
373 // Note: An OK return does not mean that |cert_array| is trusted, merely that | |
374 // verification was performed successfully. | |
375 // | |
376 // This function should only be called while the Mac Security Services lock is | |
377 // held. | |
378 int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array, | |
379 CFArrayRef trust_policies, | |
380 int flags, | |
381 ScopedCFTypeRef<SecTrustRef>* trust_ref, | |
382 SecTrustResultType* trust_result, | |
383 ScopedCFTypeRef<CFArrayRef>* verified_chain, | |
384 CSSM_TP_APPLE_EVIDENCE_INFO** chain_info) { | |
385 SecTrustRef tmp_trust = NULL; | |
386 OSStatus status = SecTrustCreateWithCertificates(cert_array, trust_policies, | |
387 &tmp_trust); | |
388 if (status) | |
389 return NetErrorFromOSStatus(status); | |
390 ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust); | |
391 | |
392 if (TestRootCerts::HasInstance()) { | |
393 status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust); | |
394 if (status) | |
395 return NetErrorFromOSStatus(status); | |
396 } | |
397 | |
398 CSSM_APPLE_TP_ACTION_DATA tp_action_data; | |
399 memset(&tp_action_data, 0, sizeof(tp_action_data)); | |
400 tp_action_data.Version = CSSM_APPLE_TP_ACTION_VERSION; | |
401 // Allow CSSM to download any missing intermediate certificates if an | |
402 // authorityInfoAccess extension or issuerAltName extension is present. | |
403 tp_action_data.ActionFlags = CSSM_TP_ACTION_FETCH_CERT_FROM_NET | | |
404 CSSM_TP_ACTION_TRUST_SETTINGS; | |
405 | |
406 // Note: For EV certificates, the Apple TP will handle setting these flags | |
407 // as part of EV evaluation. | |
408 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) { | |
409 // Require a positive result from an OCSP responder or a CRL (or both) | |
410 // for every certificate in the chain. The Apple TP automatically | |
411 // excludes the self-signed root from this requirement. If a certificate | |
412 // is missing both a crlDistributionPoints extension and an | |
413 // authorityInfoAccess extension with an OCSP responder URL, then we | |
414 // will get a kSecTrustResultRecoverableTrustFailure back from | |
415 // SecTrustEvaluate(), with a | |
416 // CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK error code. In that case, | |
417 // we'll set our own result to include | |
418 // CERT_STATUS_NO_REVOCATION_MECHANISM. If one or both extensions are | |
419 // present, and a check fails (server unavailable, OCSP retry later, | |
420 // signature mismatch), then we'll set our own result to include | |
421 // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION. | |
422 tp_action_data.ActionFlags |= CSSM_TP_ACTION_REQUIRE_REV_PER_CERT; | |
423 | |
424 // Note, even if revocation checking is disabled, SecTrustEvaluate() will | |
425 // modify the OCSP options so as to attempt OCSP checking if it believes a | |
426 // certificate may chain to an EV root. However, because network fetches | |
427 // are disabled in CreateTrustPolicies() when revocation checking is | |
428 // disabled, these will only go against the local cache. | |
429 } | |
430 | |
431 CFDataRef action_data_ref = | |
432 CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, | |
433 reinterpret_cast<UInt8*>(&tp_action_data), | |
434 sizeof(tp_action_data), kCFAllocatorNull); | |
435 if (!action_data_ref) | |
436 return ERR_OUT_OF_MEMORY; | |
437 ScopedCFTypeRef<CFDataRef> scoped_action_data_ref(action_data_ref); | |
438 status = SecTrustSetParameters(tmp_trust, CSSM_TP_ACTION_DEFAULT, | |
439 action_data_ref); | |
440 if (status) | |
441 return NetErrorFromOSStatus(status); | |
442 | |
443 // Verify the certificate. A non-zero result from SecTrustGetResult() | |
444 // indicates that some fatal error occurred and the chain couldn't be | |
445 // processed, not that the chain contains no errors. We need to examine the | |
446 // output of SecTrustGetResult() to determine that. | |
447 SecTrustResultType tmp_trust_result; | |
448 status = SecTrustEvaluate(tmp_trust, &tmp_trust_result); | |
449 if (status) | |
450 return NetErrorFromOSStatus(status); | |
451 CFArrayRef tmp_verified_chain = NULL; | |
452 CSSM_TP_APPLE_EVIDENCE_INFO* tmp_chain_info; | |
453 status = SecTrustGetResult(tmp_trust, &tmp_trust_result, &tmp_verified_chain, | |
454 &tmp_chain_info); | |
455 if (status) | |
456 return NetErrorFromOSStatus(status); | |
457 | |
458 trust_ref->swap(scoped_tmp_trust); | |
459 *trust_result = tmp_trust_result; | |
460 verified_chain->reset(tmp_verified_chain); | |
461 *chain_info = tmp_chain_info; | |
462 | |
463 return OK; | |
464 } | |
465 | |
466 } // namespace | |
467 | |
468 CertVerifyProcMac::CertVerifyProcMac() {} | |
469 | |
470 CertVerifyProcMac::~CertVerifyProcMac() {} | |
471 | |
472 bool CertVerifyProcMac::SupportsAdditionalTrustAnchors() const { | |
473 return false; | |
474 } | |
475 | |
476 int CertVerifyProcMac::VerifyInternal( | |
477 X509Certificate* cert, | |
478 const std::string& hostname, | |
479 int flags, | |
480 CRLSet* crl_set, | |
481 const CertificateList& additional_trust_anchors, | |
482 CertVerifyResult* verify_result) { | |
483 ScopedCFTypeRef<CFArrayRef> trust_policies; | |
484 OSStatus status = CreateTrustPolicies(hostname, flags, &trust_policies); | |
485 if (status) | |
486 return NetErrorFromOSStatus(status); | |
487 | |
488 // Create and configure a SecTrustRef, which takes our certificate(s) | |
489 // and our SSL SecPolicyRef. SecTrustCreateWithCertificates() takes an | |
490 // array of certificates, the first of which is the certificate we're | |
491 // verifying, and the subsequent (optional) certificates are used for | |
492 // chain building. | |
493 ScopedCFTypeRef<CFMutableArrayRef> cert_array( | |
494 cert->CreateOSCertChainForCert()); | |
495 | |
496 // Serialize all calls that may use the Keychain, to work around various | |
497 // issues in OS X 10.6+ with multi-threaded access to Security.framework. | |
498 base::AutoLock lock(crypto::GetMacSecurityServicesLock()); | |
499 | |
500 ScopedCFTypeRef<SecTrustRef> trust_ref; | |
501 SecTrustResultType trust_result = kSecTrustResultDeny; | |
502 ScopedCFTypeRef<CFArrayRef> completed_chain; | |
503 CSSM_TP_APPLE_EVIDENCE_INFO* chain_info = NULL; | |
504 bool candidate_untrusted = true; | |
505 bool candidate_weak = false; | |
506 | |
507 // OS X lacks proper path discovery; it will take the input certs and never | |
508 // backtrack the graph attempting to discover valid paths. | |
509 // This can create issues in some situations: | |
510 // - When OS X changes the trust store, there may be a chain | |
511 // A -> B -> C -> D | |
512 // where OS X trusts D (on some versions) and trusts C (on some versions). | |
513 // If a server supplies a chain A, B, C (cross-signed by D), then this chain | |
514 // will successfully validate on systems that trust D, but fail for systems | |
515 // that trust C. If the server supplies a chain of A -> B, then it forces | |
516 // all clients to fetch C (via AIA) if they trust D, and not all clients | |
517 // (notably, Firefox and Android) will do this, thus breaking them. | |
518 // An example of this is the Verizon Business Services root - GTE CyberTrust | |
519 // and Baltimore CyberTrust roots represent old and new roots that cause | |
520 // issues depending on which version of OS X being used. | |
521 // | |
522 // - A server may be (misconfigured) to send an expired intermediate | |
523 // certificate. On platforms with path discovery, the graph traversal | |
524 // will back up to immediately before this intermediate, and then | |
525 // attempt an AIA fetch or retrieval from local store. However, OS X | |
526 // does not do this, and thus prevents access. While this is ostensibly | |
527 // a server misconfiguration issue, the fact that it works on other | |
528 // platforms is a jarring inconsistency for users. | |
529 // | |
530 // - When OS X trusts both C and D (simultaneously), it's possible that the | |
531 // version of C signed by D is signed using a weak algorithm (e.g. SHA-1), | |
532 // while the version of C in the trust store's signature doesn't matter. | |
533 // Since a 'strong' chain exists, it would be desirable to prefer this | |
534 // chain. | |
535 // | |
536 // - A variant of the above example, it may be that the version of B sent by | |
537 // the server is signed using a weak algorithm, but the version of B | |
538 // present in the AIA of A is signed using a strong algorithm. Since a | |
539 // 'strong' chain exists, it would be desirable to prefer this chain. | |
540 // | |
541 // Because of this, the code below first attempts to validate the peer's | |
542 // identity using the supplied chain. If it is not trusted (e.g. the OS only | |
543 // trusts C, but the version of C signed by D was sent, and D is not trusted), | |
544 // or if it contains a weak chain, it will begin lopping off certificates | |
545 // from the end of the chain and attempting to verify. If a stronger, trusted | |
546 // chain is found, it is used, otherwise, the algorithm continues until only | |
547 // the peer's certificate remains. | |
548 // | |
549 // This does cause a performance hit for these users, but only in cases where | |
550 // OS X is building weaker chains than desired, or when it would otherwise | |
551 // fail the connection. | |
552 while (CFArrayGetCount(cert_array) > 0) { | |
553 ScopedCFTypeRef<SecTrustRef> temp_ref; | |
554 SecTrustResultType temp_trust_result = kSecTrustResultDeny; | |
555 ScopedCFTypeRef<CFArrayRef> temp_chain; | |
556 CSSM_TP_APPLE_EVIDENCE_INFO* temp_chain_info = NULL; | |
557 | |
558 int rv = BuildAndEvaluateSecTrustRef(cert_array, trust_policies, flags, | |
559 &temp_ref, &temp_trust_result, | |
560 &temp_chain, &temp_chain_info); | |
561 if (rv != OK) | |
562 return rv; | |
563 | |
564 CertVerifyResult temp_verify_result; | |
565 bool leaf_is_weak = false; | |
566 GetCertChainInfo(temp_chain, temp_chain_info, &temp_verify_result, | |
567 &leaf_is_weak); | |
568 | |
569 bool untrusted = (temp_trust_result != kSecTrustResultUnspecified && | |
570 temp_trust_result != kSecTrustResultProceed); | |
571 bool weak_chain = | |
572 !leaf_is_weak && | |
573 (temp_verify_result.has_md2 || temp_verify_result.has_md4 || | |
574 temp_verify_result.has_md5 || temp_verify_result.has_sha1); | |
575 // Set the result to the current chain if: | |
576 // - This is the first verification attempt. This ensures that if | |
577 // everything is awful (e.g. it may just be an untrusted cert), that | |
578 // what is reported is exactly what was sent by the server | |
579 // - If the current chain is trusted, and the old chain was not trusted, | |
580 // then prefer this chain. This ensures that if there is at least a | |
581 // valid path to a trust anchor, it's preferred over reporting an error. | |
582 // - If the current chain is trusted, and the old chain is trusted, but | |
583 // the old chain contained weak algorithms while the current chain only | |
584 // contains strong algorithms, then prefer the current chain over the | |
585 // old chain. | |
586 // | |
587 // Note: If the leaf certificate itself is weak, then the only | |
588 // consideration is whether or not there is a trusted chain. That's | |
589 // because no amount of path discovery will fix a weak leaf. | |
590 if (!trust_ref || (!untrusted && (candidate_untrusted || | |
591 (candidate_weak && !weak_chain)))) { | |
592 trust_ref = temp_ref; | |
593 trust_result = temp_trust_result; | |
594 completed_chain = temp_chain; | |
595 chain_info = temp_chain_info; | |
596 | |
597 candidate_untrusted = untrusted; | |
598 candidate_weak = weak_chain; | |
599 } | |
600 // Short-circuit when a current, trusted chain is found. | |
601 if (!untrusted && !weak_chain) | |
602 break; | |
603 CFArrayRemoveValueAtIndex(cert_array, CFArrayGetCount(cert_array) - 1); | |
604 } | |
605 | |
606 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED) | |
607 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED; | |
608 | |
609 if (crl_set && !CheckRevocationWithCRLSet(completed_chain, crl_set)) | |
610 verify_result->cert_status |= CERT_STATUS_REVOKED; | |
611 | |
612 bool leaf_is_weak_unused = false; | |
613 GetCertChainInfo(completed_chain, chain_info, verify_result, | |
614 &leaf_is_weak_unused); | |
615 | |
616 // As of Security Update 2012-002/OS X 10.7.4, when an RSA key < 1024 bits | |
617 // is encountered, CSSM returns CSSMERR_TP_VERIFY_ACTION_FAILED and adds | |
618 // CSSMERR_CSP_UNSUPPORTED_KEY_SIZE as a certificate status. Avoid mapping | |
619 // the CSSMERR_TP_VERIFY_ACTION_FAILED to CERT_STATUS_INVALID if the only | |
620 // error was due to an unsupported key size. | |
621 bool policy_failed = false; | |
622 bool weak_key_or_signature_algorithm = false; | |
623 | |
624 // Evaluate the results | |
625 OSStatus cssm_result; | |
626 switch (trust_result) { | |
627 case kSecTrustResultUnspecified: | |
628 case kSecTrustResultProceed: | |
629 // Certificate chain is valid and trusted ("unspecified" indicates that | |
630 // the user has not explicitly set a trust setting) | |
631 break; | |
632 | |
633 // According to SecTrust.h, kSecTrustResultConfirm isn't returned on 10.5+, | |
634 // and it is marked deprecated in the 10.9 SDK. | |
635 case kSecTrustResultDeny: | |
636 // Certificate chain is explicitly untrusted. | |
637 verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID; | |
638 break; | |
639 | |
640 case kSecTrustResultRecoverableTrustFailure: | |
641 // Certificate chain has a failure that can be overridden by the user. | |
642 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result); | |
643 if (status) | |
644 return NetErrorFromOSStatus(status); | |
645 if (cssm_result == CSSMERR_TP_VERIFY_ACTION_FAILED) { | |
646 policy_failed = true; | |
647 } else { | |
648 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result); | |
649 } | |
650 // Walk the chain of error codes in the CSSM_TP_APPLE_EVIDENCE_INFO | |
651 // structure which can catch multiple errors from each certificate. | |
652 for (CFIndex index = 0, chain_count = CFArrayGetCount(completed_chain); | |
653 index < chain_count; ++index) { | |
654 if (chain_info[index].StatusBits & CSSM_CERT_STATUS_EXPIRED || | |
655 chain_info[index].StatusBits & CSSM_CERT_STATUS_NOT_VALID_YET) | |
656 verify_result->cert_status |= CERT_STATUS_DATE_INVALID; | |
657 if (!IsCertStatusError(verify_result->cert_status) && | |
658 chain_info[index].NumStatusCodes == 0) { | |
659 LOG(WARNING) << "chain_info[" << index << "].NumStatusCodes is 0" | |
660 ", chain_info[" << index << "].StatusBits is " | |
661 << chain_info[index].StatusBits; | |
662 } | |
663 for (uint32 status_code_index = 0; | |
664 status_code_index < chain_info[index].NumStatusCodes; | |
665 ++status_code_index) { | |
666 // As of OS X 10.9, attempting to verify a certificate chain that | |
667 // contains a weak signature algorithm (MD2, MD5) in an intermediate | |
668 // or leaf cert will be treated as a (recoverable) policy validation | |
669 // failure, with the status code CSSMERR_TP_INVALID_CERTIFICATE | |
670 // added to the Status Codes. Don't treat this code as an invalid | |
671 // certificate; instead, map it to a weak key. Any truly invalid | |
672 // certificates will have the major error (cssm_result) set to | |
673 // CSSMERR_TP_INVALID_CERTIFICATE, rather than | |
674 // CSSMERR_TP_VERIFY_ACTION_FAILED. | |
675 CertStatus mapped_status = 0; | |
676 if (policy_failed && | |
677 chain_info[index].StatusCodes[status_code_index] == | |
678 CSSMERR_TP_INVALID_CERTIFICATE) { | |
679 mapped_status = CERT_STATUS_WEAK_SIGNATURE_ALGORITHM; | |
680 weak_key_or_signature_algorithm = true; | |
681 } else { | |
682 mapped_status = CertStatusFromOSStatus( | |
683 chain_info[index].StatusCodes[status_code_index]); | |
684 if (mapped_status == CERT_STATUS_WEAK_KEY) | |
685 weak_key_or_signature_algorithm = true; | |
686 } | |
687 verify_result->cert_status |= mapped_status; | |
688 } | |
689 } | |
690 if (policy_failed && !weak_key_or_signature_algorithm) { | |
691 // If CSSMERR_TP_VERIFY_ACTION_FAILED wasn't returned due to a weak | |
692 // key, map it back to an appropriate error code. | |
693 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result); | |
694 } | |
695 if (!IsCertStatusError(verify_result->cert_status)) { | |
696 LOG(ERROR) << "cssm_result=" << cssm_result; | |
697 verify_result->cert_status |= CERT_STATUS_INVALID; | |
698 NOTREACHED(); | |
699 } | |
700 break; | |
701 | |
702 default: | |
703 status = SecTrustGetCssmResultCode(trust_ref, &cssm_result); | |
704 if (status) | |
705 return NetErrorFromOSStatus(status); | |
706 verify_result->cert_status |= CertStatusFromOSStatus(cssm_result); | |
707 if (!IsCertStatusError(verify_result->cert_status)) { | |
708 LOG(WARNING) << "trust_result=" << trust_result; | |
709 verify_result->cert_status |= CERT_STATUS_INVALID; | |
710 } | |
711 break; | |
712 } | |
713 | |
714 // Perform hostname verification independent of SecTrustEvaluate. In order to | |
715 // do so, mask off any reported name errors first. | |
716 verify_result->cert_status &= ~CERT_STATUS_COMMON_NAME_INVALID; | |
717 if (!cert->VerifyNameMatch(hostname, | |
718 &verify_result->common_name_fallback_used)) { | |
719 verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID; | |
720 } | |
721 | |
722 // TODO(wtc): Suppress CERT_STATUS_NO_REVOCATION_MECHANISM for now to be | |
723 // compatible with Windows, which in turn implements this behavior to be | |
724 // compatible with WinHTTP, which doesn't report this error (bug 3004). | |
725 verify_result->cert_status &= ~CERT_STATUS_NO_REVOCATION_MECHANISM; | |
726 | |
727 AppendPublicKeyHashes(completed_chain, &verify_result->public_key_hashes); | |
728 verify_result->is_issued_by_known_root = IsIssuedByKnownRoot(completed_chain); | |
729 | |
730 if (IsCertStatusError(verify_result->cert_status)) | |
731 return MapCertStatusToNetError(verify_result->cert_status); | |
732 | |
733 if (flags & CertVerifier::VERIFY_EV_CERT) { | |
734 // Determine the certificate's EV status using SecTrustCopyExtendedResult(), | |
735 // which is an internal/private API function added in OS X 10.5.7. | |
736 // Note: "ExtendedResult" means extended validation results. | |
737 CFBundleRef bundle = | |
738 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security")); | |
739 if (bundle) { | |
740 SecTrustCopyExtendedResultFuncPtr copy_extended_result = | |
741 reinterpret_cast<SecTrustCopyExtendedResultFuncPtr>( | |
742 CFBundleGetFunctionPointerForName(bundle, | |
743 CFSTR("SecTrustCopyExtendedResult"))); | |
744 if (copy_extended_result) { | |
745 CFDictionaryRef ev_dict_temp = NULL; | |
746 status = copy_extended_result(trust_ref, &ev_dict_temp); | |
747 ScopedCFTypeRef<CFDictionaryRef> ev_dict(ev_dict_temp); | |
748 ev_dict_temp = NULL; | |
749 if (status == noErr && ev_dict) { | |
750 // In 10.7.3, SecTrustCopyExtendedResult returns noErr and populates | |
751 // ev_dict even for non-EV certificates, but only EV certificates | |
752 // will cause ev_dict to contain kSecEVOrganizationName. In previous | |
753 // releases, SecTrustCopyExtendedResult would only return noErr and | |
754 // populate ev_dict for EV certificates, but would always include | |
755 // kSecEVOrganizationName in that case, so checking for this key is | |
756 // appropriate for all known versions of SecTrustCopyExtendedResult. | |
757 // The actual organization name is unneeded here and can be accessed | |
758 // through other means. All that matters here is the OS' conception | |
759 // of whether or not the certificate is EV. | |
760 if (CFDictionaryContainsKey(ev_dict, | |
761 kSecEVOrganizationName)) { | |
762 verify_result->cert_status |= CERT_STATUS_IS_EV; | |
763 if (flags & CertVerifier::VERIFY_REV_CHECKING_ENABLED_EV_ONLY) | |
764 verify_result->cert_status |= CERT_STATUS_REV_CHECKING_ENABLED; | |
765 } | |
766 } | |
767 } | |
768 } | |
769 } | |
770 | |
771 return OK; | |
772 } | |
773 | |
774 } // namespace net | |
OLD | NEW |