]> git.saurik.com Git - apple/security.git/blob - Security/libsecurity_keychain/lib/Trust.cpp
04a27c24fbc781baa63c351eb679b9b8e3f53b58
[apple/security.git] / Security / libsecurity_keychain / lib / Trust.cpp
1 /*
2 * Copyright (c) 2002-2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 //
25 // Trust.cpp
26 //
27 #include <security_keychain/Trust.h>
28 #include <security_keychain/TrustSettingsSchema.h>
29 #include <security_cdsa_utilities/cssmdates.h>
30 #include <security_utilities/cfutilities.h>
31 #include <CoreFoundation/CoreFoundation.h>
32 #include <Security/SecCertificate.h>
33 #include <Security/SecTrust.h>
34 #include "SecBridge.h"
35 #include "TrustAdditions.h"
36 #include "TrustKeychains.h"
37 #include <security_cdsa_client/dlclient.h>
38
39
40 using namespace Security;
41 using namespace KeychainCore;
42
43 //
44 // Translate CFDataRef to CssmData. The output shares the input's buffer.
45 //
46 static inline CssmData cfData(CFDataRef data)
47 {
48 return CssmData(const_cast<UInt8 *>(CFDataGetBytePtr(data)),
49 CFDataGetLength(data));
50 }
51
52 //
53 // Convert a SecPointer to a CF object.
54 //
55 static SecCertificateRef
56 convert(const SecPointer<Certificate> &certificate)
57 {
58 return *certificate;
59 }
60
61 //
62 // For now, we use a global TrustStore
63 //
64 ModuleNexus<TrustStore> Trust::gStore;
65
66 #pragma mark -- TrustKeychains --
67
68 static const CSSM_DL_DB_HANDLE nullCSSMDLDBHandle = {0,};
69 //
70 // TrustKeychains maintains a global reference to standard system keychains,
71 // to avoid having them be opened anew for each Trust instance.
72 //
73 class TrustKeychains
74 {
75 public:
76 TrustKeychains();
77 ~TrustKeychains() {}
78 CSSM_DL_DB_HANDLE rootStoreHandle() { return mRootStoreHandle; }
79 CSSM_DL_DB_HANDLE systemKcHandle() { return mSystem ? mSystem->database()->handle() : nullCSSMDLDBHandle; }
80 Keychain &systemKc() { return mSystem; }
81 Keychain &rootStore() { return *mRootStore; }
82
83 private:
84 DL* mRootStoreDL;
85 Db* mRootStoreDb;
86 Keychain* mRootStore;
87 CSSM_DL_DB_HANDLE mRootStoreHandle;
88 Keychain mSystem;
89 };
90
91 //
92 // Singleton maintaining open references to standard system keychains,
93 // to avoid having them be opened anew every time SecTrust is used.
94 //
95
96 static ModuleNexus<TrustKeychains> trustKeychains;
97 static ModuleNexus<RecursiveMutex> trustKeychainsMutex;
98
99 extern "C" bool GetServerMode();
100
101 TrustKeychains::TrustKeychains() :
102 mRootStoreHandle(nullCSSMDLDBHandle),
103 mSystem(globals().storageManager.make(ADMIN_CERT_STORE_PATH, false))
104 {
105 if (GetServerMode()) // in server mode? Don't make a keychain for the root store
106 {
107 mRootStoreDL = new DL(gGuidAppleFileDL),
108 mRootStoreDb = new Db(*mRootStoreDL, SYSTEM_ROOT_STORE_PATH),
109 (*mRootStoreDb)->activate();
110 mRootStoreHandle = (*mRootStoreDb)->handle();
111 }
112 else
113 {
114 mRootStore = new Keychain(globals().storageManager.make(SYSTEM_ROOT_STORE_PATH, false));
115 (*mRootStore)->database()->activate();
116 mRootStoreHandle = (*mRootStore)->database()->handle();
117 }
118 }
119
120 RecursiveMutex& SecTrustKeychainsGetMutex()
121 {
122 return trustKeychainsMutex();
123 }
124
125 #pragma mark -- Trust --
126 //
127 // Construct a Trust object with suitable defaults.
128 // Use setters for additional arguments before calling evaluate().
129 //
130 Trust::Trust(CFTypeRef certificates, CFTypeRef policies)
131 : mTP(gGuidAppleX509TP), mAction(CSSM_TP_ACTION_DEFAULT),
132 mCerts(cfArrayize(certificates)), mPolicies(cfArrayize(policies)),
133 mSearchLibs(NULL), mSearchLibsSet(false), mResult(kSecTrustResultInvalid),
134 mUsingTrustSettings(false), mAnchorPolicy(useAnchorsDefault), mMutex(Mutex::recursive)
135 {
136 if (!mPolicies) {
137 mPolicies.take(CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks));
138 }
139 }
140
141
142 //
143 // Clean up a Trust object
144 //
145 Trust::~Trust()
146 {
147 clearResults();
148 if (mSearchLibs) {
149 delete mSearchLibs;
150 }
151
152 mPolicies = NULL;
153 }
154
155
156 //
157 // Get searchLibs (a vector of Keychain objects);
158 // normally initialized to default search list
159 //
160 StorageManager::KeychainList& Trust::searchLibs(bool init)
161 {
162 if (!mSearchLibs) {
163 mSearchLibs = new StorageManager::KeychainList;
164 if (init) {
165 globals().storageManager.getSearchList(*mSearchLibs);
166 }
167 }
168 return *mSearchLibs;
169 }
170
171
172 //
173 // Set searchLibs to provided vector of Keychain objects
174 //
175 void Trust::searchLibs(StorageManager::KeychainList &libs)
176 {
177 searchLibs(false) = libs;
178 mSearchLibsSet = true;
179 }
180
181
182 //
183 // Retrieve the last TP evaluation result, if any
184 //
185 CSSM_TP_VERIFY_CONTEXT_RESULT_PTR Trust::cssmResult()
186 {
187 if (mResult == kSecTrustResultInvalid)
188 MacOSError::throwMe(errSecTrustNotAvailable);
189 return &mTpResult;
190 }
191
192
193 // SecCertificateRef -> CssmData
194 static
195 CssmData cfCertificateData(SecCertificateRef certificate)
196 {
197 return Certificate::required(certificate)->data();
198 }
199
200 // SecPolicyRef -> CssmField (CFDataRef/NULL or oid/value of a SecPolicy)
201 static
202 CssmField cfField(SecPolicyRef item)
203 {
204 SecPointer<Policy> policy = Policy::required(SecPolicyRef(item));
205 return CssmField(policy->oid(), policy->value());
206 }
207
208 // SecKeychain -> CssmDlDbHandle
209 #if 0
210 static
211 CSSM_DL_DB_HANDLE cfKeychain(SecKeychainRef ref)
212 {
213 Keychain keychain = KeychainImpl::required(ref);
214 return keychain->database()->handle();
215 }
216 #endif
217
218 #if !defined(NDEBUG)
219 void showCertSKID(const void *value, void *context);
220 #endif
221
222 //
223 // Here's the big "E" - evaluation.
224 // We build most of the CSSM-layer input structures dynamically right here;
225 // they will auto-destruct when we're done. The output structures are kept
226 // around (in our data members) for later analysis.
227 // Note that evaluate() can be called repeatedly, so we must be careful to
228 // dispose of prior results.
229 //
230 void Trust::evaluate(bool disableEV)
231 {
232 bool isEVCandidate=false;
233 // begin evaluation block with stack-based mutex
234 {
235 StLock<Mutex>_(mMutex);
236 // if we have evaluated before, release prior result
237 clearResults();
238
239 // determine whether the leaf certificate is an EV candidate
240 CFArrayRef allowedAnchors = NULL;
241 if (!disableEV) {
242 allowedAnchors = allowedEVRootsForLeafCertificate(mCerts);
243 isEVCandidate = (allowedAnchors != NULL);
244 }
245 CFArrayRef filteredCerts = NULL;
246 if (isEVCandidate) {
247 secdebug("evTrust", "Trust::evaluate() certificate is EV candidate");
248 filteredCerts = potentialEVChainWithCertificates(mCerts);
249 mCerts = filteredCerts;
250 } else {
251 secdebug("evTrust", "Trust::evaluate() performing standard evaluation");
252 if (mCerts) {
253 filteredCerts = CFArrayCreateMutableCopy(NULL, 0, mCerts);
254 }
255 if (mAnchors) {
256 allowedAnchors = CFArrayCreateMutableCopy(NULL, 0, mAnchors);
257 }
258 }
259 // retain these certs as long as we potentially could have results involving them
260 // (note that assignment to a CFRef type performs an implicit retain)
261 mAllowedAnchors = allowedAnchors;
262 mFilteredCerts = filteredCerts;
263
264 if (allowedAnchors)
265 CFRelease(allowedAnchors);
266 if (filteredCerts)
267 CFRelease(filteredCerts);
268
269 if (mAllowedAnchors)
270 {
271 secdebug("trusteval", "Trust::evaluate: anchors: %ld", CFArrayGetCount(mAllowedAnchors));
272 #if !defined(NDEBUG)
273 CFArrayApplyFunction(mAllowedAnchors, CFRangeMake(0, CFArrayGetCount(mAllowedAnchors)), showCertSKID, NULL);
274 #endif
275 }
276
277 // set default search list from user's default, if caller did not explicitly supply it
278 if(!mSearchLibsSet) {
279 globals().storageManager.getSearchList(searchLibs());
280 mSearchLibsSet = true;
281 }
282
283 // build the target cert group
284 CFToVector<CssmData, SecCertificateRef, cfCertificateData> subjects(mFilteredCerts);
285 CertGroup subjectCertGroup(CSSM_CERT_X_509v3,
286 CSSM_CERT_ENCODING_BER, CSSM_CERTGROUP_DATA);
287 subjectCertGroup.count() = subjects;
288 subjectCertGroup.blobCerts() = subjects;
289
290 // build a TP_VERIFY_CONTEXT, a veritable nightmare of a data structure
291 TPBuildVerifyContext context(mAction);
292
293 /*
294 * Guarantee *some* action data...
295 * NOTE this only works with the local X509 TP. When this module can deal
296 * with other TPs, this must be revisited.
297 */
298 CSSM_APPLE_TP_ACTION_DATA localActionData;
299 memset(&localActionData, 0, sizeof(localActionData));
300 CssmData localActionCData((uint8 *)&localActionData, sizeof(localActionData));
301 CSSM_APPLE_TP_ACTION_DATA *actionDataP = &localActionData;
302 if (mActionData) {
303 context.actionData() = cfData(mActionData);
304 actionDataP = (CSSM_APPLE_TP_ACTION_DATA *)context.actionData().data();
305 }
306 else {
307 context.actionData() = localActionCData;
308 }
309
310 bool hasSSLPolicy = policySpecified(mPolicies, CSSMOID_APPLE_TP_SSL);
311 bool hasEAPPolicy = policySpecified(mPolicies, CSSMOID_APPLE_TP_EAP);
312
313 if (!mAnchors) {
314 // always check trust settings if caller did not provide explicit trust anchors
315 actionDataP->ActionFlags |= CSSM_TP_ACTION_TRUST_SETTINGS;
316 }
317
318 if (mNetworkPolicy == useNetworkDefault) {
319 if (hasSSLPolicy) {
320 // enable network cert fetch for SSL only: <rdar://7422356>
321 actionDataP->ActionFlags |= CSSM_TP_ACTION_FETCH_CERT_FROM_NET;
322 }
323 }
324 else if (mNetworkPolicy == useNetworkEnabled)
325 actionDataP->ActionFlags |= CSSM_TP_ACTION_FETCH_CERT_FROM_NET;
326 else if (mNetworkPolicy == useNetworkDisabled)
327 actionDataP->ActionFlags &= ~(CSSM_TP_ACTION_FETCH_CERT_FROM_NET);
328
329 /*
330 * Policies (one at least, please).
331 * For revocation policies, see if any have been explicitly specified...
332 */
333 CFMutableArrayRef allPolicies = NULL;
334 uint32 numRevocationAdded = 0;
335 bool requirePerCert = (actionDataP->ActionFlags & CSSM_TP_ACTION_REQUIRE_REV_PER_CERT);
336
337 // If a new unified revocation policy was explicitly specified,
338 // convert into old-style individual OCSP and CRL policies.
339 // Note that the caller could configure revocation policy options
340 // to explicitly disable both methods, so 0 policies might be added,
341 // in which case we must no longer consider the cert an EV candidate.
342
343 allPolicies = convertRevocationPolicy(numRevocationAdded, context.allocator);
344 if (allPolicies) {
345 // caller has explicitly set the revocation policy they want to use
346 secdebug("evTrust", "Trust::evaluate() using explicit revocation policy (%d)",
347 numRevocationAdded);
348 if (numRevocationAdded == 0)
349 isEVCandidate = false;
350 }
351 else if (mAnchors && (CFArrayGetCount(mAnchors)==0) && (searchLibs().size()==0)) {
352 // caller explicitly provided empty anchors and no keychain list,
353 // and did not explicitly specify the revocation policy;
354 // override global revocation check setting for this evaluation
355 secdebug("evTrust", "Trust::evaluate() has empty anchors and no keychains");
356 allPolicies = NULL; // use only mPolicies
357 isEVCandidate = false;
358 }
359 else if (isEVCandidate || requirePerCert) {
360 // force revocation checking for this evaluation
361 secdebug("evTrust", "Trust::evaluate() forcing OCSP/CRL revocation check");
362 allPolicies = forceRevocationPolicies(true, requirePerCert,
363 numRevocationAdded, context.allocator, requirePerCert);
364 }
365 else if(!(revocationPolicySpecified(mPolicies))) {
366 // none specified in mPolicies; try preferences
367 allPolicies = addPreferenceRevocationPolicies(!(hasSSLPolicy || hasEAPPolicy),
368 !(hasSSLPolicy || hasEAPPolicy), numRevocationAdded, context.allocator);
369 }
370 if (allPolicies == NULL) {
371 // use mPolicies; no revocation checking will be performed
372 secdebug("evTrust", "Trust::evaluate() will not perform revocation check");
373 CFIndex numPolicies = CFArrayGetCount(mPolicies);
374 CFAllocatorRef allocator = CFGetAllocator(mPolicies);
375 allPolicies = CFArrayCreateMutableCopy(allocator, numPolicies, mPolicies);
376 }
377 orderRevocationPolicies(allPolicies);
378 CFToVector<CssmField, SecPolicyRef, cfField> policies(allPolicies);
379 #if 0
380 // error exit here if empty policies are not supported
381 if (policies.empty())
382 MacOSError::throwMe(CSSMERR_TP_INVALID_POLICY_IDENTIFIERS);
383 #endif
384 context.setPolicies(policies, policies);
385
386 // anchor certificates (if caller provides them, or if cert requires EV)
387 CFCopyRef<CFArrayRef> anchors(mAllowedAnchors);
388 CFToVector<CssmData, SecCertificateRef, cfCertificateData> roots(anchors);
389 if (!anchors) {
390 // no anchor certificates were provided;
391 // built-in anchors will be trusted unless explicitly disabled.
392 mUsingTrustSettings = (mAnchorPolicy < useAnchorsOnly);
393 secdebug("userTrust", "Trust::evaluate() %s",
394 (mUsingTrustSettings) ? "using UserTrust" : "has no trusted anchors!");
395 }
396 else {
397 // anchor certificates were provided;
398 // built-in anchors will NOT also be trusted unless explicitly enabled.
399 mUsingTrustSettings = (mAnchorPolicy == useAnchorsAndBuiltIns);
400 secdebug("userTrust", "Trust::evaluate() using %s %s anchors",
401 (mUsingTrustSettings) ? "UserTrust AND" : "only",
402 (isEVCandidate) ? "EV" : "caller");
403 context.anchors(roots, roots);
404 }
405
406 // dlDbList (keychain list)
407 vector<CSSM_DL_DB_HANDLE> dlDbList;
408 {
409 StLock<Mutex> _(SecTrustKeychainsGetMutex());
410 StorageManager::KeychainList& list = searchLibs();
411 for (StorageManager::KeychainList::const_iterator it = list.begin();
412 it != list.end(); it++)
413 {
414 try
415 {
416 // For the purpose of looking up intermediate certificates to establish trust,
417 // do not include the network-based LDAP or DotMac pseudo-keychains. (The only
418 // time the network should be consulted for certificates is if there is an AIA
419 // extension with a specific URL, which will be handled by the TP code.)
420 CSSM_DL_DB_HANDLE dldbHandle = (*it)->database()->handle();
421 if (dldbHandle.DLHandle) {
422 CSSM_GUID guid = {};
423 CSSM_RETURN crtn = CSSM_GetModuleGUIDFromHandle(dldbHandle.DLHandle, &guid);
424 if (crtn == CSSM_OK) {
425 if ((memcmp(&guid, &gGuidAppleLDAPDL, sizeof(CSSM_GUID))==0) ||
426 (memcmp(&guid, &gGuidAppleDotMacDL, sizeof(CSSM_GUID))==0)) {
427 continue; // don't add to dlDbList
428 }
429 }
430 }
431 // This DB is OK to search for intermediate certificates.
432 dlDbList.push_back(dldbHandle);
433 }
434 catch (...)
435 {
436 }
437 }
438 if(mUsingTrustSettings) {
439 /* Append system anchors for use with Trust Settings */
440 try {
441 CSSM_DL_DB_HANDLE rootStoreHandle = trustKeychains().rootStoreHandle();
442 if (rootStoreHandle.DBHandle)
443 dlDbList.push_back(rootStoreHandle);
444 actionDataP->ActionFlags |= CSSM_TP_ACTION_TRUST_SETTINGS;
445 }
446 catch (...) {
447 // no root store or system keychain; don't use trust settings but continue
448 mUsingTrustSettings = false;
449 }
450 try {
451 CSSM_DL_DB_HANDLE systemKcHandle = trustKeychains().systemKcHandle();
452 if (systemKcHandle.DBHandle)
453 dlDbList.push_back(systemKcHandle);
454 }
455 catch(...) {
456 /* Oh well, at least we got the root store DB */
457 }
458 }
459 context.setDlDbList((uint32)dlDbList.size(), &dlDbList[0]);
460 }
461
462 // verification time
463 char timeString[15];
464 if (mVerifyTime) {
465 CssmUniformDate(static_cast<CFDateRef>(mVerifyTime)).convertTo(
466 timeString, sizeof(timeString));
467 context.time(timeString);
468 }
469
470 // to avoid keychain open/close thrashing, hold a copy of the search list
471 StorageManager::KeychainList *holdSearchList = NULL;
472 if (searchLibs().size() > 0) {
473 holdSearchList = new StorageManager::KeychainList;
474 globals().storageManager.getSearchList(*holdSearchList);
475 }
476
477 // Go TP!
478 try {
479 mTP->certGroupVerify(subjectCertGroup, context, &mTpResult);
480 mTpReturn = errSecSuccess;
481 } catch (CommonError &err) {
482 mTpReturn = err.osStatus();
483 secdebug("trusteval", "certGroupVerify exception: %d", (int)mTpReturn);
484 }
485 mResult = diagnoseOutcome();
486
487 // see if we can use the evidence
488 if (mTpResult.count() > 0
489 && mTpResult[0].form() == CSSM_EVIDENCE_FORM_APPLE_HEADER
490 && mTpResult[0].as<CSSM_TP_APPLE_EVIDENCE_HEADER>()->Version == CSSM_TP_APPLE_EVIDENCE_VERSION
491 && mTpResult.count() == 3
492 && mTpResult[1].form() == CSSM_EVIDENCE_FORM_APPLE_CERTGROUP
493 && mTpResult[2].form() == CSSM_EVIDENCE_FORM_APPLE_CERT_INFO) {
494 evaluateUserTrust(*mTpResult[1].as<CertGroup>(),
495 mTpResult[2].as<CSSM_TP_APPLE_EVIDENCE_INFO>(), anchors);
496 } else {
497 // unexpected evidence information. Can't use it
498 secdebug("trusteval", "unexpected evidence ignored");
499 }
500
501 /* do post-processing for the evaluated certificate chain */
502 CFArrayRef fullChain = makeCFArray(convert, mCertChain);
503 CFDictionaryRef etResult = extendedTrustResults(fullChain, mResult, mTpReturn, isEVCandidate);
504 mExtendedResult = etResult; // assignment to CFRef type is an implicit retain
505 if (etResult) {
506 CFRelease(etResult);
507 }
508 if (fullChain) {
509 CFRelease(fullChain);
510 }
511
512 if (allPolicies) {
513 /* clean up revocation policies we created implicitly */
514 if(numRevocationAdded) {
515 freeAddedRevocationPolicyData(allPolicies, numRevocationAdded, context.allocator);
516 }
517 CFRelease(allPolicies);
518 }
519
520 if (holdSearchList) {
521 delete holdSearchList;
522 holdSearchList = NULL;
523 }
524 } // end evaluation block with mutex; releases all temporary allocations in this scope
525
526
527 if (isEVCandidate && mResult == kSecTrustResultRecoverableTrustFailure &&
528 (mTpReturn == CSSMERR_TP_NOT_TRUSTED || isRevocationServerMetaError(mTpReturn))) {
529 // re-do the evaluation, this time disabling EV
530 evaluate(true);
531 }
532 }
533
534 // CSSM_RETURN values that map to kSecTrustResultRecoverableTrustFailure.
535 static const CSSM_RETURN recoverableErrors[] =
536 {
537 CSSMERR_TP_INVALID_ANCHOR_CERT,
538 CSSMERR_TP_NOT_TRUSTED,
539 CSSMERR_TP_VERIFICATION_FAILURE,
540 CSSMERR_TP_VERIFY_ACTION_FAILED,
541 CSSMERR_TP_INVALID_REQUEST_INPUTS,
542 CSSMERR_TP_CERT_EXPIRED,
543 CSSMERR_TP_CERT_NOT_VALID_YET,
544 CSSMERR_TP_CERTIFICATE_CANT_OPERATE,
545 CSSMERR_TP_INVALID_CERT_AUTHORITY,
546 CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK,
547 CSSMERR_APPLETP_HOSTNAME_MISMATCH,
548 CSSMERR_TP_VERIFY_ACTION_FAILED,
549 CSSMERR_APPLETP_SMIME_EMAIL_ADDRS_NOT_FOUND,
550 CSSMERR_APPLETP_SMIME_NO_EMAIL_ADDRS,
551 CSSMERR_APPLETP_SMIME_BAD_EXT_KEY_USE,
552 CSSMERR_APPLETP_CS_BAD_CERT_CHAIN_LENGTH,
553 CSSMERR_APPLETP_CS_NO_BASIC_CONSTRAINTS,
554 CSSMERR_APPLETP_CS_BAD_PATH_LENGTH,
555 CSSMERR_APPLETP_CS_NO_EXTENDED_KEY_USAGE,
556 CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE,
557 CSSMERR_APPLETP_CODE_SIGN_DEVELOPMENT,
558 CSSMERR_APPLETP_RS_BAD_CERT_CHAIN_LENGTH,
559 CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN,
560 CSSMERR_APPLETP_CRL_NOT_FOUND,
561 CSSMERR_APPLETP_CRL_SERVER_DOWN,
562 CSSMERR_APPLETP_CRL_NOT_VALID_YET,
563 CSSMERR_APPLETP_OCSP_UNAVAILABLE,
564 CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK,
565 CSSMERR_APPLETP_NETWORK_FAILURE,
566 CSSMERR_APPLETP_OCSP_RESP_TRY_LATER,
567 CSSMERR_APPLETP_IDENTIFIER_MISSING,
568 };
569 #define NUM_RECOVERABLE_ERRORS (sizeof(recoverableErrors) / sizeof(CSSM_RETURN))
570
571 //
572 // Classify the TP outcome in terms of a SecTrustResultType
573 //
574 SecTrustResultType Trust::diagnoseOutcome()
575 {
576 StLock<Mutex>_(mMutex);
577
578 uint32 chainLength = 0;
579 if (mTpResult.count() == 3 &&
580 mTpResult[1].form() == CSSM_EVIDENCE_FORM_APPLE_CERTGROUP &&
581 mTpResult[2].form() == CSSM_EVIDENCE_FORM_APPLE_CERT_INFO)
582 {
583 const CertGroup &chain = *mTpResult[1].as<CertGroup>();
584 chainLength = chain.count();
585 }
586
587 switch (mTpReturn) {
588 case errSecSuccess: // peachy
589 if (mUsingTrustSettings)
590 {
591 if (chainLength)
592 {
593 const CSSM_TP_APPLE_EVIDENCE_INFO *infoList = mTpResult[2].as<CSSM_TP_APPLE_EVIDENCE_INFO>();
594 const TPEvidenceInfo &info = TPEvidenceInfo::overlay(infoList[chainLength-1]);
595 const CSSM_TP_APPLE_CERT_STATUS resultCertStatus = info.status();
596 bool hasUserDomainTrust = ((resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_TRUST) &&
597 (resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_USER));
598 bool hasAdminDomainTrust = ((resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_TRUST) &&
599 (resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_ADMIN));
600 if (hasUserDomainTrust || hasAdminDomainTrust)
601 {
602 return kSecTrustResultProceed; // explicitly allowed
603 }
604 }
605 }
606 return kSecTrustResultUnspecified; // cert evaluates OK
607 case CSSMERR_TP_INVALID_CERTIFICATE: // bad certificate
608 return kSecTrustResultFatalTrustFailure;
609 case CSSMERR_APPLETP_TRUST_SETTING_DENY: // authoritative denial
610 return kSecTrustResultDeny;
611 default:
612 break;
613 }
614
615 // a known list of returns maps to kSecTrustResultRecoverableTrustFailure
616 const CSSM_RETURN *errp=recoverableErrors;
617 for(unsigned dex=0; dex<NUM_RECOVERABLE_ERRORS; dex++, errp++) {
618 if(*errp == mTpReturn) {
619 return kSecTrustResultRecoverableTrustFailure;
620 }
621 }
622 return kSecTrustResultOtherError; // unknown
623 }
624
625
626 //
627 // Assuming a good evidence chain, check user trust
628 // settings and set mResult accordingly.
629 //
630 void Trust::evaluateUserTrust(const CertGroup &chain,
631 const CSSM_TP_APPLE_EVIDENCE_INFO *infoList, CFCopyRef<CFArrayRef> anchors)
632 {
633 StLock<Mutex>_(mMutex);
634 // extract cert chain as Certificate objects
635 mCertChain.resize(chain.count());
636 for (uint32 n = 0; n < mCertChain.size(); n++) {
637 const TPEvidenceInfo &info = TPEvidenceInfo::overlay(infoList[n]);
638 if (info.recordId()) {
639 Keychain keychain = keychainByDLDb(info.DlDbHandle);
640 DbUniqueRecord uniqueId(keychain->database()->newDbUniqueRecord());
641 secdebug("trusteval", "evidence %lu from keychain \"%s\"", (unsigned long)n, keychain->name());
642 *static_cast<CSSM_DB_UNIQUE_RECORD_PTR *>(uniqueId) = info.UniqueRecord;
643 uniqueId->activate(); // transfers ownership
644 Item ii = keychain->item(CSSM_DL_DB_RECORD_X509_CERTIFICATE, uniqueId);
645 Certificate* cert = dynamic_cast<Certificate*>(ii.get());
646 if (cert == NULL) {
647 CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER);
648 }
649 mCertChain[n] = cert;
650 } else if (info.status(CSSM_CERT_STATUS_IS_IN_INPUT_CERTS)) {
651 secdebug("trusteval", "evidence %lu from input cert %lu", (unsigned long)n, (unsigned long)info.index());
652 assert(info.index() < uint32(CFArrayGetCount(mCerts)));
653 SecCertificateRef cert = SecCertificateRef(CFArrayGetValueAtIndex(mCerts,
654 info.index()));
655 mCertChain[n] = Certificate::required(cert);
656 } else if (info.status(CSSM_CERT_STATUS_IS_IN_ANCHORS)) {
657 secdebug("trusteval", "evidence %lu from anchor cert %lu", (unsigned long)n, (unsigned long)info.index());
658 assert(info.index() < uint32(CFArrayGetCount(anchors)));
659 SecCertificateRef cert = SecCertificateRef(CFArrayGetValueAtIndex(anchors,
660 info.index()));
661 mCertChain[n] = Certificate::required(cert);
662 } else {
663 // unknown source; make a new Certificate for it
664 secdebug("trusteval", "evidence %lu from unknown source", (unsigned long)n);
665 mCertChain[n] =
666 new Certificate(chain.blobCerts()[n],
667 CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_BER);
668 }
669 }
670
671 // now walk the chain, leaf-to-root, checking for user settings
672 TrustStore &store = gStore();
673 SecPointer<Policy> policy = (CFArrayGetCount(mPolicies)) ?
674 Policy::required(SecPolicyRef(CFArrayGetValueAtIndex(mPolicies, 0))) : NULL;
675 for (mResultIndex = 0;
676 mResult == kSecTrustResultUnspecified && mResultIndex < mCertChain.size() && policy;
677 mResultIndex++) {
678 if (!mCertChain[mResultIndex]) {
679 assert(false);
680 continue;
681 }
682 mResult = store.find(mCertChain[mResultIndex], policy, searchLibs());
683 secdebug("trusteval", "trustResult=%d from cert %d", (int)mResult, (int)mResultIndex);
684 }
685 }
686
687
688 //
689 // Release TP evidence information.
690 // This information is severely under-defined by CSSM, so we proceed
691 // as follows:
692 // (a) If the evidence matches an Apple-defined pattern, use specific
693 // knowledge of that format.
694 // (b) Otherwise, assume that the void * are flat blocks of memory.
695 //
696 void Trust::releaseTPEvidence(TPVerifyResult &result, Allocator &allocator)
697 {
698 if (result.count() > 0) { // something to do
699 if (result[0].form() == CSSM_EVIDENCE_FORM_APPLE_HEADER) {
700 // Apple defined evidence form -- use intimate knowledge
701 if (result[0].as<CSSM_TP_APPLE_EVIDENCE_HEADER>()->Version == CSSM_TP_APPLE_EVIDENCE_VERSION
702 && result.count() == 3
703 && result[1].form() == CSSM_EVIDENCE_FORM_APPLE_CERTGROUP
704 && result[2].form() == CSSM_EVIDENCE_FORM_APPLE_CERT_INFO) {
705 // proper format
706 CertGroup& certs = *result[1].as<CertGroup>();
707 CSSM_TP_APPLE_EVIDENCE_INFO *evidence = result[2].as<CSSM_TP_APPLE_EVIDENCE_INFO>();
708 uint32 count = certs.count();
709 allocator.free(result[0].data()); // just a struct
710 certs.destroy(allocator); // certgroup contents
711 allocator.free(result[1].data()); // the CertGroup itself
712 for (uint32 n = 0; n < count; n++)
713 allocator.free(evidence[n].StatusCodes);
714 allocator.free(result[2].data()); // array of (flat) info structs
715 } else {
716 secdebug("trusteval", "unrecognized Apple TP evidence format");
717 // drop it -- better leak than kill
718 }
719 } else {
720 // unknown format -- blindly assume flat blobs
721 secdebug("trusteval", "destroying unknown TP evidence format");
722 for (uint32 n = 0; n < result.count(); n++)
723 {
724 allocator.free(result[n].data());
725 }
726 }
727
728 allocator.free (result.Evidence);
729 }
730 }
731
732
733 //
734 // Clear evaluation results unless state is initial (invalid)
735 //
736 void Trust::clearResults()
737 {
738 StLock<Mutex>_(mMutex);
739 if (mResult != kSecTrustResultInvalid) {
740 releaseTPEvidence(mTpResult, mTP.allocator());
741 mResult = kSecTrustResultInvalid;
742 }
743 }
744
745
746 //
747 // Build evidence information
748 //
749 void Trust::buildEvidence(CFArrayRef &certChain, TPEvidenceInfo * &statusChain)
750 {
751 StLock<Mutex>_(mMutex);
752 if (mResult == kSecTrustResultInvalid)
753 MacOSError::throwMe(errSecTrustNotAvailable);
754 certChain = mEvidenceReturned =
755 makeCFArray(convert, mCertChain);
756 if(mTpResult.count() >= 3) {
757 statusChain = mTpResult[2].as<TPEvidenceInfo>();
758 }
759 else {
760 statusChain = NULL;
761 }
762 }
763
764
765 //
766 // Return extended result dictionary
767 //
768 void Trust::extendedResult(CFDictionaryRef &result)
769 {
770 if (mResult == kSecTrustResultInvalid)
771 MacOSError::throwMe(errSecTrustNotAvailable);
772 if (mExtendedResult)
773 CFRetain(mExtendedResult); // retain before handing out to caller
774 result = mExtendedResult;
775 }
776
777
778 //
779 // Return properties array (a CFDictionaryRef for each certificate in chain)
780 //
781 CFArrayRef Trust::properties()
782 {
783 // Builds and returns an array which the caller must release.
784 StLock<Mutex>_(mMutex);
785 CFMutableArrayRef properties = CFArrayCreateMutable(NULL, 0,
786 &kCFTypeArrayCallBacks);
787 if (mResult == kSecTrustResultInvalid) // chain not built or evaluated
788 return properties;
789
790 // Walk the chain from leaf to anchor, building properties dictionaries
791 for (uint32 idx=0; idx < mCertChain.size(); idx++) {
792 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0,
793 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
794 if (dict) {
795 CFStringRef title = NULL;
796 mCertChain[idx]->inferLabel(false, &title);
797 if (title) {
798 CFDictionarySetValue(dict, (const void *)kSecPropertyTypeTitle, (const void *)title);
799 CFRelease(title);
800 }
801 if (idx == 0 && mTpReturn != errSecSuccess) {
802 CFStringRef error = SecCopyErrorMessageString(mTpReturn, NULL);
803 if (error) {
804 CFDictionarySetValue(dict, (const void *)kSecPropertyTypeError, (const void *)error);
805 CFRelease(error);
806 }
807 }
808 CFArrayAppendValue(properties, (const void *)dict);
809 CFRelease(dict);
810 }
811 }
812
813 return properties;
814 }
815
816 //
817 // Return dictionary of evaluation results
818 //
819 CFDictionaryRef Trust::results()
820 {
821 // Builds and returns a dictionary which the caller must release.
822 StLock<Mutex>_(mMutex);
823 CFMutableDictionaryRef results = CFDictionaryCreateMutable(NULL, 0,
824 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
825
826 // kSecTrustResultValue
827 CFNumberRef numValue = CFNumberCreate(NULL, kCFNumberSInt32Type, &mResult);
828 if (numValue) {
829 CFDictionarySetValue(results, (const void *)kSecTrustResultValue, (const void *)numValue);
830 CFRelease(numValue);
831 }
832 if (mResult == kSecTrustResultInvalid || !mExtendedResult)
833 return results; // we have nothing more to add
834
835 // kSecTrustEvaluationDate
836 CFTypeRef evaluationDate;
837 if (CFDictionaryGetValueIfPresent(mExtendedResult, kSecTrustEvaluationDate, &evaluationDate))
838 CFDictionarySetValue(results, (const void *)kSecTrustEvaluationDate, (const void *)evaluationDate);
839
840 // kSecTrustExtendedValidation, kSecTrustOrganizationName
841 CFTypeRef organizationName;
842 if (CFDictionaryGetValueIfPresent(mExtendedResult, kSecEVOrganizationName, &organizationName)) {
843 CFDictionarySetValue(results, (const void *)kSecTrustOrganizationName, (const void *)organizationName);
844 CFDictionarySetValue(results, (const void *)kSecTrustExtendedValidation, (const void *)kCFBooleanTrue);
845 }
846
847 // kSecTrustRevocationChecked, kSecTrustRevocationValidUntilDate
848 CFTypeRef expirationDate;
849 if (CFDictionaryGetValueIfPresent(mExtendedResult, kSecTrustExpirationDate, &expirationDate)) {
850 CFDictionarySetValue(results, (const void *)kSecTrustRevocationValidUntilDate, (const void *)expirationDate);
851 CFDictionarySetValue(results, (const void *)kSecTrustRevocationChecked, (const void *)kCFBooleanTrue);
852 }
853
854 return results;
855 }
856
857
858
859 //* ===========================================================================
860 //* We need a way to compare two CSSM_DL_DB_HANDLEs WITHOUT using a operator
861 //* overload
862 //* ===========================================================================
863 static
864 bool Compare_CSSM_DL_DB_HANDLE(const CSSM_DL_DB_HANDLE &h1, const CSSM_DL_DB_HANDLE &h2)
865 {
866 return (h1.DLHandle == h2.DLHandle && h1.DBHandle == h2.DBHandle);
867 }
868
869
870
871 //
872 // Given a DL_DB_HANDLE, locate the Keychain object (from the search list)
873 //
874 Keychain Trust::keychainByDLDb(const CSSM_DL_DB_HANDLE &handle)
875 {
876 StLock<Mutex>_(mMutex);
877 StorageManager::KeychainList& list = searchLibs();
878 for (StorageManager::KeychainList::const_iterator it = list.begin();
879 it != list.end(); it++)
880 {
881 try
882 {
883
884 if (Compare_CSSM_DL_DB_HANDLE((*it)->database()->handle(), handle))
885 return *it;
886 }
887 catch (...)
888 {
889 }
890 }
891 if(mUsingTrustSettings) {
892 try {
893 if(Compare_CSSM_DL_DB_HANDLE(trustKeychains().rootStoreHandle(), handle)) {
894 return trustKeychains().rootStore();
895 }
896 if(Compare_CSSM_DL_DB_HANDLE(trustKeychains().systemKcHandle(), handle)) {
897 return trustKeychains().systemKc();
898 }
899 }
900 catch(...) {
901 /* one of those is missing; proceed */
902 }
903 }
904
905 // could not find in search list - internal error
906
907 // we now throw an error here rather than assert and silently fail. That way our application won't crash...
908 MacOSError::throwMe(errSecInternal);
909 }