2 * Copyright (c) 2005,2011-2015 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@
25 * TrustSettings.h - class to manage cert trust settings.
29 #include "TrustSettings.h"
30 #include "TrustSettingsSchema.h"
31 #include "SecTrustSettings.h"
32 #include "TrustSettingsUtils.h"
33 #include "TrustKeychains.h"
34 #include "Certificate.h"
35 #include "cssmdatetime.h"
36 #include <Security/SecBase.h>
37 #include "SecTrustedApplicationPriv.h"
38 #include <security_utilities/errors.h>
39 #include <security_utilities/debugging.h>
40 #include <security_utilities/logging.h>
41 #include <security_utilities/cfutilities.h>
42 #include <security_utilities/alloc.h>
43 #include <Security/Authorization.h>
44 #include <Security/cssmapplePriv.h>
45 #include <Security/oidscert.h>
46 #include <Security/SecCertificatePriv.h>
47 #include <Security/SecPolicyPriv.h>
48 #include <security_keychain/KCCursor.h>
49 #include <security_ocspd/ocspdClient.h>
50 #include <CoreFoundation/CoreFoundation.h>
52 #include <dispatch/dispatch.h>
57 #define trustSettingsDbg(args...) syslog(LOG_ERR, ## args)
58 #define trustSettingsEvalDbg(args...) syslog(LOG_ERR, ## args)
60 #define trustSettingsDbg(args...) secinfo("trustSettings", ## args)
61 #define trustSettingsEvalDbg(args...) secinfo("trustSettingsEval", ## args)
65 * Common error return for "malformed TrustSettings record"
67 #define errSecInvalidTrustedRootRecord errSecInvalidTrustSettings
69 using namespace KeychainCore
;
71 #pragma mark --- Static functions ---
74 * Comparator atoms to determine if an app's specified usage
75 * matches an individual trust setting. Each returns true on a match, false
76 * if the trust setting does not match the app's spec.
80 * -- the app has specified a field, and the cert has a spec for that
81 * field, and the two specs do not match;
85 * -- the cert has a spec for the field and the app hasn't specified the field
87 static bool tsCheckPolicy(
88 const CSSM_OID
*appPolicy
,
91 if(certPolicy
!= NULL
) {
92 if(appPolicy
== NULL
) {
93 trustSettingsEvalDbg("tsCheckPolicy: certPolicy, !appPolicy");
96 unsigned cLen
= (unsigned)CFDataGetLength(certPolicy
);
97 const UInt8
*cData
= CFDataGetBytePtr(certPolicy
);
98 if((cLen
!= appPolicy
->Length
) || memcmp(appPolicy
->Data
, cData
, cLen
)) {
99 trustSettingsEvalDbg("tsCheckPolicy: policy mismatch");
107 * This one's slightly different: the match is for *this* app, not one
108 * specified by the app.
110 static bool tsCheckApp(
113 if(certApp
!= NULL
) {
114 SecTrustedApplicationRef appRef
;
116 ortn
= SecTrustedApplicationCreateWithExternalRepresentation(certApp
, &appRef
);
118 trustSettingsDbg("tsCheckApp: bad trustedApp data");
121 ortn
= SecTrustedApplicationValidateWithPath(appRef
, NULL
);
131 static bool tsCheckKeyUse(
132 SecTrustSettingsKeyUsage appKeyUse
,
133 CFNumberRef certKeyUse
)
135 if(certKeyUse
!= NULL
) {
137 CFNumberGetValue(certKeyUse
, kCFNumberSInt32Type
, &certUse
);
138 SecTrustSettingsKeyUsage cku
= (SecTrustSettingsKeyUsage
)certUse
;
139 if(cku
== kSecTrustSettingsKeyUseAny
) {
140 /* explicitly allows anything */
143 /* cert specification must be a superset of app's intended use */
145 trustSettingsEvalDbg("tsCheckKeyUse: certKeyUsage, !appKeyUsage");
149 if((cku
& appKeyUse
) != appKeyUse
) {
150 trustSettingsEvalDbg("tsCheckKeyUse: keyUse mismatch");
157 static bool tsCheckPolicyStr(
158 const char *appPolicyStr
,
159 CFStringRef certPolicyStr
)
161 if(certPolicyStr
!= NULL
) {
162 if(appPolicyStr
== NULL
) {
163 trustSettingsEvalDbg("tsCheckPolicyStr: certPolicyStr, !appPolicyStr");
166 /* Let CF do the string compare */
167 CFStringRef cfPolicyStr
= CFStringCreateWithCString(NULL
, appPolicyStr
,
168 kCFStringEncodingUTF8
);
169 if(cfPolicyStr
== NULL
) {
170 /* I really don't see how this can happen */
171 trustSettingsEvalDbg("tsCheckPolicyStr: policyStr string conversion error");
175 // Some trust setting strings were created with a NULL character at the
176 // end, which was included in the length. Strip those off before compare
178 CFMutableStringRef certPolicyStrNoNULL
= CFStringCreateMutableCopy(NULL
, 0, certPolicyStr
);
179 if (certPolicyStrNoNULL
== NULL
) {
180 /* I really don't see how this can happen either */
181 trustSettingsEvalDbg("tsCheckPolicyStr: policyStr string conversion error 2");
185 CFStringFindAndReplace(certPolicyStrNoNULL
, CFSTR("\00"),
186 CFSTR(""), CFRangeMake(0, CFStringGetLength(certPolicyStrNoNULL
)), kCFCompareBackwards
);
188 CFComparisonResult res
= CFStringCompare(cfPolicyStr
, certPolicyStrNoNULL
, 0);
189 CFRelease(cfPolicyStr
);
190 CFRelease(certPolicyStrNoNULL
);
191 if(res
!= kCFCompareEqualTo
) {
192 trustSettingsEvalDbg("tsCheckPolicyStr: policyStr mismatch");
200 * Determine if a cert's trust settings dictionary satisfies the specified
201 * usage constraints. Returns true if so.
202 * Only certs with a SecTrustSettingsResult of kSecTrustSettingsResultTrustRoot
203 * or kSecTrustSettingsResultTrustAsRoot will match.
205 static bool qualifyUsageWithCertDict(
206 CFDictionaryRef certDict
,
207 const CSSM_OID
*policyOID
, /* optional */
208 const char *policyStr
, /* optional */
209 SecTrustSettingsKeyUsage keyUsage
, /* optional; default = any (actually "all" here) */
212 /* this array is optional */
213 CFArrayRef trustSettings
= (CFArrayRef
)CFDictionaryGetValue(certDict
,
214 kTrustRecordTrustSettings
);
215 CFIndex numSpecs
= 0;
216 if(trustSettings
!= NULL
) {
217 numSpecs
= CFArrayGetCount(trustSettings
);
221 * Trivial case: cert has no trust settings, indicating that
222 * it's used for everything.
224 trustSettingsEvalDbg("qualifyUsageWithCertDict: no trust settings");
227 for(CFIndex addDex
=0; addDex
<numSpecs
; addDex
++) {
228 CFDictionaryRef tsDict
= (CFDictionaryRef
)CFArrayGetValueAtIndex(trustSettings
,
231 /* per-cert specs: all optional */
232 CFDataRef certPolicy
= (CFDataRef
)CFDictionaryGetValue(tsDict
,
233 kSecTrustSettingsPolicy
);
234 CFDataRef certApp
= (CFDataRef
)CFDictionaryGetValue(tsDict
,
235 kSecTrustSettingsApplication
);
236 CFStringRef certPolicyStr
= (CFStringRef
)CFDictionaryGetValue(tsDict
,
237 kSecTrustSettingsPolicyString
);
238 CFNumberRef certKeyUsage
= (CFNumberRef
)CFDictionaryGetValue(tsDict
,
239 kSecTrustSettingsKeyUsage
);
240 CFNumberRef certResultType
= (CFNumberRef
)CFDictionaryGetValue(tsDict
,
241 kSecTrustSettingsResult
);
243 if(!tsCheckPolicy(policyOID
, certPolicy
)) {
246 if(!tsCheckApp(certApp
)) {
249 if(!tsCheckKeyUse(keyUsage
, certKeyUsage
)) {
252 if(!tsCheckPolicyStr(policyStr
, certPolicyStr
)) {
257 * This is a match, take whatever SecTrustSettingsResult is here,
258 * including the default if not specified.
260 SecTrustSettingsResult resultType
= kSecTrustSettingsResultTrustRoot
;
263 CFNumberGetValue(certResultType
, kCFNumberSInt32Type
, &s
);
264 resultType
= (SecTrustSettingsResult
)s
;
267 case kSecTrustSettingsResultTrustRoot
:
268 trustSettingsEvalDbg("qualifyUsageWithCertDict: TrustRoot MATCH");
270 case kSecTrustSettingsResultTrustAsRoot
:
272 trustSettingsEvalDbg("qualifyUsageWithCertDict: TrustAsRoot but not root");
275 trustSettingsEvalDbg("qualifyUsageWithCertDict: TrustAsRoot MATCH");
278 trustSettingsEvalDbg("qualifyUsageWithCertDict: bad resultType "
279 "(%lu)", (unsigned long)resultType
);
283 trustSettingsEvalDbg("qualifyUsageWithCertDict: NO MATCH");
288 * Create initial top-level dictionary when constructing a new TrustSettings.
290 static CFMutableDictionaryRef
tsInitialDict()
292 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
,
293 kSecTrustRecordNumTopDictKeys
,
294 &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
296 /* the dictionary of per-cert entries */
297 CFMutableDictionaryRef trustDict
= CFDictionaryCreateMutable(NULL
, 0,
298 &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
299 CFDictionaryAddValue(dict
, kTrustRecordTrustList
, trustDict
);
300 CFRelease(trustDict
);
302 SInt32 vers
= kSecTrustRecordVersionCurrent
;
303 CFNumberRef cfVers
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &vers
);
304 CFDictionaryAddValue(dict
, kTrustRecordVersion
, cfVers
);
310 * Set the modification date of a per-cert dictionary to current time.
312 static void tsSetModDate(
313 CFMutableDictionaryRef dict
)
317 modDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent());
318 CFDictionarySetValue(dict
, kTrustRecordModDate
, modDate
);
322 /* make sure a presumed CFNumber can be converted to a 32-bit number */
324 bool tsIsGoodCfNum(CFNumberRef cfn
, SInt32
*num
= NULL
)
333 if(CFGetTypeID(cfn
) != CFNumberGetTypeID()) {
338 if(!CFNumberGetValue(cfn
, kCFNumberSInt32Type
, &s
)) {
349 TrustSettings::TrustSettings(SecTrustSettingsDomain domain
)
360 #pragma mark --- Public methods ---
363 * Normal constructor, from disk.
364 * If create is true, the absence of an on-disk TrustSettings file
365 * results in the creation of a new empty TrustSettings. If create is
366 * false and no on-disk TrustSettings exists, errSecNoTrustSettings is
368 * If trim is true, the components of the on-disk TrustSettings not
369 * needed for cert evaluation are discarded. This is for TrustSettings
370 * that will be cached in memory long-term.
372 OSStatus
TrustSettings::CreateTrustSettings(
373 SecTrustSettingsDomain domain
,
378 TrustSettings
* t
= new TrustSettings(domain
);
380 Allocator
&alloc
= Allocator::standard();
381 CSSM_DATA fileData
= {0, NULL
};
382 OSStatus ortn
= errSecSuccess
;
386 /* get trust settings from file, one way or another */
388 case kSecTrustSettingsDomainAdmin
:
390 * Quickie optimization: if it's not there, don't try to
391 * get it from ocspd. This is possible because the name of the
392 * admin file is hard coded, but the per-user files aren't.
394 path
= TRUST_SETTINGS_PATH
"/" ADMIN_TRUST_SETTINGS
;
395 if(stat(path
, &sb
)) {
396 trustSettingsDbg("TrustSettings: no admin record; skipping");
397 ortn
= errSecNoTrustSettings
;
400 /* else drop thru, get it from ocspd */
401 case kSecTrustSettingsDomainUser
:
402 /* get settings from ocspd */
403 ortn
= ocspdTrustSettingsRead(alloc
, domain
, fileData
);
405 case kSecTrustSettingsDomainSystem
:
406 /* immutable; it's safe for us to read this directly */
407 if(tsReadFile(SYSTEM_TRUST_SETTINGS_PATH
, alloc
, fileData
)) {
408 ortn
= errSecNoTrustSettings
;
417 trustSettingsDbg("TrustSettings: creating new record for domain %d",
419 t
->mPropList
= tsInitialDict();
423 trustSettingsDbg("TrustSettings: record not found for domain %d",
430 CFRef
<CFDataRef
> propList(CFDataCreate(NULL
, fileData
.Data
, fileData
.Length
));
431 t
->initFromData(propList
);
432 alloc
.free(fileData
.Data
);
434 t
->validatePropList(trim
);
437 return errSecSuccess
;
441 * Create from external data, obtained by createExternal().
442 * If externalData is NULL, we'll create an empty mTrustDict.
444 OSStatus
TrustSettings::CreateTrustSettings(
445 SecTrustSettingsDomain domain
,
446 CFDataRef externalData
,
450 case kSecTrustSettingsDomainUser
:
451 case kSecTrustSettingsDomainAdmin
:
452 case kSecTrustSettingsDomainMemory
:
454 case kSecTrustSettingsDomainSystem
: /* no can do, that implies writing to it */
459 TrustSettings
* t
= new TrustSettings(domain
);
461 if(externalData
!= NULL
) {
462 t
->initFromData(externalData
);
465 t
->mPropList
= tsInitialDict();
467 t
->validatePropList(TRIM_NO
); /* never trim this */
471 return errSecSuccess
;
475 TrustSettings::~TrustSettings()
477 trustSettingsDbg("TrustSettings(domain %d) destructor", (int)mDomain
);
478 CFRELEASE(mPropList
); /* may be null if trimmed */
479 CFRELEASE(mTrustDict
); /* normally always non-NULL */
483 /* common code to init mPropList from raw data */
484 void TrustSettings::initFromData(
485 CFDataRef trustSettingsData
)
487 CFStringRef errStr
= NULL
;
489 mPropList
= (CFMutableDictionaryRef
)CFPropertyListCreateFromXMLData(
492 kCFPropertyListMutableContainersAndLeaves
,
494 if(mPropList
== NULL
) {
495 trustSettingsDbg("TrustSettings::initFromData decode err (%s)",
496 errStr
? CFStringGetCStringPtr(errStr
, kCFStringEncodingUTF8
) : "<no err>");
500 MacOSError::throwMe(errSecInvalidTrustSettings
);
505 * Flush property list data out to disk if dirty.
507 void TrustSettings::flushToDisk()
510 trustSettingsDbg("flushToDisk, domain %d, !dirty!", (int)mDomain
);
513 if(mPropList
== NULL
) {
514 trustSettingsDbg("flushToDisk, domain %d, trimmed!", (int)mDomain
);
516 MacOSError::throwMe(errSecInternalComponent
);
519 case kSecTrustSettingsDomainSystem
:
520 case kSecTrustSettingsDomainMemory
:
521 /* caller shouldn't even try this */
523 trustSettingsDbg("flushToDisk, bad domain (%d)", (int)mDomain
);
524 MacOSError::throwMe(errSecInternalComponent
);
525 case kSecTrustSettingsDomainUser
:
526 case kSecTrustSettingsDomainAdmin
:
531 * Optimization: if there are no certs in the mTrustDict dictionary,
532 * we tell ocspd to *remove* the settings for the specified domain.
533 * Having *no* settings uses less memory and is faster than having
534 * an empty settings file, especially for the admin domain, where we
536 * an RPC if the settings file is simply not there.
538 CFRef
<CFDataRef
> xmlData
;
539 CSSM_DATA cssmXmlData
= {0, NULL
};
540 CFIndex numCerts
= CFDictionaryGetCount(mTrustDict
);
542 xmlData
.take(CFPropertyListCreateXMLData(NULL
, mPropList
));
544 /* we've been very careful; this should never happen */
545 trustSettingsDbg("flushToDisk, domain %d: error converting to XML", (int)mDomain
);
546 MacOSError::throwMe(errSecInternalComponent
);
548 cssmXmlData
.Data
= (uint8
*)CFDataGetBytePtr(xmlData
);
549 cssmXmlData
.Length
= CFDataGetLength(xmlData
);
552 trustSettingsDbg("flushToDisk, domain %d: DELETING trust settings", (int)mDomain
);
555 /* cook up auth stuff so ocspd can act on our behalf */
556 AuthorizationRef authRef
;
558 ortn
= AuthorizationCreate(NULL
, kAuthorizationEmptyEnvironment
,
561 trustSettingsDbg("flushToDisk, domain %d: AuthorizationCreate returned %ld",
562 (int)mDomain
, (long)ortn
);
563 MacOSError::throwMe(errSecInternalComponent
);
565 AuthorizationExternalForm authExt
;
566 CSSM_DATA authBlob
= {sizeof(authExt
), (uint8
*)&authExt
};
567 ortn
= AuthorizationMakeExternalForm(authRef
, &authExt
);
569 trustSettingsDbg("flushToDisk, domain %d: AuthorizationMakeExternalForm returned %ld",
570 (int)mDomain
, (long)ortn
);
571 ortn
= errSecInternalComponent
;
575 ortn
= ocspdTrustSettingsWrite(mDomain
, authBlob
, cssmXmlData
);
577 trustSettingsDbg("flushToDisk, domain %d: ocspdTrustSettingsWrite returned %ld",
578 (int)mDomain
, (long)ortn
);
581 trustSettingsDbg("flushToDisk, domain %d: wrote to disk", (int)mDomain
);
584 AuthorizationFree(authRef
, 0);
586 MacOSError::throwMe(ortn
);
591 * Obtain external representation of TrustSettings data.
593 CFDataRef
TrustSettings::createExternal()
596 CFDataRef xmlData
= CFPropertyListCreateXMLData(NULL
, mPropList
);
597 if(xmlData
== NULL
) {
598 trustSettingsDbg("createExternal, domain %d: error converting to XML",
600 MacOSError::throwMe(errSecInternalComponent
);
606 * Evaluate specified cert. Returns true if we found a record for the cert
607 * matching specified constraints.
608 * Note that a true return with a value of kSecTrustSettingsResultUnspecified for
609 * the resultType means that a cert isn't to be trusted or untrusted
610 * per se; it just means that we only found allowedErrors entries.
612 * Found "allows errors" values are added to the incoming allowedErrors
613 * array which is reallocd as needed (and which may be NULL or non-NULL on
616 bool TrustSettings::evaluateCert(
617 CFStringRef certHashStr
,
618 const CSSM_OID
*policyOID
, /* optional */
619 const char *policyStr
, /* optional */
620 SecTrustSettingsKeyUsage keyUsage
, /* optional */
621 bool isRootCert
, /* for checking default setting */
622 CSSM_RETURN
**allowedErrors
, /* IN/OUT; reallocd as needed */
623 uint32
*numAllowedErrors
, /* IN/OUT */
624 SecTrustSettingsResult
*resultType
, /* RETURNED */
625 bool *foundAnyEntry
) /* RETURNED */
627 assert(mTrustDict
!= NULL
);
629 /* get trust settings dictionary for this cert */
630 CFDictionaryRef certDict
= findDictionaryForCertHash(certHashStr
);
631 if((certDict
== NULL
) && isRootCert
) {
632 /* No? How about default root setting for this domain? */
633 certDict
= findDictionaryForCertHash(kSecTrustRecordDefaultRootCert
);
636 /* @@@ debug only @@@ */
637 /* print certificate hash and found dictionary reference */
638 const size_t maxHashStrLen
= 512;
639 char *buf
= (char*)malloc(maxHashStrLen
);
641 if (!CFStringGetCString(certHashStr
, buf
, (CFIndex
)maxHashStrLen
, kCFStringEncodingUTF8
)) {
644 trustSettingsEvalDbg("evaluateCert for \"%s\", found dict %p", buf
, certDict
);
649 if(certDict
== NULL
) {
650 *foundAnyEntry
= false;
653 *foundAnyEntry
= true;
655 /* to-be-returned array of allowed errors */
656 CSSM_RETURN
*allowedErrs
= *allowedErrors
;
657 uint32 numAllowedErrs
= *numAllowedErrors
;
659 /* this means "we found something other than allowedErrors" if true */
660 bool foundSettings
= false;
662 /* to be returned in *resultType if it ends up something other than Invalid */
663 SecTrustSettingsResult returnedResult
= kSecTrustSettingsResultInvalid
;
666 * Note since we validated the entire mPropList in our constructor, and we're careful
667 * about what we put into it, we don't bother typechecking its contents here.
668 * Also note that the kTrustRecordTrustSettings entry is optional.
670 CFArrayRef trustSettings
= (CFArrayRef
)CFDictionaryGetValue(certDict
,
671 kTrustRecordTrustSettings
);
672 CFIndex numSpecs
= 0;
673 if(trustSettings
!= NULL
) {
674 numSpecs
= CFArrayGetCount(trustSettings
);
678 * Trivial case: cert has no trust settings, indicating that
679 * it's used for everything.
681 trustSettingsEvalDbg("evaluateCert: no trust settings");
683 *resultType
= kSecTrustSettingsResultTrustRoot
;
688 * The decidedly nontrivial part: grind thru all of the cert's trust
689 * settings, see if the cert matches the caller's specified usage.
691 for(CFIndex addDex
=0; addDex
<numSpecs
; addDex
++) {
692 CFDictionaryRef tsDict
= (CFDictionaryRef
)CFArrayGetValueAtIndex(trustSettings
,
695 /* per-cert specs: all optional */
696 CFDataRef certPolicy
= (CFDataRef
)CFDictionaryGetValue(tsDict
,
697 kSecTrustSettingsPolicy
);
698 CFDataRef certApp
= (CFDataRef
)CFDictionaryGetValue(tsDict
,
699 kSecTrustSettingsApplication
);
700 CFStringRef certPolicyStr
= (CFStringRef
)CFDictionaryGetValue(tsDict
,
701 kSecTrustSettingsPolicyString
);
702 CFNumberRef certKeyUsage
= (CFNumberRef
)CFDictionaryGetValue(tsDict
,
703 kSecTrustSettingsKeyUsage
);
704 CFNumberRef certResultType
= (CFNumberRef
)CFDictionaryGetValue(tsDict
,
705 kSecTrustSettingsResult
);
706 CFNumberRef certAllowedErr
= (CFNumberRef
)CFDictionaryGetValue(tsDict
,
707 kSecTrustSettingsAllowedError
);
709 /* now, skip if we find a constraint that doesn't match intended use */
710 if(!tsCheckPolicy(policyOID
, certPolicy
)) {
713 if(!tsCheckApp(certApp
)) {
716 if(!tsCheckKeyUse(keyUsage
, certKeyUsage
)) {
719 if(!tsCheckPolicyStr(policyStr
, certPolicyStr
)) {
723 trustSettingsEvalDbg("evaluateCert: MATCH");
724 foundSettings
= true;
727 /* note we already validated this value */
729 CFNumberGetValue(certAllowedErr
, kCFNumberSInt32Type
, &s
);
730 allowedErrs
= (CSSM_RETURN
*)::realloc(allowedErrs
,
731 ++numAllowedErrs
* sizeof(CSSM_RETURN
));
732 allowedErrs
[numAllowedErrs
-1] = (CSSM_RETURN
) s
;
736 * We found a match, but we only return the current result type
737 * to caller if we haven't already returned something other than
738 * kSecTrustSettingsResultUnspecified. Once we find a valid result type,
739 * we keep on searching, but only for additional allowed errors.
741 switch(returnedResult
) {
742 /* found match but no valid resultType yet */
743 case kSecTrustSettingsResultUnspecified
:
744 /* haven't been thru here */
745 case kSecTrustSettingsResultInvalid
:
747 /* note we already validated this */
749 CFNumberGetValue(certResultType
, kCFNumberSInt32Type
, &s
);
750 returnedResult
= (SecTrustSettingsResult
)s
;
753 /* default is "copacetic" */
754 returnedResult
= kSecTrustSettingsResultTrustRoot
;
758 /* we already have a definitive resultType, don't change it */
761 } /* for each dictionary in trustSettings */
763 *allowedErrors
= allowedErrs
;
764 *numAllowedErrors
= numAllowedErrs
;
765 if(returnedResult
!= kSecTrustSettingsResultInvalid
) {
766 *resultType
= returnedResult
;
768 return foundSettings
;
773 * Find all certs in specified keychain list which have entries in this trust record.
774 * Certs already in the array are not added.
776 void TrustSettings::findCerts(
777 StorageManager::KeychainList
&keychains
,
778 CFMutableArrayRef certArray
)
780 findQualifiedCerts(keychains
,
782 false, /* onlyRoots */
783 NULL
, NULL
, kSecTrustSettingsKeyUseAny
,
787 void TrustSettings::findQualifiedCerts(
788 StorageManager::KeychainList
&keychains
,
790 * If findAll is true, all certs are returned and the subsequent
791 * qualifiers are ignored
794 /* if true, only return root (self-signed) certs */
796 const CSSM_OID
*policyOID
, /* optional */
797 const char *policyString
, /* optional */
798 SecTrustSettingsKeyUsage keyUsage
, /* optional */
799 CFMutableArrayRef certArray
) /* certs appended here */
801 StLock
<Mutex
> _(SecTrustKeychainsGetMutex());
804 * a set, hopefully with a good hash function for CFData, to keep track of what's
805 * been added to the outgoing array.
807 CFRef
<CFMutableSetRef
> certSet(CFSetCreateMutable(NULL
, 0, &kCFTypeSetCallBacks
));
809 /* search: all certs, no attributes */
810 KCCursor
cursor(keychains
, CSSM_DL_DB_RECORD_X509_CERTIFICATE
, NULL
);
813 unsigned int total
=0, entries
=0, qualified
=0;
815 found
= cursor
->next(certItem
);
821 CFRef
<SecCertificateRef
> certRef((SecCertificateRef
)certItem
->handle());
823 /* must convert to unified SecCertificateRef */
824 SecPointer
<Certificate
> certificate(static_cast<Certificate
*>(&*certItem
));
825 CssmData certCssmData
;
827 certCssmData
= certificate
->data();
830 if (!(certCssmData
.Data
&& certCssmData
.Length
)) {
833 CFRef
<CFDataRef
> cfDataRef(CFDataCreate(NULL
, certCssmData
.Data
, certCssmData
.Length
));
834 CFRef
<SecCertificateRef
> certRef(SecCertificateCreateWithData(NULL
, cfDataRef
));
837 /* do we have an entry for this cert? */
838 CFDictionaryRef certDict
= findDictionaryForCert(certRef
);
839 if(certDict
== NULL
) {
846 if(!qualifyUsageWithCertDict(certDict
, policyOID
,
847 policyString
, keyUsage
, onlyRoots
)) {
853 /* see if we already have this one - get in CFData form */
855 OSStatus ortn
= SecCertificateGetData(certRef
, &certData
);
857 trustSettingsEvalDbg("findQualifiedCerts: SecCertificateGetData error");
860 CFRef
<CFDataRef
> cfData(CFDataCreate(NULL
, certData
.Data
, certData
.Length
));
861 CFDataRef cfd
= cfData
.get();
862 if(CFSetContainsValue(certSet
, cfd
)) {
863 trustSettingsEvalDbg("findQualifiedCerts: dup cert");
867 /* add to the tracking set, which owns the CFData now */
868 CFSetAddValue(certSet
, cfd
);
869 /* and add the SecCert to caller's array, which owns that now */
870 CFArrayAppendValue(certArray
, certRef
);
874 trustSettingsEvalDbg("findQualifiedCerts: examined %d certs, qualified %d of %d",
875 total
, qualified
, entries
);
879 * Obtain trust settings for the specified cert. Returned settings array
880 * is in the public API form; caller must release. Returns NULL
881 * (does not throw) if the cert is not present in this TrustRecord.
883 CFArrayRef
TrustSettings::copyTrustSettings(
884 SecCertificateRef certRef
)
886 CFDictionaryRef certDict
= NULL
;
888 /* find the on-disk usage constraints for this cert */
889 certDict
= findDictionaryForCert(certRef
);
890 if(certDict
== NULL
) {
891 trustSettingsDbg("copyTrustSettings: dictionary not found");
894 CFArrayRef diskTrustSettings
= (CFArrayRef
)CFDictionaryGetValue(certDict
,
895 kTrustRecordTrustSettings
);
896 CFIndex numSpecs
= 0;
897 if(diskTrustSettings
!= NULL
) {
898 /* this field is optional */
899 numSpecs
= CFArrayGetCount(diskTrustSettings
);
903 * Convert to API-style array of dictionaries.
904 * We give the caller an array even if it's empty.
906 CFRef
<CFMutableArrayRef
> outArray(CFArrayCreateMutable(NULL
, numSpecs
,
907 &kCFTypeArrayCallBacks
));
908 for(CFIndex dex
=0; dex
<numSpecs
; dex
++) {
909 CFDictionaryRef diskTsDict
=
910 (CFDictionaryRef
)CFArrayGetValueAtIndex(diskTrustSettings
, dex
);
911 /* already validated... */
912 assert(CFGetTypeID(diskTsDict
) == CFDictionaryGetTypeID());
914 CFTypeRef certPolicy
= (CFTypeRef
) CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsPolicy
);
915 CFStringRef policyName
= (CFStringRef
)CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsPolicyName
);
916 CFDataRef certApp
= (CFDataRef
) CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsApplication
);
917 CFStringRef policyStr
= (CFStringRef
)CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsPolicyString
);
918 CFNumberRef allowedErr
= (CFNumberRef
)CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsAllowedError
);
919 CFNumberRef resultType
= (CFNumberRef
)CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsResult
);
920 CFNumberRef keyUsage
= (CFNumberRef
)CFDictionaryGetValue(diskTsDict
, kSecTrustSettingsKeyUsage
);
922 if((certPolicy
== NULL
) &&
924 (policyStr
== NULL
) &&
925 (allowedErr
== NULL
) &&
926 (resultType
== NULL
) &&
927 (keyUsage
== NULL
)) {
928 /* weird but legal */
931 CFRef
<CFMutableDictionaryRef
> outTsDict(CFDictionaryCreateMutable(NULL
,
933 &kCFTypeDictionaryKeyCallBacks
,
934 &kCFTypeDictionaryValueCallBacks
));
936 if(certPolicy
!= NULL
) {
937 SecPolicyRef policyRef
= NULL
;
938 if (CFDataGetTypeID() == CFGetTypeID(certPolicy
)) {
939 /* convert OID as CFDataRef to SecPolicyRef */
940 CSSM_OID policyOid
= { CFDataGetLength((CFDataRef
)certPolicy
),
941 (uint8
*)CFDataGetBytePtr((CFDataRef
)certPolicy
) };
942 OSStatus ortn
= SecPolicyCopy(CSSM_CERT_X_509v3
, &policyOid
, &policyRef
);
944 trustSettingsDbg("copyTrustSettings: OID conversion error");
945 abort("Bad Policy OID in trusted root list", errSecInvalidTrustedRootRecord
);
947 } else if (CFStringGetTypeID() == CFGetTypeID(certPolicy
)) {
948 policyRef
= SecPolicyCreateWithProperties(certPolicy
, NULL
);
951 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsPolicy
, policyRef
);
952 CFRelease(policyRef
); // owned by dictionary
956 if (policyName
!= NULL
) {
958 * copy, since policyName is in our mutable dictionary and could change out from
961 CFStringRef str
= CFStringCreateCopy(NULL
, policyName
);
962 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsPolicyName
, str
);
963 CFRelease(str
); // owned by dictionary
966 if(certApp
!= NULL
) {
967 /* convert app as CFDataRef to SecTrustedApplicationRef */
968 SecTrustedApplicationRef appRef
;
969 OSStatus ortn
= SecTrustedApplicationCreateWithExternalRepresentation(certApp
, &appRef
);
971 trustSettingsDbg("copyTrustSettings: App conversion error");
972 abort("Bad application data in trusted root list", errSecInvalidTrustedRootRecord
);
974 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsApplication
, appRef
);
975 CFRelease(appRef
); // owned by dictionary
978 /* remaining 4 are trivial */
979 if(policyStr
!= NULL
) {
981 * copy, since policyStr is in our mutable dictionary and could change out from
984 CFStringRef str
= CFStringCreateCopy(NULL
, policyStr
);
985 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsPolicyString
, str
);
986 CFRelease(str
); // owned by dictionary
988 if(allowedErr
!= NULL
) {
989 /* there is no mutable CFNumber, so.... */
990 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsAllowedError
, allowedErr
);
992 if(resultType
!= NULL
) {
993 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsResult
, resultType
);
995 if(keyUsage
!= NULL
) {
996 CFDictionaryAddValue(outTsDict
, kSecTrustSettingsKeyUsage
, keyUsage
);
998 CFArrayAppendValue(outArray
, outTsDict
);
999 /* outTsDict autoreleases; owned by outArray now */
1001 CFRetain(outArray
); // now that it's good to go....
1005 CFDateRef
TrustSettings::copyModDate(
1006 SecCertificateRef certRef
)
1008 CFDictionaryRef certDict
= NULL
;
1010 /* find the on-disk usage constraints dictionary for this cert */
1011 certDict
= findDictionaryForCert(certRef
);
1012 if(certDict
== NULL
) {
1013 trustSettingsDbg("copyModDate: dictionary not found");
1016 CFDateRef modDate
= (CFDateRef
)CFDictionaryGetValue(certDict
, kTrustRecordModDate
);
1017 if(modDate
== NULL
) {
1021 /* this only works becuase there is no mutable CFDateRef */
1027 * Modify cert's trust settings, or add a new cert to the record.
1029 void TrustSettings::setTrustSettings(
1030 SecCertificateRef certRef
,
1031 CFTypeRef trustSettingsDictOrArray
)
1033 /* to validate, we need to know if the cert is self-signed */
1035 Boolean isSelfSigned
= false;
1037 if(certRef
== kSecTrustSettingsDefaultRootCertSetting
) {
1039 * Validate settings as if this were root, specifically,
1040 * kSecTrustSettingsResultTrustRoot (explicitly or by
1043 isSelfSigned
= true;
1046 ortn
= SecCertificateIsSelfSigned(certRef
, &isSelfSigned
);
1048 MacOSError::throwMe(ortn
);
1052 /* caller's app/policy spec OK? */
1053 CFRef
<CFArrayRef
> trustSettings(validateApiTrustSettings(
1054 trustSettingsDictOrArray
, isSelfSigned
));
1056 /* caller is responsible for ensuring these */
1057 assert(mPropList
!= NULL
);
1058 assert(mDomain
!= kSecTrustSettingsDomainSystem
);
1060 /* extract issuer and serial number from the cert, if it's a cert */
1061 CFRef
<CFDataRef
> issuer
;
1062 CFRef
<CFDataRef
> serial
;
1063 if(certRef
!= kSecTrustSettingsDefaultRootCertSetting
) {
1064 copyIssuerAndSerial(certRef
, issuer
.take(), serial
.take());
1068 issuer
= CFDataCreate(NULL
, &dummy
, 0);
1069 serial
= CFDataCreate(NULL
, &dummy
, 0);
1072 /* SHA1 digest as string */
1073 CFRef
<CFStringRef
> certHashStr(SecTrustSettingsCertHashStrFromCert(certRef
));
1075 trustSettingsDbg("TrustSettings::setTrustSettings: CertHashStrFromCert error");
1076 MacOSError::throwMe(errSecItemNotFound
);
1080 * Find entry for this cert, if present.
1082 CFMutableDictionaryRef certDict
=
1083 (CFMutableDictionaryRef
)findDictionaryForCertHash(certHashStr
);
1084 if(certDict
== NULL
) {
1085 /* create new dictionary */
1086 certDict
= CFDictionaryCreateMutable(NULL
, kSecTrustRecordNumCertDictKeys
,
1087 &kCFCopyStringDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1088 if(certDict
== NULL
) {
1089 MacOSError::throwMe(errSecAllocate
);
1091 CFDictionaryAddValue(certDict
, kTrustRecordIssuer
, issuer
);
1092 CFDictionaryAddValue(certDict
, kTrustRecordSerialNumber
, serial
);
1093 if(CFArrayGetCount(trustSettings
) != 0) {
1094 /* skip this if the settings array is empty */
1095 CFDictionaryAddValue(certDict
, kTrustRecordTrustSettings
, trustSettings
);
1097 tsSetModDate(certDict
);
1099 /* add this new cert dictionary to top-level mTrustDict */
1100 CFDictionaryAddValue(mTrustDict
, static_cast<CFStringRef
>(certHashStr
), certDict
);
1102 /* mTrustDict owns the dictionary now */
1103 CFRelease(certDict
);
1107 tsSetModDate(certDict
);
1108 if(CFArrayGetCount(trustSettings
) != 0) {
1109 CFDictionarySetValue(certDict
, kTrustRecordTrustSettings
, trustSettings
);
1112 /* empty settings array: remove from dictionary */
1113 CFDictionaryRemoveValue(certDict
, kTrustRecordTrustSettings
);
1120 * Delete a certificate's trust settings.
1122 void TrustSettings::deleteTrustSettings(
1123 SecCertificateRef certRef
)
1125 CFDictionaryRef certDict
= NULL
;
1127 /* caller is responsible for ensuring these */
1128 assert(mPropList
!= NULL
);
1129 assert(mDomain
!= kSecTrustSettingsDomainSystem
);
1131 /* SHA1 digest as string */
1132 CFRef
<CFStringRef
> certHashStr(SecTrustSettingsCertHashStrFromCert(certRef
));
1134 MacOSError::throwMe(errSecItemNotFound
);
1137 /* present in top-level mTrustDict? */
1138 certDict
= findDictionaryForCertHash(certHashStr
);
1139 if(certDict
!= NULL
) {
1140 CFDictionaryRemoveValue(mTrustDict
, static_cast<CFStringRef
>(certHashStr
));
1145 * Throwing this error is the only reason we don't blindly do
1146 * a CFDictionaryRemoveValue() without first doing
1147 * findDictionaryForCertHash().
1149 trustSettingsDbg("TrustSettings::deleteRoot: cert dictionary not found");
1150 MacOSError::throwMe(errSecItemNotFound
);
1154 #pragma mark --- Private methods ---
1157 * Find a given cert's entry in the top-level mTrustDict. Return the
1158 * entry as a dictionary. Returned dictionary is not refcounted.
1159 * The mutability of the returned dictionary is the same as the mutability
1160 * of the underlying StickRecord::mPropList, which the caller is just
1161 * going to have to know (and cast accordingly if a mutable dictionary
1164 CFDictionaryRef
TrustSettings::findDictionaryForCert(
1165 SecCertificateRef certRef
)
1167 CFRef
<CFStringRef
> certHashStr(SecTrustSettingsCertHashStrFromCert(certRef
));
1168 if (certHashStr
.get() == NULL
)
1173 return findDictionaryForCertHash(static_cast<CFStringRef
>(certHashStr
.get()));
1177 * Find entry in mTrustDict given cert hash string.
1179 CFDictionaryRef
TrustSettings::findDictionaryForCertHash(
1180 CFStringRef certHashStr
)
1182 assert(mTrustDict
!= NULL
);
1183 return (CFDictionaryRef
)CFDictionaryGetValue(mTrustDict
, certHashStr
);
1187 * Validate incoming trust settings, which may be NULL, a dictionary, or
1188 * an array of dictionaries. Convert from the API-style dictionaries
1189 * to the internal style suitable for writing to disk as part of
1192 * We return a refcounted CFArray in any case if the incoming parameter is good.
1194 CFArrayRef
TrustSettings::validateApiTrustSettings(
1195 CFTypeRef trustSettingsDictOrArray
,
1196 Boolean isSelfSigned
)
1198 CFArrayRef tmpInArray
= NULL
;
1200 if(trustSettingsDictOrArray
== NULL
) {
1201 /* trivial case, only valid for roots */
1203 trustSettingsDbg("validateApiUsageConstraints: !isSelfSigned, no settings");
1204 MacOSError::throwMe(errSecParam
);
1206 return CFArrayCreate(NULL
, NULL
, 0, &kCFTypeArrayCallBacks
);
1208 else if(CFGetTypeID(trustSettingsDictOrArray
) == CFDictionaryGetTypeID()) {
1210 tmpInArray
= CFArrayCreate(NULL
, &trustSettingsDictOrArray
, 1,
1211 &kCFTypeArrayCallBacks
);
1213 else if(CFGetTypeID(trustSettingsDictOrArray
) == CFArrayGetTypeID()) {
1214 /* as is, refcount - we'll release later */
1215 tmpInArray
= (CFArrayRef
)trustSettingsDictOrArray
;
1216 CFRetain(tmpInArray
);
1219 trustSettingsDbg("validateApiUsageConstraints: bad trustSettingsDictOrArray");
1220 MacOSError::throwMe(errSecParam
);
1223 CFIndex numSpecs
= CFArrayGetCount(tmpInArray
);
1224 CFMutableArrayRef outArray
= CFArrayCreateMutable(NULL
, numSpecs
, &kCFTypeArrayCallBacks
);
1226 OSStatus ortn
= errSecSuccess
;
1227 SecPolicyRef certPolicy
;
1228 SecTrustedApplicationRef certApp
;
1231 for(CFIndex dex
=0; dex
<numSpecs
; dex
++) {
1232 CFTypeRef oidData
= NULL
;
1233 CFStringRef policyName
= NULL
;
1234 CFDataRef appData
= NULL
;
1235 CFStringRef policyStr
= NULL
;
1236 CFNumberRef allowedErr
= NULL
;
1237 CFNumberRef resultType
= NULL
;
1238 CFNumberRef keyUsage
= NULL
;
1240 SecTrustSettingsResult result
;
1242 /* each element is a dictionary */
1243 CFDictionaryRef ucDict
= (CFDictionaryRef
)CFArrayGetValueAtIndex(tmpInArray
, dex
);
1244 if(CFGetTypeID(ucDict
) != CFDictionaryGetTypeID()) {
1245 trustSettingsDbg("validateAppPolicyArray: malformed usageConstraint dictionary");
1250 /* policy - optional */
1251 certPolicy
= (SecPolicyRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsPolicy
);
1252 if(certPolicy
!= NULL
) {
1253 if(CFGetTypeID(certPolicy
) != SecPolicyGetTypeID()) {
1254 trustSettingsDbg("validateAppPolicyArray: malformed certPolicy");
1258 ortn
= SecPolicyGetOID(certPolicy
, &oid
);
1260 /* newer policies don't have CSSM OIDs but they do have string OIDs */
1261 oidData
= CFRetain(SecPolicyGetOidString(certPolicy
));
1263 oidData
= CFDataCreate(NULL
, oid
.Data
, oid
.Length
);
1267 trustSettingsDbg("validateAppPolicyArray: SecPolicyGetOID error");
1270 policyName
= SecPolicyGetName(certPolicy
);
1273 /* application - optional */
1274 certApp
= (SecTrustedApplicationRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsApplication
);
1275 if(certApp
!= NULL
) {
1276 if(CFGetTypeID(certApp
) != SecTrustedApplicationGetTypeID()) {
1277 trustSettingsDbg("validateAppPolicyArray: malformed certApp");
1281 ortn
= SecTrustedApplicationCopyExternalRepresentation(certApp
, &appData
);
1283 trustSettingsDbg("validateAppPolicyArray: "
1284 "SecTrustedApplicationCopyExternalRepresentation error");
1289 policyStr
= (CFStringRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsPolicyString
);
1290 if(policyStr
!= NULL
) {
1291 if(CFGetTypeID(policyStr
) != CFStringGetTypeID()) {
1292 trustSettingsDbg("validateAppPolicyArray: malformed policyStr");
1297 allowedErr
= (CFNumberRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsAllowedError
);
1298 if(!tsIsGoodCfNum(allowedErr
)) {
1299 trustSettingsDbg("validateAppPolicyArray: malformed allowedErr");
1303 resultType
= (CFNumberRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsResult
);
1304 if(!tsIsGoodCfNum(resultType
, &resultNum
)) {
1305 trustSettingsDbg("validateAppPolicyArray: malformed resultType");
1310 /* validate result later */
1312 keyUsage
= (CFNumberRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsKeyUsage
);
1313 if(!tsIsGoodCfNum(keyUsage
)) {
1314 trustSettingsDbg("validateAppPolicyArray: malformed keyUsage");
1319 if(!oidData
&& !appData
&& !policyStr
&&
1320 !allowedErr
&& !resultType
&& !keyUsage
) {
1321 /* nothing here - weird, but legal - skip it */
1325 /* create dictionary for this usageConstraint */
1326 CFMutableDictionaryRef outDict
= CFDictionaryCreateMutable(NULL
,
1328 &kCFTypeDictionaryKeyCallBacks
,
1329 &kCFTypeDictionaryValueCallBacks
);
1331 CFDictionaryAddValue(outDict
, kSecTrustSettingsPolicy
, oidData
);
1332 CFRelease(oidData
); // owned by dictionary
1335 CFDictionaryAddValue(outDict
, kSecTrustSettingsPolicyName
, policyName
);
1336 /* still owned by ucDict */
1339 CFDictionaryAddValue(outDict
, kSecTrustSettingsApplication
, appData
);
1340 CFRelease(appData
); // owned by dictionary
1343 CFDictionaryAddValue(outDict
, kSecTrustSettingsPolicyString
, policyStr
);
1344 /* still owned by ucDict */
1347 CFDictionaryAddValue(outDict
, kSecTrustSettingsAllowedError
, allowedErr
);
1350 ortn
= errSecSuccess
;
1353 /* let's be really picky on this one */
1355 case kSecTrustSettingsResultInvalid
:
1358 case kSecTrustSettingsResultTrustRoot
:
1360 trustSettingsDbg("validateAppPolicyArray: TrustRoot, !isSelfSigned");
1364 case kSecTrustSettingsResultTrustAsRoot
:
1366 trustSettingsDbg("validateAppPolicyArray: TrustAsRoot, isSelfSigned");
1370 case kSecTrustSettingsResultDeny
:
1371 case kSecTrustSettingsResultUnspecified
:
1374 trustSettingsDbg("validateAppPolicyArray: bogus resultType");
1381 CFDictionaryAddValue(outDict
, kSecTrustSettingsResult
, resultType
);
1384 /* no resultType; default of TrustRoot only valid for root */
1386 trustSettingsDbg("validateAppPolicyArray: default result, !isSelfSigned");
1393 CFDictionaryAddValue(outDict
, kSecTrustSettingsKeyUsage
, keyUsage
);
1396 /* append dictionary to output */
1397 CFArrayAppendValue(outArray
, outDict
);
1398 /* array owns the dictionary now */
1401 } /* for each usage constraint dictionary */
1403 CFRelease(tmpInArray
);
1405 CFRelease(outArray
);
1406 MacOSError::throwMe(ortn
);
1412 * Validate an trust settings array obtained from disk.
1413 * Returns true if OK, else returns false.
1415 bool TrustSettings::validateTrustSettingsArray(
1416 CFArrayRef trustSettings
)
1418 CFIndex numSpecs
= CFArrayGetCount(trustSettings
);
1419 for(CFIndex dex
=0; dex
<numSpecs
; dex
++) {
1420 CFDictionaryRef ucDict
= (CFDictionaryRef
)CFArrayGetValueAtIndex(trustSettings
,
1422 if(CFGetTypeID(ucDict
) != CFDictionaryGetTypeID()) {
1423 trustSettingsDbg("validateAppPolicyArray: malformed app/policy dictionary");
1426 CFDataRef certPolicy
= (CFDataRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsPolicy
);
1427 if((certPolicy
!= NULL
) && (CFGetTypeID(certPolicy
) != CFDataGetTypeID())) {
1428 trustSettingsDbg("validateAppPolicyArray: malformed certPolicy");
1431 CFDataRef certApp
= (CFDataRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsApplication
);
1432 if((certApp
!= NULL
) && (CFGetTypeID(certApp
) != CFDataGetTypeID())) {
1433 trustSettingsDbg("validateAppPolicyArray: malformed certApp");
1436 CFStringRef policyStr
= (CFStringRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsPolicyString
);
1437 if((policyStr
!= NULL
) && (CFGetTypeID(policyStr
) != CFStringGetTypeID())) {
1438 trustSettingsDbg("validateAppPolicyArray: malformed policyStr");
1441 CFNumberRef cfNum
= (CFNumberRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsAllowedError
);
1442 if(!tsIsGoodCfNum(cfNum
)) {
1443 trustSettingsDbg("validateAppPolicyArray: malformed allowedErr");
1446 cfNum
= (CFNumberRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsResult
);
1447 if(!tsIsGoodCfNum(cfNum
)) {
1448 trustSettingsDbg("validateAppPolicyArray: malformed resultType");
1451 cfNum
= (CFNumberRef
)CFDictionaryGetValue(ucDict
, kSecTrustSettingsKeyUsage
);
1452 if(!tsIsGoodCfNum(cfNum
)) {
1453 trustSettingsDbg("validateAppPolicyArray: malformed keyUsage");
1456 } /* for each usageConstraint dictionary */
1461 * Validate mPropList after it's read from disk or supplied as an external
1462 * representation. Allows subsequent use of mTrustDict to proceed with
1463 * relative impunity.
1465 void TrustSettings::validatePropList(bool trim
)
1467 /* top level dictionary */
1469 trustSettingsDbg("TrustSettings::validatePropList missing mPropList");
1470 abort("missing propList", errSecInvalidTrustedRootRecord
);
1473 if(CFGetTypeID(mPropList
) != CFDictionaryGetTypeID()) {
1474 trustSettingsDbg("TrustSettings::validatePropList: malformed mPropList");
1475 abort("malformed propList", errSecInvalidTrustedRootRecord
);
1478 /* That dictionary has two entries */
1479 CFNumberRef cfVers
= (CFNumberRef
)CFDictionaryGetValue(mPropList
, kTrustRecordVersion
);
1480 if((cfVers
== NULL
) || (CFGetTypeID(cfVers
) != CFNumberGetTypeID())) {
1481 trustSettingsDbg("TrustSettings::validatePropList: malformed version");
1482 abort("malformed version", errSecInvalidTrustedRootRecord
);
1484 if(!CFNumberGetValue(cfVers
, kCFNumberSInt32Type
, &mDictVersion
)) {
1485 trustSettingsDbg("TrustSettings::validatePropList: malformed version");
1486 abort("malformed version", errSecInvalidTrustedRootRecord
);
1488 if((mDictVersion
> kSecTrustRecordVersionCurrent
) ||
1489 (mDictVersion
== kSecTrustRecordVersionInvalid
)) {
1490 trustSettingsDbg("TrustSettings::validatePropList: incompatible version");
1491 abort("incompatible version", errSecInvalidTrustedRootRecord
);
1493 /* other backwards-compatibility handling done later, if needed, per mDictVersion */
1495 mTrustDict
= (CFMutableDictionaryRef
)CFDictionaryGetValue(mPropList
, kTrustRecordTrustList
);
1496 if(mTrustDict
!= NULL
) {
1497 CFRetain(mTrustDict
);
1499 if((mTrustDict
== NULL
) || (CFGetTypeID(mTrustDict
) != CFDictionaryGetTypeID())) {
1500 trustSettingsDbg("TrustSettings::validatePropList: malformed mTrustDict");
1501 abort("malformed TrustArray", errSecInvalidTrustedRootRecord
);
1504 /* grind through the per-cert entries */
1505 CFIndex numCerts
= CFDictionaryGetCount(mTrustDict
);
1506 const void *dictKeys
[numCerts
];
1507 const void *dictValues
[numCerts
];
1508 CFDictionaryGetKeysAndValues(mTrustDict
, dictKeys
, dictValues
);
1510 for(CFIndex dex
=0; dex
<numCerts
; dex
++) {
1511 /* get per-cert dictionary */
1512 CFMutableDictionaryRef certDict
= (CFMutableDictionaryRef
)dictValues
[dex
];
1513 if((certDict
== NULL
) || (CFGetTypeID(certDict
) != CFDictionaryGetTypeID())) {
1514 trustSettingsDbg("TrustSettings::validatePropList: malformed certDict");
1515 abort("malformed certDict", errSecInvalidTrustedRootRecord
);
1519 * That dictionary has exactly four entries.
1520 * If we're trimming, all we need is the actual trust settings.
1524 CFDataRef cfd
= (CFDataRef
)CFDictionaryGetValue(certDict
, kTrustRecordIssuer
);
1526 trustSettingsDbg("TrustSettings::validatePropList: missing issuer");
1527 abort("missing issuer", errSecInvalidTrustedRootRecord
);
1529 if(CFGetTypeID(cfd
) != CFDataGetTypeID()) {
1530 trustSettingsDbg("TrustSettings::validatePropList: malformed issuer");
1531 abort("malformed issuer", errSecInvalidTrustedRootRecord
);
1534 CFDictionaryRemoveValue(certDict
, kTrustRecordIssuer
);
1538 cfd
= (CFDataRef
)CFDictionaryGetValue(certDict
, kTrustRecordSerialNumber
);
1540 trustSettingsDbg("TrustSettings::validatePropList: missing serial number");
1541 abort("missing serial number", errSecInvalidTrustedRootRecord
);
1543 if(CFGetTypeID(cfd
) != CFDataGetTypeID()) {
1544 trustSettingsDbg("TrustSettings::validatePropList: malformed serial number");
1545 abort("malformed serial number", errSecInvalidTrustedRootRecord
);
1548 CFDictionaryRemoveValue(certDict
, kTrustRecordSerialNumber
);
1551 /* modification date */
1552 CFDateRef modDate
= (CFDateRef
)CFDictionaryGetValue(certDict
, kTrustRecordModDate
);
1553 if(modDate
== NULL
) {
1554 trustSettingsDbg("TrustSettings::validatePropList: missing modDate");
1555 abort("missing modDate", errSecInvalidTrustedRootRecord
);
1557 if(CFGetTypeID(modDate
) != CFDateGetTypeID()) {
1558 trustSettingsDbg("TrustSettings::validatePropList: malformed modDate");
1559 abort("malformed modDate", errSecInvalidTrustedRootRecord
);
1562 CFDictionaryRemoveValue(certDict
, kTrustRecordModDate
);
1565 /* the actual trust settings */
1566 CFArrayRef trustSettings
= (CFArrayRef
)CFDictionaryGetValue(certDict
,
1567 kTrustRecordTrustSettings
);
1568 if(trustSettings
== NULL
) {
1569 /* optional; this cert's entry is good */
1572 if(CFGetTypeID(trustSettings
) != CFArrayGetTypeID()) {
1573 trustSettingsDbg("TrustSettings::validatePropList: malformed useConstraint"
1575 abort("malformed useConstraint array", errSecInvalidTrustedRootRecord
);
1578 /* Now validate the usageConstraint array contents */
1579 if(!validateTrustSettingsArray(trustSettings
)) {
1580 abort("malformed useConstraint array", errSecInvalidTrustedRootRecord
);
1582 } /* for each cert dictionary in top-level array */
1585 /* we don't need the top-level dictionary any more */
1586 CFRelease(mPropList
);
1592 * Obtain non-normalized issuer and serial number for specified cert, both
1593 * returned as CFDataRefs owned by caller.
1595 void TrustSettings::copyIssuerAndSerial(
1596 SecCertificateRef certRef
,
1597 CFDataRef
*issuer
, /* optional, RETURNED */
1598 CFDataRef
*serial
) /* RETURNED */
1601 CFRef
<SecCertificateRef
> certificate
= SecCertificateCreateItemImplInstance(certRef
);
1603 CFRef
<SecCertificateRef
> certificate
= (SecCertificateRef
) ((certRef
) ? CFRetain(certRef
) : NULL
);
1606 SecPointer
<Certificate
> cert
= Certificate::required(certificate
);
1607 CSSM_DATA_PTR fieldVal
;
1609 if(issuer
!= NULL
) {
1610 fieldVal
= cert
->copyFirstFieldValue(CSSMOID_X509V1IssuerNameStd
);
1611 *issuer
= CFDataCreate(NULL
, fieldVal
->Data
, fieldVal
->Length
);
1612 cert
->releaseFieldValue(CSSMOID_X509V1IssuerNameStd
, fieldVal
);
1615 fieldVal
= cert
->copyFirstFieldValue(CSSMOID_X509V1SerialNumber
);
1616 *serial
= CFDataCreate(NULL
, fieldVal
->Data
, fieldVal
->Length
);
1617 cert
->releaseFieldValue(CSSMOID_X509V1SerialNumber
, fieldVal
);
1620 void TrustSettings::abort(
1624 Syslog::error("TrustSettings: %s", why
);
1625 MacOSError::throwMe(err
);