2 * Copyright (c) 2002-2010,2012 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
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>
40 using namespace Security
;
41 using namespace KeychainCore
;
44 // Translate CFDataRef to CssmData. The output shares the input's buffer.
46 static inline CssmData
cfData(CFDataRef data
)
48 return CssmData(const_cast<UInt8
*>(CFDataGetBytePtr(data
)),
49 CFDataGetLength(data
));
53 // Convert a SecPointer to a CF object.
55 static SecCertificateRef
56 convert(const SecPointer
<Certificate
> &certificate
)
62 // For now, we use a global TrustStore
64 ModuleNexus
<TrustStore
> Trust::gStore
;
66 #pragma mark -- TrustKeychains --
68 static const CSSM_DL_DB_HANDLE nullCSSMDLDBHandle
= {0,};
70 // TrustKeychains maintains a global reference to standard system keychains,
71 // to avoid having them be opened anew for each Trust instance.
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
; }
87 CSSM_DL_DB_HANDLE mRootStoreHandle
;
92 // Singleton maintaining open references to standard system keychains,
93 // to avoid having them be opened anew every time SecTrust is used.
96 static ModuleNexus
<TrustKeychains
> trustKeychains
;
97 static ModuleNexus
<RecursiveMutex
> trustKeychainsMutex
;
99 extern "C" bool GetServerMode();
101 TrustKeychains::TrustKeychains() :
102 mRootStoreHandle(nullCSSMDLDBHandle
),
103 mSystem(globals().storageManager
.make(ADMIN_CERT_STORE_PATH
, false))
105 if (GetServerMode()) // in server mode? Don't make a keychain for the root store
107 mRootStoreDL
= new DL(gGuidAppleFileDL
),
108 mRootStoreDb
= new Db(*mRootStoreDL
, SYSTEM_ROOT_STORE_PATH
),
109 (*mRootStoreDb
)->activate();
110 mRootStoreHandle
= (*mRootStoreDb
)->handle();
114 mRootStore
= new Keychain(globals().storageManager
.make(SYSTEM_ROOT_STORE_PATH
, false));
115 (*mRootStore
)->database()->activate();
116 mRootStoreHandle
= (*mRootStore
)->database()->handle();
120 RecursiveMutex
& SecTrustKeychainsGetMutex()
122 return trustKeychainsMutex();
125 #pragma mark -- Trust --
127 // Construct a Trust object with suitable defaults.
128 // Use setters for additional arguments before calling evaluate().
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
)
137 mPolicies
.take(CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
));
143 // Clean up a Trust object
157 // Get searchLibs (a vector of Keychain objects);
158 // normally initialized to default search list
160 StorageManager::KeychainList
& Trust::searchLibs(bool init
)
163 mSearchLibs
= new StorageManager::KeychainList
;
165 globals().storageManager
.getSearchList(*mSearchLibs
);
173 // Set searchLibs to provided vector of Keychain objects
175 void Trust::searchLibs(StorageManager::KeychainList
&libs
)
177 searchLibs(false) = libs
;
178 mSearchLibsSet
= true;
183 // Retrieve the last TP evaluation result, if any
185 CSSM_TP_VERIFY_CONTEXT_RESULT_PTR
Trust::cssmResult()
187 if (mResult
== kSecTrustResultInvalid
)
188 MacOSError::throwMe(errSecTrustNotAvailable
);
193 // SecCertificateRef -> CssmData
195 CssmData
cfCertificateData(SecCertificateRef certificate
)
197 return Certificate::required(certificate
)->data();
200 // SecPolicyRef -> CssmField (CFDataRef/NULL or oid/value of a SecPolicy)
202 CssmField
cfField(SecPolicyRef item
)
204 SecPointer
<Policy
> policy
= Policy::required(SecPolicyRef(item
));
205 return CssmField(policy
->oid(), policy
->value());
208 // SecKeychain -> CssmDlDbHandle
211 CSSM_DL_DB_HANDLE
cfKeychain(SecKeychainRef ref
)
213 Keychain keychain
= KeychainImpl::required(ref
);
214 return keychain
->database()->handle();
219 void showCertSKID(const void *value
, void *context
);
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.
230 void Trust::evaluate(bool disableEV
)
232 bool isEVCandidate
=false;
233 // begin evaluation block with stack-based mutex
235 StLock
<Mutex
>_(mMutex
);
236 // if we have evaluated before, release prior result
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;
244 secdebug("evTrust", "Trust::evaluate() certificate is EV candidate");
245 filteredCerts
= potentialEVChainWithCertificates(mCerts
);
246 mCerts
= filteredCerts
;
248 secdebug("evTrust", "Trust::evaluate() performing standard evaluation");
250 filteredCerts
= CFArrayCreateMutableCopy(NULL
, 0, mCerts
);
253 allowedAnchors
= CFArrayCreateMutableCopy(NULL
, 0, mAnchors
);
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
;
262 CFRelease(allowedAnchors
);
264 CFRelease(filteredCerts
);
268 secdebug("trusteval", "Trust::evaluate: anchors: %ld", CFArrayGetCount(mAllowedAnchors
));
270 CFArrayApplyFunction(mAllowedAnchors
, CFRangeMake(0, CFArrayGetCount(mAllowedAnchors
)), showCertSKID
, NULL
);
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;
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
;
287 // build a TP_VERIFY_CONTEXT, a veritable nightmare of a data structure
288 TPBuildVerifyContext
context(mAction
);
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.
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
;
300 context
.actionData() = cfData(mActionData
);
301 actionDataP
= (CSSM_APPLE_TP_ACTION_DATA
*)context
.actionData().data();
304 context
.actionData() = localActionCData
;
308 // always check trust settings if caller did not provide explicit trust anchors
309 actionDataP
->ActionFlags
|= CSSM_TP_ACTION_TRUST_SETTINGS
;
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
;
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
);
324 * Policies (one at least, please).
325 * For revocation policies, see if any have been explicitly specified...
327 CFMutableArrayRef allPolicies
= NULL
;
328 uint32 numRevocationAdded
= 0;
329 bool requirePerCert
= (actionDataP
->ActionFlags
& CSSM_TP_ACTION_REQUIRE_REV_PER_CERT
);
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.
337 allPolicies
= convertRevocationPolicy(numRevocationAdded
, context
.allocator
);
339 // caller has explicitly set the revocation policy they want to use
340 secdebug("evTrust", "Trust::evaluate() using explicit revocation policy (%d)",
342 if (numRevocationAdded
== 0)
343 isEVCandidate
= false;
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;
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
);
359 else if(!(revocationPolicySpecified(mPolicies
))) {
360 // none specified in mPolicies; try preferences
361 allPolicies
= addPreferenceRevocationPolicies(numRevocationAdded
,
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
);
371 orderRevocationPolicies(allPolicies
);
372 CFToVector
<CssmField
, SecPolicyRef
, cfField
> policies(allPolicies
);
374 // error exit here if empty policies are not supported
375 if (policies
.empty())
376 MacOSError::throwMe(CSSMERR_TP_INVALID_POLICY_IDENTIFIERS
);
378 context
.setPolicies(policies
, policies
);
380 // anchor certificates (if caller provides them, or if cert requires EV)
381 CFCopyRef
<CFArrayRef
> anchors(mAllowedAnchors
);
382 CFToVector
<CssmData
, SecCertificateRef
, cfCertificateData
> roots(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!");
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
);
400 // dlDbList (keychain list)
401 vector
<CSSM_DL_DB_HANDLE
> dlDbList
;
403 StLock
<Mutex
> _(SecTrustKeychainsGetMutex());
404 StorageManager::KeychainList
& list
= searchLibs();
405 for (StorageManager::KeychainList::const_iterator it
= list
.begin();
406 it
!= list
.end(); it
++)
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
) {
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
425 // This DB is OK to search for intermediate certificates.
426 dlDbList
.push_back(dldbHandle
);
432 if(mUsingTrustSettings
) {
433 /* Append system anchors for use with Trust Settings */
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
;
441 // no root store or system keychain; don't use trust settings but continue
442 mUsingTrustSettings
= false;
445 CSSM_DL_DB_HANDLE systemKcHandle
= trustKeychains().systemKcHandle();
446 if (systemKcHandle
.DBHandle
)
447 dlDbList
.push_back(systemKcHandle
);
450 /* Oh well, at least we got the root store DB */
453 context
.setDlDbList((uint32
)dlDbList
.size(), &dlDbList
[0]);
459 CssmUniformDate(static_cast<CFDateRef
>(mVerifyTime
)).convertTo(
460 timeString
, sizeof(timeString
));
461 context
.time(timeString
);
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
);
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
);
479 mResult
= diagnoseOutcome();
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
);
491 // unexpected evidence information. Can't use it
492 secdebug("trusteval", "unexpected evidence ignored");
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
503 CFRelease(fullChain
);
507 /* clean up revocation policies we created implicitly */
508 if(numRevocationAdded
) {
509 freeAddedRevocationPolicyData(allPolicies
, numRevocationAdded
, context
.allocator
);
511 CFRelease(allPolicies
);
514 if (holdSearchList
) {
515 delete holdSearchList
;
516 holdSearchList
= NULL
;
518 } // end evaluation block with mutex; releases all temporary allocations in this scope
521 if (isEVCandidate
&& mResult
== kSecTrustResultRecoverableTrustFailure
&&
522 isRevocationServerMetaError(mTpReturn
)) {
523 // re-do the evaluation, this time disabling EV
528 // CSSM_RETURN values that map to kSecTrustResultRecoverableTrustFailure.
529 static const CSSM_RETURN recoverableErrors
[] =
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
,
563 #define NUM_RECOVERABLE_ERRORS (sizeof(recoverableErrors) / sizeof(CSSM_RETURN))
566 // Classify the TP outcome in terms of a SecTrustResultType
568 SecTrustResultType
Trust::diagnoseOutcome()
570 StLock
<Mutex
>_(mMutex
);
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
)
577 const CertGroup
&chain
= *mTpResult
[1].as
<CertGroup
>();
578 chainLength
= chain
.count();
582 case errSecSuccess
: // peachy
583 if (mUsingTrustSettings
)
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
)
596 return kSecTrustResultProceed
; // explicitly allowed
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
;
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
;
616 return kSecTrustResultOtherError
; // unknown
621 // Assuming a good evidence chain, check user trust
622 // settings and set mResult accordingly.
624 void Trust::evaluateUserTrust(const CertGroup
&chain
,
625 const CSSM_TP_APPLE_EVIDENCE_INFO
*infoList
, CFCopyRef
<CFArrayRef
> anchors
)
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());
641 CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER
);
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
,
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
,
655 mCertChain
[n
] = Certificate::required(cert
);
657 // unknown source; make a new Certificate for it
658 secdebug("trusteval", "evidence %lu from unknown source", (unsigned long)n
);
660 new Certificate(chain
.blobCerts()[n
],
661 CSSM_CERT_X_509v3
, CSSM_CERT_ENCODING_BER
);
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
;
672 if (!mCertChain
[mResultIndex
]) {
676 mResult
= store
.find(mCertChain
[mResultIndex
], policy
, searchLibs());
677 secdebug("trusteval", "trustResult=%d from cert %d", (int)mResult
, (int)mResultIndex
);
683 // Release TP evidence information.
684 // This information is severely under-defined by CSSM, so we proceed
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.
690 void Trust::releaseTPEvidence(TPVerifyResult
&result
, Allocator
&allocator
)
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
) {
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
710 secdebug("trusteval", "unrecognized Apple TP evidence format");
711 // drop it -- better leak than kill
714 // unknown format -- blindly assume flat blobs
715 secdebug("trusteval", "destroying unknown TP evidence format");
716 for (uint32 n
= 0; n
< result
.count(); n
++)
718 allocator
.free(result
[n
].data());
722 allocator
.free (result
.Evidence
);
728 // Clear evaluation results unless state is initial (invalid)
730 void Trust::clearResults()
732 StLock
<Mutex
>_(mMutex
);
733 if (mResult
!= kSecTrustResultInvalid
) {
734 releaseTPEvidence(mTpResult
, mTP
.allocator());
735 mResult
= kSecTrustResultInvalid
;
741 // Build evidence information
743 void Trust::buildEvidence(CFArrayRef
&certChain
, TPEvidenceInfo
* &statusChain
)
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
>();
760 // Return extended result dictionary
762 void Trust::extendedResult(CFDictionaryRef
&result
)
764 if (mResult
== kSecTrustResultInvalid
)
765 MacOSError::throwMe(errSecTrustNotAvailable
);
767 CFRetain(mExtendedResult
); // retain before handing out to caller
768 result
= mExtendedResult
;
773 // Return properties array (a CFDictionaryRef for each certificate in chain)
775 CFArrayRef
Trust::properties()
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
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
);
789 CFStringRef title
= NULL
;
790 mCertChain
[idx
]->inferLabel(false, &title
);
792 CFDictionarySetValue(dict
, (const void *)kSecPropertyTypeTitle
, (const void *)title
);
795 if (idx
== 0 && mTpReturn
!= errSecSuccess
) {
796 CFStringRef error
= SecCopyErrorMessageString(mTpReturn
, NULL
);
798 CFDictionarySetValue(dict
, (const void *)kSecPropertyTypeError
, (const void *)error
);
802 CFArrayAppendValue(properties
, (const void *)dict
);
811 // Return dictionary of evaluation results
813 CFDictionaryRef
Trust::results()
815 // Builds and returns a dictionary which the caller must release.
816 StLock
<Mutex
>_(mMutex
);
817 CFMutableDictionaryRef results
= CFDictionaryCreateMutable(NULL
, 0,
818 &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
820 // kSecTrustResultValue
821 CFNumberRef numValue
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &mResult
);
823 CFDictionarySetValue(results
, (const void *)kSecTrustResultValue
, (const void *)numValue
);
826 if (mResult
== kSecTrustResultInvalid
|| !mExtendedResult
)
827 return results
; // we have nothing more to add
829 // kSecTrustEvaluationDate
830 CFTypeRef evaluationDate
;
831 if (CFDictionaryGetValueIfPresent(mExtendedResult
, kSecTrustEvaluationDate
, &evaluationDate
))
832 CFDictionarySetValue(results
, (const void *)kSecTrustEvaluationDate
, (const void *)evaluationDate
);
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
);
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
);
853 //* ===========================================================================
854 //* We need a way to compare two CSSM_DL_DB_HANDLEs WITHOUT using a operator
856 //* ===========================================================================
858 bool Compare_CSSM_DL_DB_HANDLE(const CSSM_DL_DB_HANDLE
&h1
, const CSSM_DL_DB_HANDLE
&h2
)
860 return (h1
.DLHandle
== h2
.DLHandle
&& h1
.DBHandle
== h2
.DBHandle
);
866 // Given a DL_DB_HANDLE, locate the Keychain object (from the search list)
868 Keychain
Trust::keychainByDLDb(const CSSM_DL_DB_HANDLE
&handle
)
870 StLock
<Mutex
>_(mMutex
);
871 StorageManager::KeychainList
& list
= searchLibs();
872 for (StorageManager::KeychainList::const_iterator it
= list
.begin();
873 it
!= list
.end(); it
++)
878 if (Compare_CSSM_DL_DB_HANDLE((*it
)->database()->handle(), handle
))
885 if(mUsingTrustSettings
) {
887 if(Compare_CSSM_DL_DB_HANDLE(trustKeychains().rootStoreHandle(), handle
)) {
888 return trustKeychains().rootStore();
890 if(Compare_CSSM_DL_DB_HANDLE(trustKeychains().systemKcHandle(), handle
)) {
891 return trustKeychains().systemKc();
895 /* one of those is missing; proceed */
899 // could not find in search list - internal error
901 // we now throw an error here rather than assert and silently fail. That way our application won't crash...
902 MacOSError::throwMe(errSecInternal
);