]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/lib/SecTrustSettings.cpp
Security-57337.50.23.tar.gz
[apple/security.git] / OSX / libsecurity_keychain / lib / SecTrustSettings.cpp
1 /*
2 * Copyright (c) 2005,2011-2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * SecTrustSettings.cpp - Public interface for manipulation of Trust Settings.
26 *
27 */
28
29 #include "SecBridge.h"
30 #include "SecCertificatePriv.h"
31 #include "SecTrustSettings.h"
32 #include "SecTrustSettingsPriv.h"
33 #include "SecTrustSettingsCertificates.h"
34 #include "TrustSettingsUtils.h"
35 #include "TrustSettings.h"
36 #include "TrustSettingsSchema.h"
37 #include "TrustKeychains.h"
38 #include "Trust.h"
39 #include "SecKeychainPriv.h"
40 #include "Globals.h"
41 #include <security_utilities/threading.h>
42 #include <security_utilities/globalizer.h>
43 #include <security_utilities/errors.h>
44 #include <security_cdsa_utilities/cssmerrors.h>
45 #include <security_utilities/logging.h>
46 #include <security_utilities/debugging.h>
47 #include <security_utilities/simpleprefs.h>
48 #include <securityd_client/dictionary.h>
49 #include <securityd_client/ssclient.h>
50 #include <assert.h>
51 #include <dlfcn.h>
52 #include <libproc.h>
53 #include <syslog.h>
54 #include <vector>
55 #include <CommonCrypto/CommonDigest.h>
56 #include <CoreFoundation/CFPreferences.h>
57 #include <CoreServices/CoreServicesPriv.h> /* for _CSCheckFix */
58
59 #define trustSettingsDbg(args...) secdebug("trustSettings", ## args)
60
61 /*
62 * Ideally we'd like to implement our own lock to protect the state of the cert stores
63 * without grabbing the global Sec API lock, but we deal with SecCFObjects, so we'll have
64 * to bite the bullet and grab the big lock. We also have our own lock protecting the
65 * global trust settings cache which is also used by the keychain callback function
66 * (which does not grab the Sec API lock).
67 */
68
69 #define BEGIN_RCSAPI \
70 OSStatus __secapiresult; \
71 try {
72 #define END_RCSAPI \
73 __secapiresult=errSecSuccess; \
74 } \
75 catch (const MacOSError &err) { __secapiresult=err.osStatus(); } \
76 catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } \
77 catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } \
78 catch (...) { __secapiresult=errSecInternalComponent; } \
79 return __secapiresult;
80
81 #define END_RCSAPI0 \
82 catch (...) {} \
83 return;
84
85
86 #pragma mark --- TrustSettings preferences ---
87
88 /*
89 * If Colonel Klink wants to disable user-level Trust Settings, he'll have
90 * to restart the apps which will be affected after he does so. We are not
91 * going to consult system prefs every time we do a cert evaluation. We
92 * consult it once per process and cache the results here.
93 */
94 static bool tsUserTrustDisableValid = false; /* true once we consult prefs */
95 static bool tsUserTrustDisable = false; /* the cached value */
96
97 /*
98 * Determine whether user-level Trust Settings disabled.
99 */
100 static bool tsUserTrustSettingsDisabled()
101 {
102 if(tsUserTrustDisableValid) {
103 return tsUserTrustDisable;
104 }
105 tsUserTrustDisable = false;
106
107 Dictionary* dictionary = Dictionary::CreateDictionary(kSecTrustSettingsPrefsDomain, Dictionary::US_System);
108 if (dictionary)
109 {
110 auto_ptr<Dictionary> prefsDict(dictionary);
111 /* this returns false if the pref isn't there, just like we want */
112 tsUserTrustDisable = prefsDict->getBoolValue(kSecTrustSettingsDisableUserTrustSettings);
113 }
114
115 tsUserTrustDisableValid = true;
116 return tsUserTrustDisable;
117 }
118
119 #pragma mark --- TrustSettings global cache ---
120
121 /***
122 *** cache submodule - keeps per-app copy of zero or one TrustSettings
123 *** for each domain. Used only by SecTrustSettingsEvaluateCert()
124 *** and SecTrustSettingsCopyQualifiedCerts(); results of
125 *** manipulation by public API functions are not cached.
126 ***/
127
128 /*
129 * API/client code has to hold this lock when doing anything with any of
130 * the TrustSettings maintained here.
131 * It's recursive to accomodate CodeSigning's need to do cert verification
132 * (while we evaluate app equivalence).
133 */
134 static ModuleNexus<RecursiveMutex> sutCacheLock;
135
136 #define TRUST_SETTINGS_NUM_DOMAINS 3
137
138 /*
139 * The three global TrustSettings.
140 * We rely on the fact the the domain enums start with 0; we use
141 * the domain value as an index into the following two arrays.
142 */
143 static TrustSettings *globalTrustSettings[TRUST_SETTINGS_NUM_DOMAINS] =
144 {NULL, NULL, NULL};
145
146 /*
147 * Indicates "the associated global here is currently valid; if there isn't a
148 * globalTrustSettings[domain], don't try to find one"
149 */
150 static bool globalTrustSettingsValid[TRUST_SETTINGS_NUM_DOMAINS] =
151 {false, false, false};
152
153 /* remember the fact that we've registered our KC callback */
154 static bool sutRegisteredCallback = false;
155
156 static void tsRegisterCallback();
157
158 /*
159 * Assign global TrustSetting to new incoming value, which may be NULL.
160 * Caller holds sutCacheLock.
161 */
162 static void tsSetGlobalTrustSettings(
163 TrustSettings *ts,
164 SecTrustSettingsDomain domain)
165 {
166 assert(((int)domain >= 0) && ((int)domain < TRUST_SETTINGS_NUM_DOMAINS));
167
168 trustSettingsDbg("tsSetGlobalTrustSettings domain %d: caching TS %p old TS %p",
169 (int)domain, ts, globalTrustSettings[domain]);
170 delete globalTrustSettings[domain];
171 globalTrustSettings[domain] = ts;
172 globalTrustSettingsValid[domain] = ts ? true : false;
173 tsRegisterCallback();
174 }
175
176 /*
177 * Obtain global TrustSettings for specified domain if it exists.
178 * Returns NULL if there is simply no TS for that domain.
179 * The TS, if returned, belongs to this cache module.
180 * Caller holds sutCacheLock.
181 */
182 static TrustSettings *tsGetGlobalTrustSettings(
183 SecTrustSettingsDomain domain)
184 {
185 assert(((int)domain >= 0) && ((int)domain < TRUST_SETTINGS_NUM_DOMAINS));
186
187 if((domain == kSecTrustSettingsDomainUser) && tsUserTrustSettingsDisabled()) {
188 trustSettingsDbg("tsGetGlobalTrustSettings: skipping DISABLED user domain");
189 return NULL;
190 }
191
192 if(globalTrustSettingsValid[domain]) {
193 // ready or not, use this
194 return globalTrustSettings[domain];
195 }
196 assert(globalTrustSettings[domain] == NULL);
197
198 /* try to find one */
199 OSStatus result = errSecSuccess;
200 TrustSettings *ts = NULL;
201 /* don't create; trim if found */
202 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_YES, ts);
203 if ( (domain != kSecTrustSettingsDomainSystem)
204 && (result == errSecInternalComponent)) {
205 /*
206 * Could not connect to ocspd to get the user/admin domain trust settings
207 * This happens in single user mode for example.
208 * Valid flag is set to false and continue.
209 */
210 trustSettingsDbg("tsGetGlobalTrustSettings: could not connect to ocspd for domain (%d)",(int)domain);
211 globalTrustSettingsValid[domain] = false;
212 tsRegisterCallback();
213 return NULL;
214 }
215 else if (result == errSecNoTrustSettings) {
216 /*
217 * No TrustSettings for this domain, actually a fairly common case.
218 * Optimize: don't bother trying this again.
219 */
220 trustSettingsDbg("tsGetGlobalTrustSettings: flagging known NULL");
221 globalTrustSettingsValid[domain] = true;
222 tsRegisterCallback();
223 return NULL;
224 }
225 else if(result != errSecSuccess) {
226 /* gross error */
227 MacOSError::throwMe(result);
228 }
229
230 tsSetGlobalTrustSettings(ts, domain);
231 return ts;
232 }
233
234 /*
235 * Purge TrustSettings cache.
236 * Called by Keychain Event callback and by our API functions that
237 * modify trust settings.
238 * Caller can NOT hold sutCacheLock.
239 */
240 static void tsPurgeCache()
241 {
242 int domain;
243
244 StLock<Mutex> _(sutCacheLock());
245 trustSettingsDbg("tsPurgeCache");
246 for(domain=0; domain<TRUST_SETTINGS_NUM_DOMAINS; domain++) {
247 tsSetGlobalTrustSettings(NULL, domain);
248 }
249 }
250
251 /*
252 * Keychain event callback function, for notification by other processes that
253 * user trust list(s) has/have changed.
254 */
255 static OSStatus tsTrustSettingsCallback (
256 SecKeychainEvent keychainEvent,
257 SecKeychainCallbackInfo *info,
258 void *context)
259 {
260 trustSettingsDbg("tsTrustSettingsCallback, event %d", (int)keychainEvent);
261 if(keychainEvent != kSecTrustSettingsChangedEvent) {
262 /* should not happen, right? */
263 return errSecSuccess;
264 }
265 if(info->pid == getpid()) {
266 /*
267 * Avoid dup cache invalidates: we already dealt with this event.
268 */
269 trustSettingsDbg("cacheEventCallback: our pid, skipping");
270 }
271 else {
272 tsPurgeCache();
273 }
274 return errSecSuccess;
275 }
276
277 /*
278 * Ensure that we've registered for kSecTrustSettingsChangedEvent callbacks
279 */
280 static void tsRegisterCallback()
281 {
282 if(sutRegisteredCallback) {
283 return;
284 }
285 trustSettingsDbg("tsRegisterCallback: registering callback");
286 OSStatus ortn = SecKeychainAddCallback(tsTrustSettingsCallback,
287 kSecTrustSettingsChangedEventMask, NULL);
288 if(ortn) {
289 trustSettingsDbg("tsRegisterCallback: SecKeychainAddCallback returned %d", (int)ortn);
290 /* Not sure how this could ever happen - maybe if there is no run loop active? */
291 }
292 sutRegisteredCallback = true;
293 }
294
295 #pragma mark --- Static functions ---
296
297
298 /*
299 * Called by API code when a trust list has changed; we notify other processes
300 * and purge our own cache.
301 */
302 static void tsTrustSettingsChanged()
303 {
304 tsPurgeCache();
305
306 /* The only interesting data is our pid */
307 NameValueDictionary nvd;
308 pid_t ourPid = getpid();
309 nvd.Insert (new NameValuePair (PID_KEY,
310 CssmData (reinterpret_cast<void*>(&ourPid), sizeof (pid_t))));
311 CssmData data;
312 nvd.Export (data);
313
314 trustSettingsDbg("tsTrustSettingsChanged: posting notification");
315 SecurityServer::ClientSession cs (Allocator::standard(), Allocator::standard());
316 cs.postNotification (SecurityServer::kNotificationDomainDatabase,
317 kSecTrustSettingsChangedEvent, data);
318 free (data.data ());
319 }
320
321 /*
322 * Common code for SecTrustSettingsCopyTrustSettings(),
323 * SecTrustSettingsCopyModificationDate().
324 */
325 static OSStatus tsCopyTrustSettings(
326 SecCertificateRef cert,
327 SecTrustSettingsDomain domain,
328 CFArrayRef *trustSettings, /* optionally RETURNED */
329 CFDateRef *modDate) /* optionally RETURNED */
330 {
331 BEGIN_RCSAPI
332
333 TS_REQUIRED(cert)
334
335 /* obtain fresh full copy from disk */
336 OSStatus result;
337 TrustSettings* ts;
338
339 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
340
341 // rather than throw these results, just return them because we are at the top level
342 if (result == errSecNoTrustSettings) {
343 return errSecItemNotFound;
344 }
345 else if (result != errSecSuccess) {
346 return result;
347 }
348
349 auto_ptr<TrustSettings>_(ts); // make sure this gets deleted just in case something throws underneath
350
351 if(trustSettings) {
352 *trustSettings = ts->copyTrustSettings(cert);
353 }
354 if(modDate) {
355 *modDate = ts->copyModDate(cert);
356 }
357
358 END_RCSAPI
359 }
360
361 static void tsAddConditionalCerts(CFMutableArrayRef certArray);
362
363 /*
364 * Common code for SecTrustSettingsCopyQualifiedCerts() and
365 * SecTrustSettingsCopyUnrestrictedRoots().
366 */
367 static OSStatus tsCopyCertsCommon(
368 /* usage constraints, all optional */
369 const CSSM_OID *policyOID,
370 const char *policyString,
371 SecTrustSettingsKeyUsage keyUsage,
372 /* constrain to only roots */
373 bool onlyRoots,
374 /* per-domain enables */
375 bool user,
376 bool admin,
377 bool system,
378 CFArrayRef *certArray) /* RETURNED */
379 {
380 StLock<Mutex> _TC(sutCacheLock());
381 StLock<Mutex> _TK(SecTrustKeychainsGetMutex());
382
383 TS_REQUIRED(certArray)
384
385 /* this relies on the domain enums being numbered 0..2, user..system */
386 bool domainEnable[3] = {user, admin, system};
387
388 /* we'll retain it again before successful exit */
389 CFRef<CFMutableArrayRef> outArray(CFArrayCreateMutable(NULL, 0,
390 &kCFTypeArrayCallBacks));
391
392 /*
393 * Search all keychains - user's, System.keychain, system root store,
394 * system intermdiates as appropriate
395 */
396 StorageManager::KeychainList keychains;
397 Keychain adminKc;
398 if(user) {
399 globals().storageManager.getSearchList(keychains);
400 }
401 if(user || admin) {
402 adminKc = globals().storageManager.make(ADMIN_CERT_STORE_PATH, false);
403 keychains.push_back(adminKc);
404 }
405 Keychain sysRootKc = globals().storageManager.make(SYSTEM_ROOT_STORE_PATH, false);
406 keychains.push_back(sysRootKc);
407 Keychain sysCertKc = globals().storageManager.make(SYSTEM_CERT_STORE_PATH, false);
408 keychains.push_back(sysCertKc);
409
410 assert(kSecTrustSettingsDomainUser == 0);
411 for(unsigned domain=0; domain<TRUST_SETTINGS_NUM_DOMAINS; domain++) {
412 if(!domainEnable[domain]) {
413 continue;
414 }
415 TrustSettings *ts = tsGetGlobalTrustSettings(domain);
416 if(ts == NULL) {
417 continue;
418 }
419 ts->findQualifiedCerts(keychains,
420 false, /* !findAll */
421 onlyRoots,
422 policyOID, policyString, keyUsage,
423 outArray);
424 }
425 if (system) {
426 tsAddConditionalCerts(outArray);
427 }
428 *certArray = outArray;
429 CFRetain(*certArray);
430 trustSettingsDbg("tsCopyCertsCommon: %ld certs found",
431 CFArrayGetCount(outArray));
432 return errSecSuccess;
433 }
434
435 #if TARGET_OS_MAC && !TARGET_IPHONE_SIMULATOR && !TARGET_OS_IPHONE && !TARGET_OS_NANO
436 /*
437 * _CSCheckFix is implemented in CarbonCore and exported via CoreServices.
438 * To avoid a circular dependency with Security, load this symbol dynamically.
439 */
440 typedef Boolean (*CSCheckFix_f)(CFStringRef str);
441
442 static dispatch_once_t sTSInitializeOnce = 0;
443 static void * sCSCheckFixLibrary = NULL;
444 static CSCheckFix_f sCSCheckFix_f = NULL;
445
446 static OSStatus _tsEnsuredInitialized(void);
447
448 static OSStatus _tsEnsuredInitialized(void)
449 {
450 __block OSStatus status = errSecNotAvailable;
451
452 dispatch_once(&sTSInitializeOnce, ^{
453 sCSCheckFixLibrary = dlopen("/System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Versions/A/CarbonCore", RTLD_LAZY | RTLD_LOCAL);
454 assert(sCSCheckFixLibrary);
455 if (sCSCheckFixLibrary) {
456 sCSCheckFix_f = (CSCheckFix_f)(uintptr_t) dlsym(sCSCheckFixLibrary, "_CSCheckFix");
457 }
458 });
459
460 if (sCSCheckFix_f) {
461 status = noErr;
462 }
463 return status;
464 }
465 #endif
466
467 static void tsAddConditionalCerts(CFMutableArrayRef certArray)
468 {
469 #if TARGET_OS_MAC && !TARGET_IPHONE_SIMULATOR && !TARGET_OS_IPHONE && !TARGET_OS_NANO
470 struct certmap_entry_s {
471 const UInt8* data;
472 const CFIndex length;
473 };
474 typedef struct certmap_entry_s certmap_entry_t;
475
476 if (!certArray) { return; }
477
478 OSStatus status = _tsEnsuredInitialized();
479 if (status == 0 && sCSCheckFix_f(CFSTR("21946795"))) {
480 // conditionally include these 1024-bit roots
481 const certmap_entry_t certmap[] = {
482 { _EquifaxSecureCA, sizeof(_EquifaxSecureCA) },
483 { _GTECyberTrustGlobalRootCA, sizeof(_GTECyberTrustGlobalRootCA) },
484 { _ThawtePremiumServerCA, sizeof(_ThawtePremiumServerCA) },
485 { _ThawteServerCA, sizeof(_ThawteServerCA) },
486 { _VeriSignClass3CA, sizeof(_VeriSignClass3CA) },
487 };
488 unsigned int i, certmaplen = sizeof(certmap) / sizeof(certmap_entry_t);
489 for (i=0; i<certmaplen; i++) {
490 SecCertificateRef cert = SecCertificateCreateWithBytes(NULL,
491 certmap[i].data, certmap[i].length);
492 if (cert) {
493 CFArrayAppendValue(certArray, cert);
494 CFRelease(cert);
495 cert = NULL;
496 }
497 }
498 }
499 #else
500 // this function is a no-op on iOS platforms
501 #endif
502 }
503
504
505 #pragma mark --- SPI functions ---
506
507
508 /*
509 * Fundamental routine used by TP to ascertain status of one cert.
510 *
511 * Returns true in *foundMatchingEntry if a trust setting matching
512 * specific constraints was found for the cert. Returns true in
513 * *foundAnyEntry if any entry was found for the cert, even if it
514 * did not match the specified constraints. The TP uses this to
515 * optimize for the case where a cert is being evaluated for
516 * one type of usage, and then later for another type. If
517 * foundAnyEntry is false, the second evaluation need not occur.
518 *
519 * Returns the domain in which a setting was found in *foundDomain.
520 *
521 * Allowed errors applying to the specified cert evaluation
522 * are returned in a mallocd array in *allowedErrors and must
523 * be freed by caller.
524 *
525 * The design of the entire TrustSettings module is centered around
526 * optimizing the performance of this routine (security concerns
527 * aside, that is). It's why the per-cert dictionaries are stored
528 * as a dictionary, keyed off of the cert hash. It's why TrustSettings
529 * are cached in memory by tsGetGlobalTrustSettings(), and why those
530 * cached TrustSettings objects are 'trimmed' of dictionary fields
531 * which are not needed to verify a cert.
532 *
533 * The API functions which are used to manipulate Trust Settings
534 * are called infrequently and need not be particularly fast since
535 * they result in user interaction for authentication. Thus they do
536 * not use cached TrustSettings as this function does.
537 */
538 OSStatus SecTrustSettingsEvaluateCert(
539 CFStringRef certHashStr,
540 /* parameters describing the current cert evalaution */
541 const CSSM_OID *policyOID,
542 const char *policyString, /* optional */
543 uint32 policyStringLen,
544 SecTrustSettingsKeyUsage keyUsage, /* optional */
545 bool isRootCert, /* for checking default setting */
546 /* RETURNED values */
547 SecTrustSettingsDomain *foundDomain,
548 CSSM_RETURN **allowedErrors, /* mallocd */
549 uint32 *numAllowedErrors,
550 SecTrustSettingsResult *resultType,
551 bool *foundMatchingEntry,
552 bool *foundAnyEntry)
553 {
554 BEGIN_RCSAPI
555
556 StLock<Mutex> _(sutCacheLock());
557
558 TS_REQUIRED(certHashStr)
559 TS_REQUIRED(foundDomain)
560 TS_REQUIRED(allowedErrors)
561 TS_REQUIRED(numAllowedErrors)
562 TS_REQUIRED(resultType)
563 TS_REQUIRED(foundMatchingEntry)
564 TS_REQUIRED(foundAnyEntry)
565
566 /* ensure a NULL_terminated string */
567 auto_array<char> polStr;
568 if(policyString != NULL && policyStringLen > 0) {
569 polStr.allocate(policyStringLen + 1);
570 memmove(polStr.get(), policyString, policyStringLen);
571 if(policyString[policyStringLen - 1] != '\0') {
572 (polStr.get())[policyStringLen] = '\0';
573 }
574 }
575
576 /* initial condition - this can grow if we inspect multiple TrustSettings */
577 *allowedErrors = NULL;
578 *numAllowedErrors = 0;
579
580 /*
581 * This loop relies on the ordering of the SecTrustSettingsDomain enum:
582 * search user first, then admin, then system.
583 */
584 assert(kSecTrustSettingsDomainAdmin == (kSecTrustSettingsDomainUser + 1));
585 assert(kSecTrustSettingsDomainSystem == (kSecTrustSettingsDomainAdmin + 1));
586 bool foundAny = false;
587 for(unsigned domain=kSecTrustSettingsDomainUser;
588 domain<=kSecTrustSettingsDomainSystem;
589 domain++) {
590 TrustSettings *ts = tsGetGlobalTrustSettings(domain);
591 if(ts == NULL) {
592 continue;
593 }
594
595 /* validate cert returns true if matching entry was found */
596 bool foundAnyHere = false;
597 bool found = ts->evaluateCert(certHashStr, policyOID,
598 polStr.get(), keyUsage, isRootCert,
599 allowedErrors, numAllowedErrors, resultType, &foundAnyHere);
600
601 if(found) {
602 /*
603 * Note this, even though we may overwrite it later if this
604 * is an Unspecified entry and we find a definitive entry
605 * later
606 */
607 *foundDomain = domain;
608 }
609 if(found && (*resultType != kSecTrustSettingsResultUnspecified)) {
610 trustSettingsDbg("SecTrustSettingsEvaluateCert: found in domain %d", domain);
611 *foundAnyEntry = true;
612 *foundMatchingEntry = true;
613 return errSecSuccess;
614 }
615 foundAny |= foundAnyHere;
616 }
617 trustSettingsDbg("SecTrustSettingsEvaluateCert: NOT FOUND");
618 *foundAnyEntry = foundAny;
619 *foundMatchingEntry = false;
620 return errSecSuccess;
621 END_RCSAPI
622 }
623
624 /*
625 * Obtain trusted certs which match specified usage.
626 * Only certs with a SecTrustSettingsResult of
627 * kSecTrustSettingsResultTrustRoot or
628 * or kSecTrustSettingsResultTrustAsRoot will be returned.
629 * To be used by SecureTransport for its SSLSetTrustedRoots() call;
630 * I hope nothing else has to use this...
631 * Caller must CFRelease the returned CFArrayRef.
632 */
633 OSStatus SecTrustSettingsCopyQualifiedCerts(
634 const CSSM_OID *policyOID,
635 const char *policyString, /* optional */
636 uint32 policyStringLen,
637 SecTrustSettingsKeyUsage keyUsage, /* optional */
638 CFArrayRef *certArray) /* RETURNED */
639 {
640 BEGIN_RCSAPI
641
642 /* ensure a NULL_terminated string */
643 auto_array<char> polStr;
644 if(policyString != NULL) {
645 polStr.allocate(policyStringLen + 1);
646 memmove(polStr.get(), policyString, policyStringLen);
647 if(policyString[policyStringLen - 1] != '\0') {
648 (polStr.get())[policyStringLen] = '\0';
649 }
650 }
651
652 return tsCopyCertsCommon(policyOID, polStr.get(), keyUsage,
653 false, /* !onlyRoots */
654 true, true, true, /* all domains */
655 certArray);
656
657 END_RCSAPI
658 }
659
660 /*
661 * Obtain unrestricted root certs from the specified domain(s).
662 * Only returns roots with no usage constraints.
663 * Caller must CFRelease the returned CFArrayRef.
664 */
665 OSStatus SecTrustSettingsCopyUnrestrictedRoots(
666 Boolean user,
667 Boolean admin,
668 Boolean system,
669 CFArrayRef *certArray) /* RETURNED */
670 {
671 BEGIN_RCSAPI
672
673 return tsCopyCertsCommon(NULL, NULL, NULL, /* no constraints */
674 true, /* onlyRoots */
675 user, admin, system,
676 certArray);
677
678 END_RCSAPI
679 }
680
681 static const char hexChars[16] = {
682 '0', '1', '2', '3', '4', '5', '6', '7',
683 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
684 };
685
686 /*
687 * Obtain a string representing a cert's SHA1 digest. This string is
688 * the key used to look up per-cert trust settings in a TrustSettings record.
689 */
690 CFStringRef SecTrustSettingsCertHashStrFromCert(
691 SecCertificateRef certRef)
692 {
693 if(certRef == NULL) {
694 return NULL;
695 }
696
697 if(certRef == kSecTrustSettingsDefaultRootCertSetting) {
698 /* use this string instead of the cert hash as the dictionary key */
699 trustSettingsDbg("SecTrustSettingsCertHashStrFromCert: DefaultSetting");
700 return kSecTrustRecordDefaultRootCert;
701 }
702
703 CSSM_DATA certData;
704 OSStatus ortn = SecCertificateGetData(certRef, &certData);
705 if(ortn) {
706 return NULL;
707 }
708 return SecTrustSettingsCertHashStrFromData(certData.Data, certData.Length);
709 }
710
711 CFStringRef SecTrustSettingsCertHashStrFromData(
712 const void *cert,
713 size_t certLen)
714 {
715 unsigned char digest[CC_SHA1_DIGEST_LENGTH];
716 char asciiDigest[(2 * CC_SHA1_DIGEST_LENGTH) + 1];
717 unsigned dex;
718 char *outp = asciiDigest;
719 unsigned char *inp = digest;
720
721 if(cert == NULL) {
722 return NULL;
723 }
724
725 CC_SHA1(cert, (CC_LONG)certLen, digest);
726
727 for(dex=0; dex<CC_SHA1_DIGEST_LENGTH; dex++) {
728 unsigned c = *inp++;
729 outp[1] = hexChars[c & 0xf];
730 c >>= 4;
731 outp[0] = hexChars[c];
732 outp += 2;
733 }
734 *outp = 0;
735 return CFStringCreateWithCString(NULL, asciiDigest, kCFStringEncodingASCII);
736 }
737
738 /*
739 * Add a cert's TrustSettings to a non-persistent TrustSettings record.
740 * No locking or cache flushing here; it's all local to the TrustSettings
741 * we construct here.
742 */
743 OSStatus SecTrustSettingsSetTrustSettingsExternal(
744 CFDataRef settingsIn, /* optional */
745 SecCertificateRef certRef, /* optional */
746 CFTypeRef trustSettingsDictOrArray, /* optional */
747 CFDataRef *settingsOut) /* RETURNED */
748 {
749 BEGIN_RCSAPI
750
751 TS_REQUIRED(settingsOut)
752
753 OSStatus result;
754 TrustSettings* ts;
755
756 result = TrustSettings::CreateTrustSettings(kSecTrustSettingsDomainMemory, settingsIn, ts);
757 if (result != errSecSuccess) {
758 return result;
759 }
760
761 auto_ptr<TrustSettings>_(ts);
762
763 if(certRef != NULL) {
764 ts->setTrustSettings(certRef, trustSettingsDictOrArray);
765 }
766 *settingsOut = ts->createExternal();
767 return errSecSuccess;
768
769 END_RCSAPI
770 }
771
772 #pragma mark --- API functions ---
773
774 OSStatus SecTrustSettingsCopyTrustSettings(
775 SecCertificateRef certRef,
776 SecTrustSettingsDomain domain,
777 CFArrayRef *trustSettings) /* RETURNED */
778 {
779 TS_REQUIRED(certRef)
780 TS_REQUIRED(trustSettings)
781
782 OSStatus result = tsCopyTrustSettings(certRef, domain, trustSettings, NULL);
783 if (result == errSecSuccess && *trustSettings == NULL) {
784 result = errSecItemNotFound; /* documented result if no trust settings exist */
785 }
786 return result;
787 }
788
789 OSStatus SecTrustSettingsCopyModificationDate(
790 SecCertificateRef certRef,
791 SecTrustSettingsDomain domain,
792 CFDateRef *modificationDate) /* RETURNED */
793 {
794 TS_REQUIRED(certRef)
795 TS_REQUIRED(modificationDate)
796
797 OSStatus result = tsCopyTrustSettings(certRef, domain, NULL, modificationDate);
798 if (result == errSecSuccess && *modificationDate == NULL) {
799 result = errSecItemNotFound; /* documented result if no trust settings exist */
800 }
801 return result;
802 }
803
804 /* works with existing and with new cert */
805 OSStatus SecTrustSettingsSetTrustSettings(
806 SecCertificateRef certRef,
807 SecTrustSettingsDomain domain,
808 CFTypeRef trustSettingsDictOrArray)
809 {
810 BEGIN_RCSAPI
811
812 TS_REQUIRED(certRef)
813
814 if(domain == kSecTrustSettingsDomainSystem) {
815 return errSecDataNotModifiable;
816 }
817
818 OSStatus result;
819 TrustSettings* ts;
820
821 result = TrustSettings::CreateTrustSettings(domain, CREATE_YES, TRIM_NO, ts);
822 if (result != errSecSuccess) {
823 return result;
824 }
825
826 auto_ptr<TrustSettings>_(ts);
827
828 ts->setTrustSettings(certRef, trustSettingsDictOrArray);
829 ts->flushToDisk();
830 tsTrustSettingsChanged();
831 return errSecSuccess;
832
833 END_RCSAPI
834 }
835
836 OSStatus SecTrustSettingsRemoveTrustSettings(
837 SecCertificateRef cert,
838 SecTrustSettingsDomain domain)
839 {
840 BEGIN_RCSAPI
841
842 TS_REQUIRED(cert)
843
844 if(domain == kSecTrustSettingsDomainSystem) {
845 return errSecDataNotModifiable;
846 }
847
848 OSStatus result;
849 TrustSettings* ts;
850
851 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
852 if (result != errSecSuccess) {
853 return result;
854 }
855
856 auto_ptr<TrustSettings>_(ts);
857
858 /* deleteTrustSettings throws if record not found */
859 trustSettingsDbg("SecTrustSettingsRemoveTrustSettings: deleting from domain %d",
860 (int)domain);
861 ts->deleteTrustSettings(cert);
862 ts->flushToDisk();
863 tsTrustSettingsChanged();
864 return errSecSuccess;
865
866 END_RCSAPI
867 }
868
869 /* get all certs listed in specified domain */
870 OSStatus SecTrustSettingsCopyCertificates(
871 SecTrustSettingsDomain domain,
872 CFArrayRef *certArray)
873 {
874 BEGIN_RCSAPI
875
876 TS_REQUIRED(certArray)
877
878 OSStatus result;
879 TrustSettings* ts;
880
881 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
882 if (result != errSecSuccess) {
883 return result;
884 }
885
886 auto_ptr<TrustSettings>_(ts);
887
888 CFMutableArrayRef outArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
889
890 /*
891 * Keychains to search: user's search list, System.keychain, system root store,
892 * system intermediates, as appropriate
893 */
894 StorageManager::KeychainList keychains;
895 Keychain adminKc;
896 Keychain sysCertKc;
897 Keychain sysRootKc;
898 switch(domain) {
899 case kSecTrustSettingsDomainUser:
900 /* user search list */
901 globals().storageManager.getSearchList(keychains);
902 /* drop thru to next case */
903 case kSecTrustSettingsDomainAdmin:
904 /* admin certs in system keychain */
905 adminKc = globals().storageManager.make(ADMIN_CERT_STORE_PATH, false);
906 keychains.push_back(adminKc);
907 /* system-wide intermediate certs */
908 sysCertKc = globals().storageManager.make(SYSTEM_CERT_STORE_PATH, false);
909 keychains.push_back(sysCertKc);
910 /* drop thru to next case */
911 case kSecTrustSettingsDomainSystem:
912 /* and, for all cases, immutable system root store */
913 sysRootKc = globals().storageManager.make(SYSTEM_ROOT_STORE_PATH, false);
914 keychains.push_back(sysRootKc);
915 default:
916 /* already validated when we created the TrustSettings */
917 break;
918 }
919 ts->findCerts(keychains, outArray);
920 if(CFArrayGetCount(outArray) == 0) {
921 CFRelease(outArray);
922 return errSecNoTrustSettings;
923 }
924 tsAddConditionalCerts(outArray);
925 *certArray = outArray;
926 END_RCSAPI
927 }
928
929 /*
930 * Obtain an external, portable representation of the specified
931 * domain's TrustSettings. Caller must CFRelease the returned data.
932 */
933 OSStatus SecTrustSettingsCreateExternalRepresentation(
934 SecTrustSettingsDomain domain,
935 CFDataRef *trustSettings)
936 {
937 BEGIN_RCSAPI
938
939 TS_REQUIRED(trustSettings)
940
941 OSStatus result;
942 TrustSettings* ts;
943
944 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
945 if (result != errSecSuccess) {
946 return result;
947 }
948
949 auto_ptr<TrustSettings>_(ts);
950
951 *trustSettings = ts->createExternal();
952 return errSecSuccess;
953
954 END_RCSAPI
955 }
956
957 /*
958 * Import trust settings, obtained via SecTrustSettingsCreateExternalRepresentation,
959 * into the specified domain.
960 */
961 OSStatus SecTrustSettingsImportExternalRepresentation(
962 SecTrustSettingsDomain domain,
963 CFDataRef trustSettings) /* optional - NULL means empty settings */
964 {
965 BEGIN_RCSAPI
966
967 if(domain == kSecTrustSettingsDomainSystem) {
968 return errSecDataNotModifiable;
969 }
970
971 OSStatus result;
972 TrustSettings* ts;
973
974 result = TrustSettings::CreateTrustSettings(domain, trustSettings, ts);
975 if (result != errSecSuccess) {
976 return result;
977 }
978
979 auto_ptr<TrustSettings>_(ts);
980
981 ts->flushToDisk();
982 tsTrustSettingsChanged();
983 return errSecSuccess;
984
985 END_RCSAPI
986 }
987