]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/lib/SecTrustSettings.cpp
Security-57740.31.2.tar.gz
[apple/security.git] / OSX / libsecurity_keychain / lib / SecTrustSettings.cpp
1 /*
2 * Copyright (c) 2005,2011-2016 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 <utilities/SecCFRelease.h>
58
59 #define trustSettingsDbg(args...) secinfo("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 keychain list, System.keychain,
394 * and system root store
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
408 assert(kSecTrustSettingsDomainUser == 0);
409 for(unsigned domain=0; domain<TRUST_SETTINGS_NUM_DOMAINS; domain++) {
410 if(!domainEnable[domain]) {
411 continue;
412 }
413 TrustSettings *ts = tsGetGlobalTrustSettings(domain);
414 if(ts == NULL) {
415 continue;
416 }
417 ts->findQualifiedCerts(keychains,
418 false, /* !findAll */
419 onlyRoots,
420 policyOID, policyString, keyUsage,
421 outArray);
422 }
423 if (system) {
424 tsAddConditionalCerts(outArray);
425 }
426 *certArray = outArray;
427 CFRetain(*certArray);
428 trustSettingsDbg("tsCopyCertsCommon: %ld certs found",
429 CFArrayGetCount(outArray));
430 return errSecSuccess;
431 }
432
433 static void tsAddConditionalCerts(CFMutableArrayRef certArray)
434 {
435 #if TARGET_OS_MAC && !TARGET_IPHONE_SIMULATOR && !TARGET_OS_IPHONE && !TARGET_OS_NANO
436 struct certmap_entry_s {
437 CFStringRef bundleId;
438 const UInt8* data;
439 const CFIndex length;
440 };
441 typedef struct certmap_entry_s certmap_entry_t;
442
443 CFBundleRef bundle = CFBundleGetMainBundle();
444 CFStringRef bundleIdentifier = (bundle) ? CFBundleGetIdentifier(bundle) : NULL;
445 if (!bundleIdentifier || !certArray) { return; }
446
447 // conditionally include 1024-bit compatibility roots for specific apps
448 const certmap_entry_t certmap[] = {
449 { CFSTR("com.autodesk.AdSSO"), _GTECyberTrustGlobalRootCA, sizeof(_GTECyberTrustGlobalRootCA) }, // rdar://25916338
450 { CFSTR("com.clo3d.MD5"), _ThawtePremiumServerCA, sizeof(_ThawtePremiumServerCA) }, // rdar://26281864
451 };
452
453 unsigned int i, certmaplen = sizeof(certmap) / sizeof(certmap_entry_t);
454 for (i=0; i<certmaplen; i++) {
455 if (CFStringCompare(bundleIdentifier, certmap[i].bundleId, 0) == kCFCompareEqualTo) {
456 SecCertificateRef cert = SecCertificateCreateWithBytes(NULL, certmap[i].data, certmap[i].length);
457 if (!cert) { continue; }
458 CFArrayAppendValue(certArray, cert);
459 CFRelease(cert);
460 cert = NULL;
461 }
462 }
463 #else
464 // this function is a no-op on iOS platforms
465 #endif
466 }
467
468
469 #pragma mark --- SPI functions ---
470
471
472 /*
473 * Fundamental routine used by TP to ascertain status of one cert.
474 *
475 * Returns true in *foundMatchingEntry if a trust setting matching
476 * specific constraints was found for the cert. Returns true in
477 * *foundAnyEntry if any entry was found for the cert, even if it
478 * did not match the specified constraints. The TP uses this to
479 * optimize for the case where a cert is being evaluated for
480 * one type of usage, and then later for another type. If
481 * foundAnyEntry is false, the second evaluation need not occur.
482 *
483 * Returns the domain in which a setting was found in *foundDomain.
484 *
485 * Allowed errors applying to the specified cert evaluation
486 * are returned in a mallocd array in *allowedErrors and must
487 * be freed by caller.
488 *
489 * The design of the entire TrustSettings module is centered around
490 * optimizing the performance of this routine (security concerns
491 * aside, that is). It's why the per-cert dictionaries are stored
492 * as a dictionary, keyed off of the cert hash. It's why TrustSettings
493 * are cached in memory by tsGetGlobalTrustSettings(), and why those
494 * cached TrustSettings objects are 'trimmed' of dictionary fields
495 * which are not needed to verify a cert.
496 *
497 * The API functions which are used to manipulate Trust Settings
498 * are called infrequently and need not be particularly fast since
499 * they result in user interaction for authentication. Thus they do
500 * not use cached TrustSettings as this function does.
501 */
502 OSStatus SecTrustSettingsEvaluateCert(
503 CFStringRef certHashStr,
504 /* parameters describing the current cert evalaution */
505 const CSSM_OID *policyOID,
506 const char *policyString, /* optional */
507 uint32 policyStringLen,
508 SecTrustSettingsKeyUsage keyUsage, /* optional */
509 bool isRootCert, /* for checking default setting */
510 /* RETURNED values */
511 SecTrustSettingsDomain *foundDomain,
512 CSSM_RETURN **allowedErrors, /* mallocd */
513 uint32 *numAllowedErrors,
514 SecTrustSettingsResult *resultType,
515 bool *foundMatchingEntry,
516 bool *foundAnyEntry)
517 {
518 BEGIN_RCSAPI
519
520 StLock<Mutex> _(sutCacheLock());
521
522 TS_REQUIRED(certHashStr)
523 TS_REQUIRED(foundDomain)
524 TS_REQUIRED(allowedErrors)
525 TS_REQUIRED(numAllowedErrors)
526 TS_REQUIRED(resultType)
527 TS_REQUIRED(foundMatchingEntry)
528 TS_REQUIRED(foundAnyEntry)
529
530 /* ensure a NULL_terminated string */
531 auto_array<char> polStr;
532 if(policyString != NULL && policyStringLen > 0) {
533 polStr.allocate(policyStringLen + 1);
534 memmove(polStr.get(), policyString, policyStringLen);
535 if(policyString[policyStringLen - 1] != '\0') {
536 (polStr.get())[policyStringLen] = '\0';
537 }
538 }
539
540 /* initial condition - this can grow if we inspect multiple TrustSettings */
541 *allowedErrors = NULL;
542 *numAllowedErrors = 0;
543
544 /*
545 * This loop relies on the ordering of the SecTrustSettingsDomain enum:
546 * search user first, then admin, then system.
547 */
548 assert(kSecTrustSettingsDomainAdmin == (kSecTrustSettingsDomainUser + 1));
549 assert(kSecTrustSettingsDomainSystem == (kSecTrustSettingsDomainAdmin + 1));
550 bool foundAny = false;
551 for(unsigned domain=kSecTrustSettingsDomainUser;
552 domain<=kSecTrustSettingsDomainSystem;
553 domain++) {
554 TrustSettings *ts = tsGetGlobalTrustSettings(domain);
555 if(ts == NULL) {
556 continue;
557 }
558
559 /* validate cert returns true if matching entry was found */
560 bool foundAnyHere = false;
561 bool found = ts->evaluateCert(certHashStr, policyOID,
562 polStr.get(), keyUsage, isRootCert,
563 allowedErrors, numAllowedErrors, resultType, &foundAnyHere);
564
565 if(found) {
566 /*
567 * Note this, even though we may overwrite it later if this
568 * is an Unspecified entry and we find a definitive entry
569 * later
570 */
571 *foundDomain = domain;
572 }
573 if(found && (*resultType != kSecTrustSettingsResultUnspecified)) {
574 trustSettingsDbg("SecTrustSettingsEvaluateCert: found in domain %d", domain);
575 *foundAnyEntry = true;
576 *foundMatchingEntry = true;
577 return errSecSuccess;
578 }
579 foundAny |= foundAnyHere;
580 }
581 trustSettingsDbg("SecTrustSettingsEvaluateCert: NOT FOUND");
582 *foundAnyEntry = foundAny;
583 *foundMatchingEntry = false;
584 return errSecSuccess;
585 END_RCSAPI
586 }
587
588 /*
589 * Obtain trusted certs which match specified usage.
590 * Only certs with a SecTrustSettingsResult of
591 * kSecTrustSettingsResultTrustRoot or
592 * or kSecTrustSettingsResultTrustAsRoot will be returned.
593 * To be used by SecureTransport for its SSLSetTrustedRoots() call;
594 * I hope nothing else has to use this...
595 * Caller must CFRelease the returned CFArrayRef.
596 */
597 OSStatus SecTrustSettingsCopyQualifiedCerts(
598 const CSSM_OID *policyOID,
599 const char *policyString, /* optional */
600 uint32 policyStringLen,
601 SecTrustSettingsKeyUsage keyUsage, /* optional */
602 CFArrayRef *certArray) /* RETURNED */
603 {
604 BEGIN_RCSAPI
605
606 /* ensure a NULL_terminated string */
607 auto_array<char> polStr;
608 if(policyString != NULL) {
609 polStr.allocate(policyStringLen + 1);
610 memmove(polStr.get(), policyString, policyStringLen);
611 if(policyString[policyStringLen - 1] != '\0') {
612 (polStr.get())[policyStringLen] = '\0';
613 }
614 }
615
616 return tsCopyCertsCommon(policyOID, polStr.get(), keyUsage,
617 false, /* !onlyRoots */
618 true, true, true, /* all domains */
619 certArray);
620
621 END_RCSAPI
622 }
623
624 /*
625 * Obtain unrestricted root certs from the specified domain(s).
626 * Only returns roots with no usage constraints.
627 * Caller must CFRelease the returned CFArrayRef.
628 */
629 OSStatus SecTrustSettingsCopyUnrestrictedRoots(
630 Boolean user,
631 Boolean admin,
632 Boolean system,
633 CFArrayRef *certArray) /* RETURNED */
634 {
635 BEGIN_RCSAPI
636
637 OSStatus status = tsCopyCertsCommon(NULL, NULL, NULL, /* no constraints */
638 true, /* onlyRoots */
639 user, admin, system,
640 certArray);
641
642 return status;
643
644 END_RCSAPI
645 }
646
647 static const char hexChars[16] = {
648 '0', '1', '2', '3', '4', '5', '6', '7',
649 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
650 };
651
652 /*
653 * Obtain a string representing a cert's SHA1 digest. This string is
654 * the key used to look up per-cert trust settings in a TrustSettings record.
655 */
656 CFStringRef SecTrustSettingsCertHashStrFromCert(
657 SecCertificateRef certRef)
658 {
659 if(certRef == NULL) {
660 return NULL;
661 }
662
663 if(certRef == kSecTrustSettingsDefaultRootCertSetting) {
664 /* use this string instead of the cert hash as the dictionary key */
665 trustSettingsDbg("SecTrustSettingsCertHashStrFromCert: DefaultSetting");
666 return kSecTrustRecordDefaultRootCert;
667 }
668
669 CSSM_DATA certData;
670 OSStatus ortn = SecCertificateGetData(certRef, &certData);
671 if(ortn) {
672 return NULL;
673 }
674 return SecTrustSettingsCertHashStrFromData(certData.Data, certData.Length);
675 }
676
677 CFStringRef SecTrustSettingsCertHashStrFromData(
678 const void *cert,
679 size_t certLen)
680 {
681 unsigned char digest[CC_SHA1_DIGEST_LENGTH];
682 char asciiDigest[(2 * CC_SHA1_DIGEST_LENGTH) + 1];
683 unsigned dex;
684 char *outp = asciiDigest;
685 unsigned char *inp = digest;
686
687 if(cert == NULL) {
688 return NULL;
689 }
690
691 CC_SHA1(cert, (CC_LONG)certLen, digest);
692
693 for(dex=0; dex<CC_SHA1_DIGEST_LENGTH; dex++) {
694 unsigned c = *inp++;
695 outp[1] = hexChars[c & 0xf];
696 c >>= 4;
697 outp[0] = hexChars[c];
698 outp += 2;
699 }
700 *outp = 0;
701 return CFStringCreateWithCString(NULL, asciiDigest, kCFStringEncodingASCII);
702 }
703
704 /*
705 * Add a cert's TrustSettings to a non-persistent TrustSettings record.
706 * No locking or cache flushing here; it's all local to the TrustSettings
707 * we construct here.
708 */
709 OSStatus SecTrustSettingsSetTrustSettingsExternal(
710 CFDataRef settingsIn, /* optional */
711 SecCertificateRef certRef, /* optional */
712 CFTypeRef trustSettingsDictOrArray, /* optional */
713 CFDataRef *settingsOut) /* RETURNED */
714 {
715 BEGIN_RCSAPI
716
717 TS_REQUIRED(settingsOut)
718
719 OSStatus result;
720 TrustSettings* ts;
721
722 result = TrustSettings::CreateTrustSettings(kSecTrustSettingsDomainMemory, settingsIn, ts);
723 if (result != errSecSuccess) {
724 return result;
725 }
726
727 auto_ptr<TrustSettings>_(ts);
728
729 if(certRef != NULL) {
730 ts->setTrustSettings(certRef, trustSettingsDictOrArray);
731 }
732 *settingsOut = ts->createExternal();
733 return errSecSuccess;
734
735 END_RCSAPI
736 }
737
738 #pragma mark --- API functions ---
739
740 OSStatus SecTrustSettingsCopyTrustSettings(
741 SecCertificateRef certRef,
742 SecTrustSettingsDomain domain,
743 CFArrayRef *trustSettings) /* RETURNED */
744 {
745 TS_REQUIRED(certRef)
746 TS_REQUIRED(trustSettings)
747
748 OSStatus result = tsCopyTrustSettings(certRef, domain, trustSettings, NULL);
749 if (result == errSecSuccess && *trustSettings == NULL) {
750 result = errSecItemNotFound; /* documented result if no trust settings exist */
751 }
752 return result;
753 }
754
755 OSStatus SecTrustSettingsCopyModificationDate(
756 SecCertificateRef certRef,
757 SecTrustSettingsDomain domain,
758 CFDateRef *modificationDate) /* RETURNED */
759 {
760 TS_REQUIRED(certRef)
761 TS_REQUIRED(modificationDate)
762
763 OSStatus result = tsCopyTrustSettings(certRef, domain, NULL, modificationDate);
764 if (result == errSecSuccess && *modificationDate == NULL) {
765 result = errSecItemNotFound; /* documented result if no trust settings exist */
766 }
767 return result;
768 }
769
770 /* works with existing and with new cert */
771 OSStatus SecTrustSettingsSetTrustSettings(
772 SecCertificateRef certRef,
773 SecTrustSettingsDomain domain,
774 CFTypeRef trustSettingsDictOrArray)
775 {
776 BEGIN_RCSAPI
777
778 TS_REQUIRED(certRef)
779
780 if(domain == kSecTrustSettingsDomainSystem) {
781 return errSecDataNotModifiable;
782 }
783
784 OSStatus result;
785 TrustSettings* ts;
786
787 result = TrustSettings::CreateTrustSettings(domain, CREATE_YES, TRIM_NO, ts);
788 if (result != errSecSuccess) {
789 return result;
790 }
791
792 auto_ptr<TrustSettings>_(ts);
793
794 ts->setTrustSettings(certRef, trustSettingsDictOrArray);
795 ts->flushToDisk();
796 tsTrustSettingsChanged();
797 return errSecSuccess;
798
799 END_RCSAPI
800 }
801
802 OSStatus SecTrustSettingsRemoveTrustSettings(
803 SecCertificateRef cert,
804 SecTrustSettingsDomain domain)
805 {
806 BEGIN_RCSAPI
807
808 TS_REQUIRED(cert)
809
810 if(domain == kSecTrustSettingsDomainSystem) {
811 return errSecDataNotModifiable;
812 }
813
814 OSStatus result;
815 TrustSettings* ts;
816
817 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
818 if (result != errSecSuccess) {
819 return result;
820 }
821
822 auto_ptr<TrustSettings>_(ts);
823
824 /* deleteTrustSettings throws if record not found */
825 trustSettingsDbg("SecTrustSettingsRemoveTrustSettings: deleting from domain %d",
826 (int)domain);
827 ts->deleteTrustSettings(cert);
828 ts->flushToDisk();
829 tsTrustSettingsChanged();
830 return errSecSuccess;
831
832 END_RCSAPI
833 }
834
835 /* get all certs listed in specified domain */
836 OSStatus SecTrustSettingsCopyCertificates(
837 SecTrustSettingsDomain domain,
838 CFArrayRef *certArray)
839 {
840 BEGIN_RCSAPI
841
842 TS_REQUIRED(certArray)
843
844 OSStatus result;
845 TrustSettings* ts;
846
847 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
848 if (result != errSecSuccess) {
849 return result;
850 }
851
852 auto_ptr<TrustSettings>_(ts);
853
854 CFMutableArrayRef outArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
855
856 /*
857 * Keychains to search: user's search list, System.keychain, system root store
858 */
859 StorageManager::KeychainList keychains;
860 Keychain adminKc;
861 Keychain sysRootKc;
862 switch(domain) {
863 case kSecTrustSettingsDomainUser:
864 /* user search list */
865 globals().storageManager.getSearchList(keychains);
866 /* drop thru to next case */
867 case kSecTrustSettingsDomainAdmin:
868 /* admin certs in system keychain */
869 adminKc = globals().storageManager.make(ADMIN_CERT_STORE_PATH, false);
870 keychains.push_back(adminKc);
871 /* drop thru to next case */
872 case kSecTrustSettingsDomainSystem:
873 /* and, for all cases, immutable system root store */
874 sysRootKc = globals().storageManager.make(SYSTEM_ROOT_STORE_PATH, false);
875 keychains.push_back(sysRootKc);
876 default:
877 /* already validated when we created the TrustSettings */
878 break;
879 }
880 ts->findCerts(keychains, outArray);
881 if(CFArrayGetCount(outArray) == 0) {
882 CFRelease(outArray);
883 return errSecNoTrustSettings;
884 }
885 if (kSecTrustSettingsDomainSystem == domain) {
886 tsAddConditionalCerts(outArray);
887 }
888 *certArray = outArray;
889 END_RCSAPI
890 }
891
892 static CFArrayRef gUserAdminCerts = NULL;
893 static bool gUserAdminCertsCacheBuilt = false;
894 static ReadWriteLock gUserAdminCertsLock;
895
896 void SecTrustSettingsPurgeUserAdminCertsCache(void) {
897 StReadWriteLock _(gUserAdminCertsLock, StReadWriteLock::Write);
898 CFReleaseNull(gUserAdminCerts);
899 gUserAdminCertsCacheBuilt = false;
900 }
901
902 OSStatus SecTrustSettingsCopyCertificatesForUserAdminDomains(
903 CFArrayRef *certArray)
904 {
905 TS_REQUIRED(certArray);
906 OSStatus result = errSecSuccess;
907
908 { /* Hold the read lock for the check */
909 StReadWriteLock _(gUserAdminCertsLock, StReadWriteLock::Read);
910 if (gUserAdminCertsCacheBuilt) {
911 if (gUserAdminCerts) {
912 *certArray = (CFArrayRef)CFRetain(gUserAdminCerts);
913 return errSecSuccess;
914 } else {
915 return errSecNoTrustSettings;
916 }
917 }
918 }
919
920 /* There were no cached results. We'll have to recreate them. */
921 CFMutableArrayRef outArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
922 if (!outArray) {
923 return errSecAllocate;
924 }
925
926 CFArrayRef userTrusted = NULL, adminTrusted = NULL;
927 OSStatus userStatus = SecTrustSettingsCopyCertificates(kSecTrustSettingsDomainUser, &userTrusted);
928 if ((userStatus == errSecSuccess) && (userTrusted != NULL)) {
929 CFArrayAppendArray(outArray, userTrusted, CFRangeMake(0, CFArrayGetCount(userTrusted)));
930 CFRelease(userTrusted);
931 }
932
933 OSStatus adminStatus = SecTrustSettingsCopyCertificates(kSecTrustSettingsDomainAdmin, &adminTrusted);
934 if ((adminStatus == errSecSuccess) && (adminTrusted != NULL)) {
935 CFArrayAppendArray(outArray, adminTrusted, CFRangeMake(0, CFArrayGetCount(adminTrusted)));
936 CFRelease(adminTrusted);
937 }
938
939 /* Lack of trust settings for a domain results in an error above. Only fail
940 * if we weren't able to get trust settings for both domains. */
941 if (userStatus != errSecSuccess && adminStatus != errSecSuccess) {
942 result = userStatus;
943 }
944
945 if (result != errSecSuccess && outArray) {
946 CFRelease(outArray);
947 outArray = NULL;
948 }
949
950 *certArray = outArray;
951
952 /* For valid results, update the global cache */
953 if (result == errSecSuccess || result == errSecNoTrustSettings) {
954 StReadWriteLock _(gUserAdminCertsLock, StReadWriteLock::Write);
955 CFReleaseNull(gUserAdminCerts);
956 gUserAdminCerts = (CFArrayRef)CFRetainSafe(outArray);
957 gUserAdminCertsCacheBuilt = true;
958 }
959
960 return result;
961 }
962
963 /*
964 * Obtain an external, portable representation of the specified
965 * domain's TrustSettings. Caller must CFRelease the returned data.
966 */
967 OSStatus SecTrustSettingsCreateExternalRepresentation(
968 SecTrustSettingsDomain domain,
969 CFDataRef *trustSettings)
970 {
971 BEGIN_RCSAPI
972
973 TS_REQUIRED(trustSettings)
974
975 OSStatus result;
976 TrustSettings* ts;
977
978 result = TrustSettings::CreateTrustSettings(domain, CREATE_NO, TRIM_NO, ts);
979 if (result != errSecSuccess) {
980 return result;
981 }
982
983 auto_ptr<TrustSettings>_(ts);
984
985 *trustSettings = ts->createExternal();
986 return errSecSuccess;
987
988 END_RCSAPI
989 }
990
991 /*
992 * Import trust settings, obtained via SecTrustSettingsCreateExternalRepresentation,
993 * into the specified domain.
994 */
995 OSStatus SecTrustSettingsImportExternalRepresentation(
996 SecTrustSettingsDomain domain,
997 CFDataRef trustSettings) /* optional - NULL means empty settings */
998 {
999 BEGIN_RCSAPI
1000
1001 if(domain == kSecTrustSettingsDomainSystem) {
1002 return errSecDataNotModifiable;
1003 }
1004
1005 OSStatus result;
1006 TrustSettings* ts;
1007
1008 result = TrustSettings::CreateTrustSettings(domain, trustSettings, ts);
1009 if (result != errSecSuccess) {
1010 return result;
1011 }
1012
1013 auto_ptr<TrustSettings>_(ts);
1014
1015 ts->flushToDisk();
1016 tsTrustSettingsChanged();
1017 return errSecSuccess;
1018
1019 END_RCSAPI
1020 }
1021