]> git.saurik.com Git - apple/security.git/blob - libsecurity_keychain/lib/Trust.cpp
Security-55471.14.8.tar.gz
[apple/security.git] / libsecurity_keychain / lib / Trust.cpp
1 /*
2 * Copyright (c) 2002-2010,2012 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 = allowedEVRootsForLeafCertificate(mCerts);
241 CFArrayRef filteredCerts = NULL;
242 isEVCandidate = (allowedAnchors && !disableEV) ? true : false;
243 if (isEVCandidate) {
244 secdebug("evTrust", "Trust::evaluate() certificate is EV candidate");
245 filteredCerts = potentialEVChainWithCertificates(mCerts);
246 mCerts = filteredCerts;
247 } else {
248 secdebug("evTrust", "Trust::evaluate() performing standard evaluation");
249 if (mCerts) {
250 filteredCerts = CFArrayCreateMutableCopy(NULL, 0, mCerts);
251 }
252 if (mAnchors) {
253 allowedAnchors = CFArrayCreateMutableCopy(NULL, 0, mAnchors);
254 }
255 }
256 // retain these certs as long as we potentially could have results involving them
257 // (note that assignment to a CFRef type performs an implicit retain)
258 mAllowedAnchors = allowedAnchors;
259 mFilteredCerts = filteredCerts;
260
261 if (allowedAnchors)
262 CFRelease(allowedAnchors);
263 if (filteredCerts)
264 CFRelease(filteredCerts);
265
266 if (mAllowedAnchors)
267 {
268 secdebug("trusteval", "Trust::evaluate: anchors: %ld", CFArrayGetCount(mAllowedAnchors));
269 #if !defined(NDEBUG)
270 CFArrayApplyFunction(mAllowedAnchors, CFRangeMake(0, CFArrayGetCount(mAllowedAnchors)), showCertSKID, NULL);
271 #endif
272 }
273
274 // set default search list from user's default, if caller did not explicitly supply it
275 if(!mSearchLibsSet) {
276 globals().storageManager.getSearchList(searchLibs());
277 mSearchLibsSet = true;
278 }
279
280 // build the target cert group
281 CFToVector<CssmData, SecCertificateRef, cfCertificateData> subjects(mFilteredCerts);
282 CertGroup subjectCertGroup(CSSM_CERT_X_509v3,
283 CSSM_CERT_ENCODING_BER, CSSM_CERTGROUP_DATA);
284 subjectCertGroup.count() = subjects;
285 subjectCertGroup.blobCerts() = subjects;
286
287 // build a TP_VERIFY_CONTEXT, a veritable nightmare of a data structure
288 TPBuildVerifyContext context(mAction);
289
290 /*
291 * Guarantee *some* action data...
292 * NOTE this only works with the local X509 TP. When this module can deal
293 * with other TPs, this must be revisited.
294 */
295 CSSM_APPLE_TP_ACTION_DATA localActionData;
296 memset(&localActionData, 0, sizeof(localActionData));
297 CssmData localActionCData((uint8 *)&localActionData, sizeof(localActionData));
298 CSSM_APPLE_TP_ACTION_DATA *actionDataP = &localActionData;
299 if (mActionData) {
300 context.actionData() = cfData(mActionData);
301 actionDataP = (CSSM_APPLE_TP_ACTION_DATA *)context.actionData().data();
302 }
303 else {
304 context.actionData() = localActionCData;
305 }
306
307 if (!mAnchors) {
308 // always check trust settings if caller did not provide explicit trust anchors
309 actionDataP->ActionFlags |= CSSM_TP_ACTION_TRUST_SETTINGS;
310 }
311
312 if (mNetworkPolicy == useNetworkDefault) {
313 if (policySpecified(mPolicies, CSSMOID_APPLE_TP_SSL)) {
314 // enable network cert fetch for SSL only: <rdar://7422356>
315 actionDataP->ActionFlags |= CSSM_TP_ACTION_FETCH_CERT_FROM_NET;
316 }
317 }
318 else if (mNetworkPolicy == useNetworkEnabled)
319 actionDataP->ActionFlags |= CSSM_TP_ACTION_FETCH_CERT_FROM_NET;
320 else if (mNetworkPolicy == useNetworkDisabled)
321 actionDataP->ActionFlags &= ~(CSSM_TP_ACTION_FETCH_CERT_FROM_NET);
322
323 /*
324 * Policies (one at least, please).
325 * For revocation policies, see if any have been explicitly specified...
326 */
327 CFMutableArrayRef allPolicies = NULL;
328 uint32 numRevocationAdded = 0;
329 bool requirePerCert = (actionDataP->ActionFlags & CSSM_TP_ACTION_REQUIRE_REV_PER_CERT);
330
331 // If a new unified revocation policy was explicitly specified,
332 // convert into old-style individual OCSP and CRL policies.
333 // Note that the caller could configure revocation policy options
334 // to explicitly disable both methods, so 0 policies might be added,
335 // in which case we must no longer consider the cert an EV candidate.
336
337 allPolicies = convertRevocationPolicy(numRevocationAdded, context.allocator);
338 if (allPolicies) {
339 // caller has explicitly set the revocation policy they want to use
340 secdebug("evTrust", "Trust::evaluate() using explicit revocation policy (%d)",
341 numRevocationAdded);
342 if (numRevocationAdded == 0)
343 isEVCandidate = false;
344 }
345 else if (mAnchors && (CFArrayGetCount(mAnchors)==0) && (searchLibs().size()==0)) {
346 // caller explicitly provided empty anchors and no keychain list,
347 // and did not explicitly specify the revocation policy;
348 // override global revocation check setting for this evaluation
349 secdebug("evTrust", "Trust::evaluate() has empty anchors and no keychains");
350 allPolicies = NULL; // use only mPolicies
351 isEVCandidate = false;
352 }
353 else if (isEVCandidate || requirePerCert) {
354 // force revocation checking for this evaluation
355 secdebug("evTrust", "Trust::evaluate() forcing OCSP/CRL revocation check");
356 allPolicies = forceRevocationPolicies(numRevocationAdded,
357 context.allocator, requirePerCert);
358 }
359 else if(!(revocationPolicySpecified(mPolicies))) {
360 // none specified in mPolicies; try preferences
361 allPolicies = addPreferenceRevocationPolicies(numRevocationAdded,
362 context.allocator);
363 }
364 if (allPolicies == NULL) {
365 // use mPolicies; no revocation checking will be performed
366 secdebug("evTrust", "Trust::evaluate() will not perform revocation check");
367 CFIndex numPolicies = CFArrayGetCount(mPolicies);
368 CFAllocatorRef allocator = CFGetAllocator(mPolicies);
369 allPolicies = CFArrayCreateMutableCopy(allocator, numPolicies, mPolicies);
370 }
371 orderRevocationPolicies(allPolicies);
372 CFToVector<CssmField, SecPolicyRef, cfField> policies(allPolicies);
373 #if 0
374 // error exit here if empty policies are not supported
375 if (policies.empty())
376 MacOSError::throwMe(CSSMERR_TP_INVALID_POLICY_IDENTIFIERS);
377 #endif
378 context.setPolicies(policies, policies);
379
380 // anchor certificates (if caller provides them, or if cert requires EV)
381 CFCopyRef<CFArrayRef> anchors(mAllowedAnchors);
382 CFToVector<CssmData, SecCertificateRef, cfCertificateData> roots(anchors);
383 if (!anchors) {
384 // no anchor certificates were provided;
385 // built-in anchors will be trusted unless explicitly disabled.
386 mUsingTrustSettings = (mAnchorPolicy < useAnchorsOnly);
387 secdebug("userTrust", "Trust::evaluate() %s",
388 (mUsingTrustSettings) ? "using UserTrust" : "has no trusted anchors!");
389 }
390 else {
391 // anchor certificates were provided;
392 // built-in anchors will NOT also be trusted unless explicitly enabled.
393 mUsingTrustSettings = (mAnchorPolicy == useAnchorsAndBuiltIns);
394 secdebug("userTrust", "Trust::evaluate() using %s %s anchors",
395 (mUsingTrustSettings) ? "UserTrust AND" : "only",
396 (isEVCandidate) ? "EV" : "caller");
397 context.anchors(roots, roots);
398 }
399
400 // dlDbList (keychain list)
401 vector<CSSM_DL_DB_HANDLE> dlDbList;
402 {
403 StLock<Mutex> _(SecTrustKeychainsGetMutex());
404 StorageManager::KeychainList& list = searchLibs();
405 for (StorageManager::KeychainList::const_iterator it = list.begin();
406 it != list.end(); it++)
407 {
408 try
409 {
410 // For the purpose of looking up intermediate certificates to establish trust,
411 // do not include the network-based LDAP or DotMac pseudo-keychains. (The only
412 // time the network should be consulted for certificates is if there is an AIA
413 // extension with a specific URL, which will be handled by the TP code.)
414 CSSM_DL_DB_HANDLE dldbHandle = (*it)->database()->handle();
415 if (dldbHandle.DLHandle) {
416 CSSM_GUID guid = {};
417 CSSM_RETURN crtn = CSSM_GetModuleGUIDFromHandle(dldbHandle.DLHandle, &guid);
418 if (crtn == CSSM_OK) {
419 if ((memcmp(&guid, &gGuidAppleLDAPDL, sizeof(CSSM_GUID))==0) ||
420 (memcmp(&guid, &gGuidAppleDotMacDL, sizeof(CSSM_GUID))==0)) {
421 continue; // don't add to dlDbList
422 }
423 }
424 }
425 // This DB is OK to search for intermediate certificates.
426 dlDbList.push_back(dldbHandle);
427 }
428 catch (...)
429 {
430 }
431 }
432 if(mUsingTrustSettings) {
433 /* Append system anchors for use with Trust Settings */
434 try {
435 CSSM_DL_DB_HANDLE rootStoreHandle = trustKeychains().rootStoreHandle();
436 if (rootStoreHandle.DBHandle)
437 dlDbList.push_back(rootStoreHandle);
438 actionDataP->ActionFlags |= CSSM_TP_ACTION_TRUST_SETTINGS;
439 }
440 catch (...) {
441 // no root store or system keychain; don't use trust settings but continue
442 mUsingTrustSettings = false;
443 }
444 try {
445 CSSM_DL_DB_HANDLE systemKcHandle = trustKeychains().systemKcHandle();
446 if (systemKcHandle.DBHandle)
447 dlDbList.push_back(systemKcHandle);
448 }
449 catch(...) {
450 /* Oh well, at least we got the root store DB */
451 }
452 }
453 context.setDlDbList((uint32)dlDbList.size(), &dlDbList[0]);
454 }
455
456 // verification time
457 char timeString[15];
458 if (mVerifyTime) {
459 CssmUniformDate(static_cast<CFDateRef>(mVerifyTime)).convertTo(
460 timeString, sizeof(timeString));
461 context.time(timeString);
462 }
463
464 // to avoid keychain open/close thrashing, hold a copy of the search list
465 StorageManager::KeychainList *holdSearchList = NULL;
466 if (searchLibs().size() > 0) {
467 holdSearchList = new StorageManager::KeychainList;
468 globals().storageManager.getSearchList(*holdSearchList);
469 }
470
471 // Go TP!
472 try {
473 mTP->certGroupVerify(subjectCertGroup, context, &mTpResult);
474 mTpReturn = errSecSuccess;
475 } catch (CommonError &err) {
476 mTpReturn = err.osStatus();
477 secdebug("trusteval", "certGroupVerify exception: %d", (int)mTpReturn);
478 }
479 mResult = diagnoseOutcome();
480
481 // see if we can use the evidence
482 if (mTpResult.count() > 0
483 && mTpResult[0].form() == CSSM_EVIDENCE_FORM_APPLE_HEADER
484 && mTpResult[0].as<CSSM_TP_APPLE_EVIDENCE_HEADER>()->Version == CSSM_TP_APPLE_EVIDENCE_VERSION
485 && mTpResult.count() == 3
486 && mTpResult[1].form() == CSSM_EVIDENCE_FORM_APPLE_CERTGROUP
487 && mTpResult[2].form() == CSSM_EVIDENCE_FORM_APPLE_CERT_INFO) {
488 evaluateUserTrust(*mTpResult[1].as<CertGroup>(),
489 mTpResult[2].as<CSSM_TP_APPLE_EVIDENCE_INFO>(), anchors);
490 } else {
491 // unexpected evidence information. Can't use it
492 secdebug("trusteval", "unexpected evidence ignored");
493 }
494
495 /* do post-processing for the evaluated certificate chain */
496 CFArrayRef fullChain = makeCFArray(convert, mCertChain);
497 CFDictionaryRef etResult = extendedTrustResults(fullChain, mResult, mTpReturn, isEVCandidate);
498 mExtendedResult = etResult; // assignment to CFRef type is an implicit retain
499 if (etResult) {
500 CFRelease(etResult);
501 }
502 if (fullChain) {
503 CFRelease(fullChain);
504 }
505
506 if (allPolicies) {
507 /* clean up revocation policies we created implicitly */
508 if(numRevocationAdded) {
509 freeAddedRevocationPolicyData(allPolicies, numRevocationAdded, context.allocator);
510 }
511 CFRelease(allPolicies);
512 }
513
514 if (holdSearchList) {
515 delete holdSearchList;
516 holdSearchList = NULL;
517 }
518 } // end evaluation block with mutex; releases all temporary allocations in this scope
519
520
521 if (isEVCandidate && mResult == kSecTrustResultRecoverableTrustFailure &&
522 isRevocationServerMetaError(mTpReturn)) {
523 // re-do the evaluation, this time disabling EV
524 evaluate(true);
525 }
526 }
527
528 // CSSM_RETURN values that map to kSecTrustResultRecoverableTrustFailure.
529 static const CSSM_RETURN recoverableErrors[] =
530 {
531 CSSMERR_TP_INVALID_ANCHOR_CERT,
532 CSSMERR_TP_NOT_TRUSTED,
533 CSSMERR_TP_VERIFICATION_FAILURE,
534 CSSMERR_TP_VERIFY_ACTION_FAILED,
535 CSSMERR_TP_INVALID_REQUEST_INPUTS,
536 CSSMERR_TP_CERT_EXPIRED,
537 CSSMERR_TP_CERT_NOT_VALID_YET,
538 CSSMERR_TP_CERTIFICATE_CANT_OPERATE,
539 CSSMERR_TP_INVALID_CERT_AUTHORITY,
540 CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK,
541 CSSMERR_APPLETP_HOSTNAME_MISMATCH,
542 CSSMERR_TP_VERIFY_ACTION_FAILED,
543 CSSMERR_APPLETP_SMIME_EMAIL_ADDRS_NOT_FOUND,
544 CSSMERR_APPLETP_SMIME_NO_EMAIL_ADDRS,
545 CSSMERR_APPLETP_SMIME_BAD_EXT_KEY_USE,
546 CSSMERR_APPLETP_CS_BAD_CERT_CHAIN_LENGTH,
547 CSSMERR_APPLETP_CS_NO_BASIC_CONSTRAINTS,
548 CSSMERR_APPLETP_CS_BAD_PATH_LENGTH,
549 CSSMERR_APPLETP_CS_NO_EXTENDED_KEY_USAGE,
550 CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE,
551 CSSMERR_APPLETP_CODE_SIGN_DEVELOPMENT,
552 CSSMERR_APPLETP_RS_BAD_CERT_CHAIN_LENGTH,
553 CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN,
554 CSSMERR_APPLETP_CRL_NOT_FOUND,
555 CSSMERR_APPLETP_CRL_SERVER_DOWN,
556 CSSMERR_APPLETP_CRL_NOT_VALID_YET,
557 CSSMERR_APPLETP_OCSP_UNAVAILABLE,
558 CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK,
559 CSSMERR_APPLETP_NETWORK_FAILURE,
560 CSSMERR_APPLETP_OCSP_RESP_TRY_LATER,
561 CSSMERR_APPLETP_IDENTIFIER_MISSING,
562 };
563 #define NUM_RECOVERABLE_ERRORS (sizeof(recoverableErrors) / sizeof(CSSM_RETURN))
564
565 //
566 // Classify the TP outcome in terms of a SecTrustResultType
567 //
568 SecTrustResultType Trust::diagnoseOutcome()
569 {
570 StLock<Mutex>_(mMutex);
571
572 uint32 chainLength = 0;
573 if (mTpResult.count() == 3 &&
574 mTpResult[1].form() == CSSM_EVIDENCE_FORM_APPLE_CERTGROUP &&
575 mTpResult[2].form() == CSSM_EVIDENCE_FORM_APPLE_CERT_INFO)
576 {
577 const CertGroup &chain = *mTpResult[1].as<CertGroup>();
578 chainLength = chain.count();
579 }
580
581 switch (mTpReturn) {
582 case errSecSuccess: // peachy
583 if (mUsingTrustSettings)
584 {
585 if (chainLength)
586 {
587 const CSSM_TP_APPLE_EVIDENCE_INFO *infoList = mTpResult[2].as<CSSM_TP_APPLE_EVIDENCE_INFO>();
588 const TPEvidenceInfo &info = TPEvidenceInfo::overlay(infoList[chainLength-1]);
589 const CSSM_TP_APPLE_CERT_STATUS resultCertStatus = info.status();
590 bool hasUserDomainTrust = ((resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_TRUST) &&
591 (resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_USER));
592 bool hasAdminDomainTrust = ((resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_TRUST) &&
593 (resultCertStatus & CSSM_CERT_STATUS_TRUST_SETTINGS_FOUND_ADMIN));
594 if (hasUserDomainTrust || hasAdminDomainTrust)
595 {
596 return kSecTrustResultProceed; // explicitly allowed
597 }
598 }
599 }
600 return kSecTrustResultUnspecified; // cert evaluates OK
601 case CSSMERR_TP_INVALID_CERTIFICATE: // bad certificate
602 return kSecTrustResultFatalTrustFailure;
603 case CSSMERR_APPLETP_TRUST_SETTING_DENY: // authoritative denial
604 return kSecTrustResultDeny;
605 default:
606 break;
607 }
608
609 // a known list of returns maps to kSecTrustResultRecoverableTrustFailure
610 const CSSM_RETURN *errp=recoverableErrors;
611 for(unsigned dex=0; dex<NUM_RECOVERABLE_ERRORS; dex++, errp++) {
612 if(*errp == mTpReturn) {
613 return kSecTrustResultRecoverableTrustFailure;
614 }
615 }
616 return kSecTrustResultOtherError; // unknown
617 }
618
619
620 //
621 // Assuming a good evidence chain, check user trust
622 // settings and set mResult accordingly.
623 //
624 void Trust::evaluateUserTrust(const CertGroup &chain,
625 const CSSM_TP_APPLE_EVIDENCE_INFO *infoList, CFCopyRef<CFArrayRef> anchors)
626 {
627 StLock<Mutex>_(mMutex);
628 // extract cert chain as Certificate objects
629 mCertChain.resize(chain.count());
630 for (uint32 n = 0; n < mCertChain.size(); n++) {
631 const TPEvidenceInfo &info = TPEvidenceInfo::overlay(infoList[n]);
632 if (info.recordId()) {
633 Keychain keychain = keychainByDLDb(info.DlDbHandle);
634 DbUniqueRecord uniqueId(keychain->database()->newDbUniqueRecord());
635 secdebug("trusteval", "evidence %lu from keychain \"%s\"", (unsigned long)n, keychain->name());
636 *static_cast<CSSM_DB_UNIQUE_RECORD_PTR *>(uniqueId) = info.UniqueRecord;
637 uniqueId->activate(); // transfers ownership
638 Item ii = keychain->item(CSSM_DL_DB_RECORD_X509_CERTIFICATE, uniqueId);
639 Certificate* cert = dynamic_cast<Certificate*>(ii.get());
640 if (cert == NULL) {
641 CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER);
642 }
643 mCertChain[n] = cert;
644 } else if (info.status(CSSM_CERT_STATUS_IS_IN_INPUT_CERTS)) {
645 secdebug("trusteval", "evidence %lu from input cert %lu", (unsigned long)n, (unsigned long)info.index());
646 assert(info.index() < uint32(CFArrayGetCount(mCerts)));
647 SecCertificateRef cert = SecCertificateRef(CFArrayGetValueAtIndex(mCerts,
648 info.index()));
649 mCertChain[n] = Certificate::required(cert);
650 } else if (info.status(CSSM_CERT_STATUS_IS_IN_ANCHORS)) {
651 secdebug("trusteval", "evidence %lu from anchor cert %lu", (unsigned long)n, (unsigned long)info.index());
652 assert(info.index() < uint32(CFArrayGetCount(anchors)));
653 SecCertificateRef cert = SecCertificateRef(CFArrayGetValueAtIndex(anchors,
654 info.index()));
655 mCertChain[n] = Certificate::required(cert);
656 } else {
657 // unknown source; make a new Certificate for it
658 secdebug("trusteval", "evidence %lu from unknown source", (unsigned long)n);
659 mCertChain[n] =
660 new Certificate(chain.blobCerts()[n],
661 CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_BER);
662 }
663 }
664
665 // now walk the chain, leaf-to-root, checking for user settings
666 TrustStore &store = gStore();
667 SecPointer<Policy> policy = (CFArrayGetCount(mPolicies)) ?
668 Policy::required(SecPolicyRef(CFArrayGetValueAtIndex(mPolicies, 0))) : NULL;
669 for (mResultIndex = 0;
670 mResult == kSecTrustResultUnspecified && mResultIndex < mCertChain.size() && policy;
671 mResultIndex++) {
672 if (!mCertChain[mResultIndex]) {
673 assert(false);
674 continue;
675 }
676 mResult = store.find(mCertChain[mResultIndex], policy, searchLibs());
677 secdebug("trusteval", "trustResult=%d from cert %d", (int)mResult, (int)mResultIndex);
678 }
679 }
680
681
682 //
683 // Release TP evidence information.
684 // This information is severely under-defined by CSSM, so we proceed
685 // as follows:
686 // (a) If the evidence matches an Apple-defined pattern, use specific
687 // knowledge of that format.
688 // (b) Otherwise, assume that the void * are flat blocks of memory.
689 //
690 void Trust::releaseTPEvidence(TPVerifyResult &result, Allocator &allocator)
691 {
692 if (result.count() > 0) { // something to do
693 if (result[0].form() == CSSM_EVIDENCE_FORM_APPLE_HEADER) {
694 // Apple defined evidence form -- use intimate knowledge
695 if (result[0].as<CSSM_TP_APPLE_EVIDENCE_HEADER>()->Version == CSSM_TP_APPLE_EVIDENCE_VERSION
696 && result.count() == 3
697 && result[1].form() == CSSM_EVIDENCE_FORM_APPLE_CERTGROUP
698 && result[2].form() == CSSM_EVIDENCE_FORM_APPLE_CERT_INFO) {
699 // proper format
700 CertGroup& certs = *result[1].as<CertGroup>();
701 CSSM_TP_APPLE_EVIDENCE_INFO *evidence = result[2].as<CSSM_TP_APPLE_EVIDENCE_INFO>();
702 uint32 count = certs.count();
703 allocator.free(result[0].data()); // just a struct
704 certs.destroy(allocator); // certgroup contents
705 allocator.free(result[1].data()); // the CertGroup itself
706 for (uint32 n = 0; n < count; n++)
707 allocator.free(evidence[n].StatusCodes);
708 allocator.free(result[2].data()); // array of (flat) info structs
709 } else {
710 secdebug("trusteval", "unrecognized Apple TP evidence format");
711 // drop it -- better leak than kill
712 }
713 } else {
714 // unknown format -- blindly assume flat blobs
715 secdebug("trusteval", "destroying unknown TP evidence format");
716 for (uint32 n = 0; n < result.count(); n++)
717 {
718 allocator.free(result[n].data());
719 }
720 }
721
722 allocator.free (result.Evidence);
723 }
724 }
725
726
727 //
728 // Clear evaluation results unless state is initial (invalid)
729 //
730 void Trust::clearResults()
731 {
732 StLock<Mutex>_(mMutex);
733 if (mResult != kSecTrustResultInvalid) {
734 releaseTPEvidence(mTpResult, mTP.allocator());
735 mResult = kSecTrustResultInvalid;
736 }
737 }
738
739
740 //
741 // Build evidence information
742 //
743 void Trust::buildEvidence(CFArrayRef &certChain, TPEvidenceInfo * &statusChain)
744 {
745 StLock<Mutex>_(mMutex);
746 if (mResult == kSecTrustResultInvalid)
747 MacOSError::throwMe(errSecTrustNotAvailable);
748 certChain = mEvidenceReturned =
749 makeCFArray(convert, mCertChain);
750 if(mTpResult.count() >= 3) {
751 statusChain = mTpResult[2].as<TPEvidenceInfo>();
752 }
753 else {
754 statusChain = NULL;
755 }
756 }
757
758
759 //
760 // Return extended result dictionary
761 //
762 void Trust::extendedResult(CFDictionaryRef &result)
763 {
764 if (mResult == kSecTrustResultInvalid)
765 MacOSError::throwMe(errSecTrustNotAvailable);
766 if (mExtendedResult)
767 CFRetain(mExtendedResult); // retain before handing out to caller
768 result = mExtendedResult;
769 }
770
771
772 //
773 // Return properties array (a CFDictionaryRef for each certificate in chain)
774 //
775 CFArrayRef Trust::properties()
776 {
777 // Builds and returns an array which the caller must release.
778 StLock<Mutex>_(mMutex);
779 CFMutableArrayRef properties = CFArrayCreateMutable(NULL, 0,
780 &kCFTypeArrayCallBacks);
781 if (mResult == kSecTrustResultInvalid) // chain not built or evaluated
782 return properties;
783
784 // Walk the chain from leaf to anchor, building properties dictionaries
785 for (uint32 idx=0; idx < mCertChain.size(); idx++) {
786 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0,
787 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
788 if (dict) {
789 CFStringRef title = NULL;
790 mCertChain[idx]->inferLabel(false, &title);
791 if (title) {
792 CFDictionarySetValue(dict, (const void *)kSecPropertyTypeTitle, (const void *)title);
793 CFRelease(title);
794 }
795 if (idx == 0 && mTpReturn != errSecSuccess) {
796 CFStringRef error = SecCopyErrorMessageString(mTpReturn, NULL);
797 if (error) {
798 CFDictionarySetValue(dict, (const void *)kSecPropertyTypeError, (const void *)error);
799 CFRelease(error);
800 }
801 }
802 CFArrayAppendValue(properties, (const void *)dict);
803 CFRelease(dict);
804 }
805 }
806
807 return properties;
808 }
809
810 //
811 // Return dictionary of evaluation results
812 //
813 CFDictionaryRef Trust::results()
814 {
815 // Builds and returns a dictionary which the caller must release.
816 StLock<Mutex>_(mMutex);
817 CFMutableDictionaryRef results = CFDictionaryCreateMutable(NULL, 0,
818 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
819
820 // kSecTrustResultValue
821 CFNumberRef numValue = CFNumberCreate(NULL, kCFNumberSInt32Type, &mResult);
822 if (numValue) {
823 CFDictionarySetValue(results, (const void *)kSecTrustResultValue, (const void *)numValue);
824 CFRelease(numValue);
825 }
826 if (mResult == kSecTrustResultInvalid || !mExtendedResult)
827 return results; // we have nothing more to add
828
829 // kSecTrustEvaluationDate
830 CFTypeRef evaluationDate;
831 if (CFDictionaryGetValueIfPresent(mExtendedResult, kSecTrustEvaluationDate, &evaluationDate))
832 CFDictionarySetValue(results, (const void *)kSecTrustEvaluationDate, (const void *)evaluationDate);
833
834 // kSecTrustExtendedValidation, kSecTrustOrganizationName
835 CFTypeRef organizationName;
836 if (CFDictionaryGetValueIfPresent(mExtendedResult, kSecEVOrganizationName, &organizationName)) {
837 CFDictionarySetValue(results, (const void *)kSecTrustOrganizationName, (const void *)organizationName);
838 CFDictionarySetValue(results, (const void *)kSecTrustExtendedValidation, (const void *)kCFBooleanTrue);
839 }
840
841 // kSecTrustRevocationChecked, kSecTrustRevocationValidUntilDate
842 CFTypeRef expirationDate;
843 if (CFDictionaryGetValueIfPresent(mExtendedResult, kSecTrustExpirationDate, &expirationDate)) {
844 CFDictionarySetValue(results, (const void *)kSecTrustRevocationValidUntilDate, (const void *)expirationDate);
845 CFDictionarySetValue(results, (const void *)kSecTrustRevocationChecked, (const void *)kCFBooleanTrue);
846 }
847
848 return results;
849 }
850
851
852
853 //* ===========================================================================
854 //* We need a way to compare two CSSM_DL_DB_HANDLEs WITHOUT using a operator
855 //* overload
856 //* ===========================================================================
857 static
858 bool Compare_CSSM_DL_DB_HANDLE(const CSSM_DL_DB_HANDLE &h1, const CSSM_DL_DB_HANDLE &h2)
859 {
860 return (h1.DLHandle == h2.DLHandle && h1.DBHandle == h2.DBHandle);
861 }
862
863
864
865 //
866 // Given a DL_DB_HANDLE, locate the Keychain object (from the search list)
867 //
868 Keychain Trust::keychainByDLDb(const CSSM_DL_DB_HANDLE &handle)
869 {
870 StLock<Mutex>_(mMutex);
871 StorageManager::KeychainList& list = searchLibs();
872 for (StorageManager::KeychainList::const_iterator it = list.begin();
873 it != list.end(); it++)
874 {
875 try
876 {
877
878 if (Compare_CSSM_DL_DB_HANDLE((*it)->database()->handle(), handle))
879 return *it;
880 }
881 catch (...)
882 {
883 }
884 }
885 if(mUsingTrustSettings) {
886 try {
887 if(Compare_CSSM_DL_DB_HANDLE(trustKeychains().rootStoreHandle(), handle)) {
888 return trustKeychains().rootStore();
889 }
890 if(Compare_CSSM_DL_DB_HANDLE(trustKeychains().systemKcHandle(), handle)) {
891 return trustKeychains().systemKc();
892 }
893 }
894 catch(...) {
895 /* one of those is missing; proceed */
896 }
897 }
898
899 // could not find in search list - internal error
900
901 // we now throw an error here rather than assert and silently fail. That way our application won't crash...
902 MacOSError::throwMe(errSecInternal);
903 }