forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcert_verify_proc_ios.cc
531 lines (469 loc) · 20.1 KB
/
cert_verify_proc_ios.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/cert_verify_proc_ios.h"
#include <CommonCrypto/CommonDigest.h>
#include "base/logging.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/notreached.h"
#include "crypto/sha2.h"
#include "net/base/net_errors.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/ct_serialization.h"
#include "net/cert/known_roots.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util_ios.h"
#include "net/cert/x509_util_ios_and_mac.h"
using base::ScopedCFTypeRef;
extern "C" {
// Declared in <Security/SecTrust.h>, available in iOS 12.1.1+
// TODO(mattm): Remove this weak_import once chromium requires a new enough
// iOS SDK.
OSStatus SecTrustSetSignedCertificateTimestamps(SecTrustRef, CFArrayRef)
__attribute__((weak_import));
} // extern "C"
namespace net {
namespace {
int NetErrorFromOSStatus(OSStatus status) {
switch (status) {
case noErr:
return OK;
case errSecNotAvailable:
return ERR_NOT_IMPLEMENTED;
case errSecAuthFailed:
return ERR_ACCESS_DENIED;
default:
return ERR_FAILED;
}
}
// Maps errors from OSStatus codes to CertStatus flags.
//
// The selection of errors is based off of Apple's SecPolicyChecks.list, and
// any unknown errors are mapped to CERT_STATUS_INVALID for safety.
CertStatus CertStatusFromOSStatus(OSStatus status) {
switch (status) {
case errSecHostNameMismatch:
return CERT_STATUS_COMMON_NAME_INVALID;
case errSecCertificateExpired:
case errSecCertificateNotValidYet:
return CERT_STATUS_DATE_INVALID;
case errSecCreateChainFailed:
case errSecNotTrusted:
// errSecVerifyActionFailed is used when CT is required
// and not present. The OS rejected this chain, and so mapping
// to CERT_STATUS_CT_COMPLIANCE_FAILED (which is informational,
// as policy enforcement is not handled in the CertVerifier)
// would cause this error to be ignored and mapped to
// CERT_STATUS_INVALID. Rather than do that, mark it simply as
// "untrusted". The CT_COMPLIANCE_FAILED bit is not set, since
// it's not necessarily a compliance failure with the embedder's
// CT policy. It's a bit of a hack, but hopefully temporary.
// errSecNotTrusted is somewhat similar. It applies for
// situations where a root isn't trusted or an intermediate
// isn't trusted, when a key is restricted, or when the calling
// application requested CT enforcement (which CertVerifier
// should never being doing).
case errSecVerifyActionFailed:
return CERT_STATUS_AUTHORITY_INVALID;
case errSecInvalidIDLinkage:
case errSecNoBasicConstraintsCA:
case errSecInvalidSubjectName:
case errSecInvalidExtendedKeyUsage:
case errSecInvalidKeyUsageForPolicy:
case errSecMissingRequiredExtension:
case errSecNoBasicConstraints:
case errSecPathLengthConstraintExceeded:
case errSecUnknownCertExtension:
case errSecUnknownCriticalExtensionFlag:
// errSecCertificatePolicyNotAllowed and errSecCertificateNameNotAllowed
// are used for certificates that violate the constraints imposed upon the
// issuer. Nominally this could be mapped to CERT_STATUS_AUTHORITY_INVALID,
// except the trustd behaviour is to treat this as a fatal
// (non-recoverable) error. That behavior is preserved here for consistency
// with Safari.
case errSecCertificatePolicyNotAllowed:
case errSecCertificateNameNotAllowed:
return CERT_STATUS_INVALID;
// Unfortunately, iOS's handling of weak digest algorithms and key sizes
// doesn't map exactly to Chrome's. errSecInvalidDigestAlgorithm and
// errSecUnsupportedKeySize may indicate errors that iOS considers fatal
// (too weak to process at all) or recoverable (too weak according to
// compliance policies).
// Further, because SecTrustEvaluateWithError only returns a single error
// code, a fatal error may have occurred elsewhere in the chain, so the
// overall result can't be used to distinguish individual certificate
// errors. For this complicated reason, the weak key and weak digest cases
// also map to CERT_STATUS_INVALID for safety.
case errSecInvalidDigestAlgorithm:
return CERT_STATUS_WEAK_SIGNATURE_ALGORITHM | CERT_STATUS_INVALID;
case errSecUnsupportedKeySize:
return CERT_STATUS_WEAK_KEY | CERT_STATUS_INVALID;
case errSecCertificateRevoked:
return CERT_STATUS_REVOKED;
case errSecIncompleteCertRevocationCheck:
return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
case errSecCertificateValidityPeriodTooLong:
return CERT_STATUS_VALIDITY_TOO_LONG;
case errSecInvalidCertificateRef:
case errSecInvalidName:
case errSecInvalidPolicyIdentifiers:
return CERT_STATUS_INVALID;
// This function should only be called on errors, so should always return a
// CertStatus code that is considered an error. If the input is unexpectedly
// errSecSuccess, return CERT_STATUS_INVALID for safety.
case errSecSuccess:
default:
OSSTATUS_LOG(WARNING, status)
<< "Unknown error mapped to CERT_STATUS_INVALID";
return CERT_STATUS_INVALID;
}
}
// Creates a series of SecPolicyRefs to be added to a SecTrustRef used to
// validate a certificate for an SSL server. |hostname| contains the name of
// the SSL server that the certificate should be verified against. If
// successful, returns noErr, and stores the resultant array of SecPolicyRefs
// in |policies|.
OSStatus CreateTrustPolicies(ScopedCFTypeRef<CFArrayRef>* policies) {
ScopedCFTypeRef<CFMutableArrayRef> local_policies(
CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
if (!local_policies)
return errSecAllocate;
SecPolicyRef ssl_policy = SecPolicyCreateBasicX509();
CFArrayAppendValue(local_policies, ssl_policy);
CFRelease(ssl_policy);
ssl_policy = SecPolicyCreateSSL(true, nullptr);
CFArrayAppendValue(local_policies, ssl_policy);
CFRelease(ssl_policy);
policies->reset(local_policies.release());
return noErr;
}
// Builds and evaluates a SecTrustRef for the certificate chain contained
// in |cert_array|, using the verification policies in |trust_policies|. On
// success, returns OK, and updates |trust_ref|, |is_trusted|, and
// |trust_error|. On failure, no output parameters are modified.
//
// Note: An OK return does not mean that |cert_array| is trusted, merely that
// verification was performed successfully.
int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array,
CFArrayRef trust_policies,
CFDataRef ocsp_response_ref,
CFArrayRef sct_array_ref,
ScopedCFTypeRef<SecTrustRef>* trust_ref,
ScopedCFTypeRef<CFArrayRef>* verified_chain,
bool* is_trusted,
ScopedCFTypeRef<CFErrorRef>* trust_error) {
SecTrustRef tmp_trust = nullptr;
OSStatus status =
SecTrustCreateWithCertificates(cert_array, trust_policies, &tmp_trust);
if (status)
return NetErrorFromOSStatus(status);
ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust);
if (TestRootCerts::HasInstance()) {
status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust);
if (status)
return NetErrorFromOSStatus(status);
}
if (ocsp_response_ref) {
status = SecTrustSetOCSPResponse(tmp_trust, ocsp_response_ref);
if (status)
return NetErrorFromOSStatus(status);
}
if (sct_array_ref) {
if (__builtin_available(iOS 12.1.1, *)) {
status = SecTrustSetSignedCertificateTimestamps(tmp_trust, sct_array_ref);
if (status)
return NetErrorFromOSStatus(status);
}
}
ScopedCFTypeRef<CFErrorRef> tmp_error;
bool tmp_is_trusted = false;
if (__builtin_available(iOS 12.0, *)) {
tmp_is_trusted =
SecTrustEvaluateWithError(tmp_trust, tmp_error.InitializeInto());
} else {
#if !defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_12_0
SecTrustResultType tmp_trust_result;
status = SecTrustEvaluate(tmp_trust, &tmp_trust_result);
if (status)
return NetErrorFromOSStatus(status);
switch (tmp_trust_result) {
case kSecTrustResultUnspecified:
case kSecTrustResultProceed:
tmp_is_trusted = true;
break;
case kSecTrustResultInvalid:
return ERR_FAILED;
default:
tmp_is_trusted = false;
}
#endif
}
ScopedCFTypeRef<CFMutableArrayRef> tmp_verified_chain(
CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
const CFIndex chain_length = SecTrustGetCertificateCount(tmp_trust);
for (CFIndex i = 0; i < chain_length; ++i) {
SecCertificateRef chain_cert = SecTrustGetCertificateAtIndex(tmp_trust, i);
CFArrayAppendValue(tmp_verified_chain, chain_cert);
}
trust_ref->swap(scoped_tmp_trust);
trust_error->swap(tmp_error);
verified_chain->reset(tmp_verified_chain.release());
*is_trusted = tmp_is_trusted;
return OK;
}
void GetCertChainInfo(CFArrayRef cert_chain, CertVerifyResult* verify_result) {
DCHECK_LT(0, CFArrayGetCount(cert_chain));
base::ScopedCFTypeRef<SecCertificateRef> verified_cert;
std::vector<base::ScopedCFTypeRef<SecCertificateRef>> verified_chain;
for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
if (i == 0) {
verified_cert.reset(chain_cert, base::scoped_policy::RETAIN);
} else {
verified_chain.emplace_back(chain_cert, base::scoped_policy::RETAIN);
}
base::ScopedCFTypeRef<CFDataRef> der_data(
SecCertificateCopyData(chain_cert));
if (!der_data) {
verify_result->cert_status |= CERT_STATUS_INVALID;
return;
}
base::StringPiece spki_bytes;
if (!asn1::ExtractSPKIFromDERCert(
base::StringPiece(
reinterpret_cast<const char*>(CFDataGetBytePtr(der_data)),
CFDataGetLength(der_data)),
&spki_bytes)) {
verify_result->cert_status |= CERT_STATUS_INVALID;
return;
}
HashValue sha256(HASH_VALUE_SHA256);
CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data());
verify_result->public_key_hashes.push_back(sha256);
}
if (!verified_cert.get()) {
NOTREACHED();
verify_result->cert_status |= CERT_STATUS_INVALID;
return;
}
scoped_refptr<X509Certificate> verified_cert_with_chain =
x509_util::CreateX509CertificateFromSecCertificate(verified_cert,
verified_chain);
if (verified_cert_with_chain)
verify_result->verified_cert = std::move(verified_cert_with_chain);
else
verify_result->cert_status |= CERT_STATUS_INVALID;
}
} // namespace
CertVerifyProcIOS::CertVerifyProcIOS() {}
// static
CertStatus CertVerifyProcIOS::GetCertFailureStatusFromError(CFErrorRef error) {
if (!error)
return CERT_STATUS_INVALID;
base::ScopedCFTypeRef<CFStringRef> error_domain(CFErrorGetDomain(error));
CFIndex error_code = CFErrorGetCode(error);
if (error_domain != kCFErrorDomainOSStatus) {
LOG(WARNING) << "Unhandled error domain: " << error;
return CERT_STATUS_INVALID;
}
return CertStatusFromOSStatus(error_code);
}
#if !defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_12_0
// The iOS APIs don't expose an API-stable set of reasons for certificate
// validation failures. However, internally, the reason is tracked, and it's
// converted to user-facing localized strings.
//
// In the absence of a consistent API, convert the English strings to their
// localized counterpart, and then compare that with the error properties. If
// they're equal, it's a strong sign that this was the cause for the error.
// While this will break if/when iOS changes the contents of these strings,
// it's sufficient enough for now.
//
// TODO(rsleevi): https://crbug.com/601915 - Use a less brittle solution when
// possible.
// static
CertStatus CertVerifyProcIOS::GetCertFailureStatusFromTrust(SecTrustRef trust) {
CertStatus reason = 0;
base::ScopedCFTypeRef<CFArrayRef> properties(SecTrustCopyProperties(trust));
if (!properties)
return CERT_STATUS_INVALID;
const CFIndex properties_length = CFArrayGetCount(properties);
if (properties_length == 0)
return CERT_STATUS_INVALID;
CFBundleRef bundle =
CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Security"));
CFStringRef date_string =
CFSTR("One or more certificates have expired or are not valid yet.");
ScopedCFTypeRef<CFStringRef> date_error(CFBundleCopyLocalizedString(
bundle, date_string, date_string, CFSTR("SecCertificate")));
CFStringRef trust_string = CFSTR("Root certificate is not trusted.");
ScopedCFTypeRef<CFStringRef> trust_error(CFBundleCopyLocalizedString(
bundle, trust_string, trust_string, CFSTR("SecCertificate")));
CFStringRef weak_string =
CFSTR("One or more certificates is using a weak key size.");
ScopedCFTypeRef<CFStringRef> weak_error(CFBundleCopyLocalizedString(
bundle, weak_string, weak_string, CFSTR("SecCertificate")));
CFStringRef hostname_mismatch_string = CFSTR("Hostname mismatch.");
ScopedCFTypeRef<CFStringRef> hostname_mismatch_error(
CFBundleCopyLocalizedString(bundle, hostname_mismatch_string,
hostname_mismatch_string,
CFSTR("SecCertificate")));
CFStringRef root_certificate_string =
CFSTR("Unable to build chain to root certificate.");
ScopedCFTypeRef<CFStringRef> root_certificate_error(
CFBundleCopyLocalizedString(bundle, root_certificate_string,
root_certificate_string,
CFSTR("SecCertificate")));
CFStringRef policy_requirements_not_met_string =
CFSTR("Policy requirements not met.");
ScopedCFTypeRef<CFStringRef> policy_requirements_not_met_error(
CFBundleCopyLocalizedString(bundle, policy_requirements_not_met_string,
policy_requirements_not_met_string,
CFSTR("SecCertificate")));
for (CFIndex i = 0; i < properties_length; ++i) {
CFDictionaryRef dict = reinterpret_cast<CFDictionaryRef>(
const_cast<void*>(CFArrayGetValueAtIndex(properties, i)));
CFStringRef error = reinterpret_cast<CFStringRef>(
const_cast<void*>(CFDictionaryGetValue(dict, CFSTR("value"))));
if (CFEqual(error, date_error)) {
reason |= CERT_STATUS_DATE_INVALID;
} else if (CFEqual(error, trust_error)) {
reason |= CERT_STATUS_AUTHORITY_INVALID;
} else if (CFEqual(error, weak_error)) {
reason |= CERT_STATUS_WEAK_KEY;
} else if (CFEqual(error, hostname_mismatch_error)) {
reason |= CERT_STATUS_COMMON_NAME_INVALID;
} else if (CFEqual(error, policy_requirements_not_met_error)) {
reason |= CERT_STATUS_INVALID | CERT_STATUS_AUTHORITY_INVALID;
} else if (CFEqual(error, root_certificate_error)) {
reason |= CERT_STATUS_AUTHORITY_INVALID;
} else {
LOG(ERROR) << "Unrecognized error: " << error;
reason |= CERT_STATUS_INVALID;
}
}
return reason;
}
#endif // !defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED <
// __IPHONE_12_0
bool CertVerifyProcIOS::SupportsAdditionalTrustAnchors() const {
return false;
}
CertVerifyProcIOS::~CertVerifyProcIOS() = default;
int CertVerifyProcIOS::VerifyInternal(
X509Certificate* cert,
const std::string& hostname,
const std::string& ocsp_response,
const std::string& sct_list,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result,
const NetLogWithSource& net_log) {
ScopedCFTypeRef<CFArrayRef> trust_policies;
OSStatus status = CreateTrustPolicies(&trust_policies);
if (status)
return NetErrorFromOSStatus(status);
ScopedCFTypeRef<CFMutableArrayRef> cert_array(
x509_util::CreateSecCertificateArrayForX509Certificate(
cert, x509_util::InvalidIntermediateBehavior::kIgnore));
if (!cert_array) {
verify_result->cert_status |= CERT_STATUS_INVALID;
return ERR_CERT_INVALID;
}
ScopedCFTypeRef<CFDataRef> ocsp_response_ref;
if (!ocsp_response.empty()) {
ocsp_response_ref.reset(
CFDataCreate(kCFAllocatorDefault,
reinterpret_cast<const UInt8*>(ocsp_response.data()),
base::checked_cast<CFIndex>(ocsp_response.size())));
if (!ocsp_response_ref)
return ERR_OUT_OF_MEMORY;
}
ScopedCFTypeRef<CFMutableArrayRef> sct_array_ref;
if (!sct_list.empty()) {
if (__builtin_available(iOS 12.1.1, *)) {
std::vector<base::StringPiece> decoded_sct_list;
if (ct::DecodeSCTList(sct_list, &decoded_sct_list)) {
sct_array_ref.reset(CFArrayCreateMutable(kCFAllocatorDefault,
decoded_sct_list.size(),
&kCFTypeArrayCallBacks));
if (!sct_array_ref)
return ERR_OUT_OF_MEMORY;
for (const auto& sct : decoded_sct_list) {
ScopedCFTypeRef<CFDataRef> sct_ref(CFDataCreate(
kCFAllocatorDefault, reinterpret_cast<const UInt8*>(sct.data()),
base::checked_cast<CFIndex>(sct.size())));
if (!sct_ref)
return ERR_OUT_OF_MEMORY;
CFArrayAppendValue(sct_array_ref.get(), sct_ref.get());
}
}
}
}
ScopedCFTypeRef<SecTrustRef> trust_ref;
bool is_trusted = false;
ScopedCFTypeRef<CFArrayRef> final_chain;
ScopedCFTypeRef<CFErrorRef> trust_error;
int err = BuildAndEvaluateSecTrustRef(
cert_array, trust_policies, ocsp_response_ref.get(), sct_array_ref.get(),
&trust_ref, &final_chain, &is_trusted, &trust_error);
if (err)
return err;
if (CFArrayGetCount(final_chain) == 0)
return ERR_FAILED;
// TODO(rsleevi): Support CRLSet revocation.
if (!is_trusted) {
if (__builtin_available(iOS 12.0, *)) {
verify_result->cert_status |= GetCertFailureStatusFromError(trust_error);
} else {
#if !defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_12_0
SecTrustResultType trust_result = kSecTrustResultInvalid;
status = SecTrustGetTrustResult(trust_ref.get(), &trust_result);
if (status)
return NetErrorFromOSStatus(status);
switch (trust_result) {
case kSecTrustResultUnspecified:
case kSecTrustResultProceed:
NOTREACHED();
break;
case kSecTrustResultDeny:
verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
break;
default:
verify_result->cert_status |=
GetCertFailureStatusFromTrust(trust_ref);
}
#else
// It should be impossible to reach this code, but if somehow it is
// reached it would allow any certificate as valid since no errors would
// be added to cert_status. Therefore, add a CHECK as a fail safe.
CHECK(false);
#endif
}
}
GetCertChainInfo(final_chain, verify_result);
// While iOS lacks the ability to distinguish system-trusted versus
// user-installed roots, the set of roots that are expected to comply with
// the Baseline Requirements can be determined by
// GetNetTrustAnchorHistogramForSPKI() - a non-zero value means that it is
// known as a publicly trusted, and therefore subject to the BRs, cert.
for (auto it = verify_result->public_key_hashes.rbegin();
it != verify_result->public_key_hashes.rend() &&
!verify_result->is_issued_by_known_root;
++it) {
verify_result->is_issued_by_known_root =
GetNetTrustAnchorHistogramIdForSPKI(*it) != 0;
}
if (IsCertStatusError(verify_result->cert_status))
return MapCertStatusToNetError(verify_result->cert_status);
LogNameNormalizationMetrics(".IOS", verify_result->verified_cert.get(),
verify_result->is_issued_by_known_root);
return OK;
}
} // namespace net