2 * Copyright (c) 2003-2018 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@
26 #import <Foundation/Foundation.h>
27 #include "OTATrustUtilities.h"
37 #include <sys/syslimits.h>
40 #include <CoreFoundation/CoreFoundation.h>
42 #include "SecFramework.h"
44 #include <sys/param.h>
46 #include <os/transaction_private.h>
47 #include <utilities/SecCFRelease.h>
48 #include <utilities/SecCFError.h>
49 #include <utilities/SecCFWrappers.h>
50 #include <Security/SecBasePriv.h>
51 #include <Security/SecCertificatePriv.h>
52 #include <Security/SecFramework.h>
53 #include <dispatch/dispatch.h>
54 #include <CommonCrypto/CommonDigest.h>
55 #include <securityd/SecPinningDb.h>
58 #import <MobileAsset/MAAsset.h>
59 #import <MobileAsset/MAAssetQuery.h>
61 #include <utilities/sec_action.h>
62 #include <utilities/SecFileLocations.h>
63 #import <securityd/SecTrustLoggingServer.h>
66 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
67 #import <MobileKeyBag/MobileKeyBag.h>
68 #include <System/sys/content_protection.h>
72 #import <MobileAsset/MobileAsset.h>
75 static inline bool isNSNumber(id nsType) {
76 return nsType && [nsType isKindOfClass:[NSNumber class]];
79 static inline bool isNSDictionary(id nsType) {
80 return nsType && [nsType isKindOfClass:[NSDictionary class]];
83 static inline bool isNSArray(id nsType) {
84 return nsType && [nsType isKindOfClass:[NSArray class]];
87 static inline bool isNSDate(id nsType) {
88 return nsType && [nsType isKindOfClass:[NSDate class]];
91 #define SECURITYD_ROLE_ACCOUNT 64
92 #define ROOT_ACCOUNT 0
94 bool SecOTAPKIIsSystemTrustd() {
95 static bool result = false;
96 static dispatch_once_t onceToken;
97 dispatch_once(&onceToken, ^{
99 // Test app running as securityd
100 #elif TARGET_OS_IPHONE
101 if (getuid() == SECURITYD_ROLE_ACCOUNT)
103 if (getuid() == ROOT_ACCOUNT)
113 /* MARK: System Trust Store */
114 static CFStringRef kSecSystemTrustStoreBundlePath = CFSTR("/System/Library/Security/Certificates.bundle");
116 CFGiblisGetSingleton(CFBundleRef, SecSystemTrustStoreGetBundle, bundle, ^{
117 CFStringRef bundlePath = NULL;
118 #if TARGET_OS_SIMULATOR
119 char *simulatorRoot = getenv("SIMULATOR_ROOT");
121 bundlePath = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s%@"), simulatorRoot, kSecSystemTrustStoreBundlePath);
124 bundlePath = CFRetainSafe(kSecSystemTrustStoreBundlePath);
125 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, bundlePath, kCFURLPOSIXPathStyle, true);
126 *bundle = (url) ? CFBundleCreate(kCFAllocatorDefault, url) : NULL;
128 CFReleaseSafe(bundlePath);
131 static CFURLRef SecSystemTrustStoreCopyResourceURL(CFStringRef resourceName,
132 CFStringRef resourceType, CFStringRef subDirName) {
134 CFBundleRef bundle = SecSystemTrustStoreGetBundle();
136 url = CFBundleCopyResourceURL(bundle, resourceName,
137 resourceType, subDirName);
140 secwarning("resource: %@.%@ in %@ not found", resourceName,
141 resourceType, subDirName);
146 static NSURL *SecSystemTrustStoreCopyResourceNSURL(NSString *resourceFileName) {
147 CFBundleRef bundle = SecSystemTrustStoreGetBundle();
151 NSURL *resourceDir = CFBridgingRelease(CFBundleCopyResourcesDirectoryURL(bundle));
155 NSURL *fileURL = [NSURL URLWithString:resourceFileName
156 relativeToURL:resourceDir];
158 secwarning("resource: %@ not found", resourceFileName);
163 static CFDataRef SecSystemTrustStoreCopyResourceContents(CFStringRef resourceName,
164 CFStringRef resourceType, CFStringRef subDirName) {
165 CFURLRef url = SecSystemTrustStoreCopyResourceURL(resourceName, resourceType, subDirName);
166 CFDataRef data = NULL;
169 if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault,
170 url, &data, NULL, NULL, &error)) {
171 secwarning("read: %ld", (long) error);
179 /* MARK: MobileAsset Updates */
180 // MARK: Forward Declarations
181 static uint64_t GetAssetVersion(CFErrorRef *error);
182 static uint64_t GetSystemVersion(CFStringRef key);
183 #if !TARGET_OS_BRIDGE
184 static BOOL UpdateFromAsset(NSURL *localURL, NSNumber *asset_version, NSError **error);
185 static BOOL UpdateOTACheckInDate(void);
186 static void UpdateKillSwitch(NSString *key, bool value);
189 static void TriggerUnlockNotificationOTATrustAssetCheck(dispatch_queue_t queue);
192 /* This queue is for fetching changes to the OTAPKI reference or otherwise doing maintenance activities */
193 static dispatch_queue_t kOTABackgroundQueue = NULL;
196 NSString *kOTATrustContentVersionKey = @"MobileAssetContentVersion";
197 NSString *kOTATrustLastCheckInKey = @"MobileAssetLastCheckIn";
198 NSString *kOTATrustContextFilename = @"OTAPKIContext.plist";
199 NSString *kOTATrustTrustedCTLogsFilename = @"TrustedCTLogs.plist";
200 NSString *kOTATrustAnalyticsSamplingRatesFilename = @"AnalyticsSamplingRates.plist";
201 NSString *kOTATrustAppleCertifcateAuthoritiesFilename = @"AppleCertificateAuthorities.plist";
202 NSString *kOTATrustCTKillSwitch = @"CTKillSwitch";
204 const CFStringRef kOTAPKIKillSwitchCT = CFSTR("CTKillSwitch");
206 #if !TARGET_OS_BRIDGE
207 const NSString *OTATrustMobileAssetType = @"com.apple.MobileAsset.PKITrustSupplementals";
208 #define kOTATrustMobileAssetNotification "com.apple.MobileAsset.PKITrustSupplementals.cached-metadata-updated"
209 #define kOTATrustOnDiskAssetNotification "com.apple.trustd.asset-updated"
210 #define kOTATrustCheckInNotification "com.apple.trustd.asset-check-in"
211 #define kOTATrustKillSwitchNotification "com.apple.trustd.kill-switch"
212 const NSUInteger OTATrustMobileAssetCompatibilityVersion = 1;
213 #define kOTATrustDefaultUpdatePeriod 60*60*12 // 12 hours
214 #define kOTATrustMinimumUpdatePeriod 60*5 // 5 min
217 const CFStringRef kSecSUPrefDomain = CFSTR("com.apple.SoftwareUpdate");
218 const CFStringRef kSecSUScanPrefConfigDataInstallKey = CFSTR("ConfigDataInstall");
221 // MARK: Helper functions
223 OTATrustLogLevelNone,
224 OTATrustLogLevelDebug,
225 OTATrustLogLevelInfo,
226 OTATrustLogLevelNotice,
227 OTATrustLogLevelError,
230 static void MakeOTATrustError(NSError **error, OTATrustLogLevel level, NSErrorDomain errDomain, OSStatus errCode, NSString *format,...) NS_FORMAT_FUNCTION(5,6);
231 static void MakeOTATrustErrorWithAttributes(NSError **error, OTATrustLogLevel level, NSErrorDomain errDomain, OSStatus errCode,
232 NSDictionary *attributes, NSString *format,...)
233 NS_FORMAT_FUNCTION(6,7);
235 static void MakeOTATrustErrorArgs(NSError **error, OTATrustLogLevel level, NSErrorDomain errDomain, OSStatus errCode,
236 NSDictionary *attributes, NSString *format, va_list arguments)
237 NS_FORMAT_FUNCTION(6,0);
239 static void LogLocally(OTATrustLogLevel level, NSString *errorString) {
241 case OTATrustLogLevelNone:
243 case OTATrustLogLevelDebug:
244 secdebug("OTATrust", "%@", errorString);
246 case OTATrustLogLevelInfo:
247 secinfo("OTATrust", "%@", errorString);
249 case OTATrustLogLevelNotice:
250 secnotice("OTATrust", "%@", errorString);
252 case OTATrustLogLevelError:
253 secerror("OTATrust: %@", errorString);
258 static void LogRemotelyWithAttributes(OTATrustLogLevel level, NSError **error, NSDictionary *attributes) {
259 #if ENABLE_TRUSTD_ANALYTICS
260 /* only report errors and notices */
261 if (error && level == OTATrustLogLevelError) {
262 [[TrustdHealthAnalytics logger] logResultForEvent:TrustdHealthAnalyticsEventOTAPKIEvent hardFailure:YES result:*error withAttributes:attributes];
263 } else if (error && level == OTATrustLogLevelNotice) {
264 [[TrustdHealthAnalytics logger] logResultForEvent:TrustdHealthAnalyticsEventOTAPKIEvent hardFailure:NO result:*error withAttributes:attributes];
266 #endif // ENABLE_TRUSTD_ANALYTICS
269 static void LogRemotely(OTATrustLogLevel level, NSError **error) {
270 LogRemotelyWithAttributes(level, error, nil);
273 static void MakeOTATrustErrorArgs(NSError **error, OTATrustLogLevel level, NSErrorDomain errDomain, OSStatus errCode,
274 NSDictionary *attributes, NSString *format, va_list args) {
275 NSString *formattedString = nil;
277 formattedString = [[NSString alloc] initWithFormat:format arguments:args];
280 NSError *localError = nil;
281 NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init];
283 [userInfo setObject:formattedString forKey:NSLocalizedDescriptionKey];
285 if (error && *error) {
286 userInfo[NSUnderlyingErrorKey] = *error;
288 localError = [NSError errorWithDomain:errDomain
292 LogLocally(level, formattedString);
293 LogRemotelyWithAttributes(level, &localError, attributes);
294 if (error) { *error = localError; }
297 static void MakeOTATrustErrorWithAttributes(NSError **error, OTATrustLogLevel level, NSErrorDomain errDomain, OSStatus errCode,
298 NSDictionary *attributes, NSString *format,...) {
300 va_start(args, format);
301 MakeOTATrustErrorArgs(error, level, errDomain, errCode, attributes, format, args);
305 static void MakeOTATrustError(NSError **error, OTATrustLogLevel level, NSErrorDomain errDomain, OSStatus errCode, NSString *format,...) {
307 va_start(args, format);
308 MakeOTATrustErrorArgs(error, level, errDomain, errCode, nil, format, args);
312 static BOOL CanCheckMobileAsset(void) {
315 /* Check the user's SU preferences to determine if "Install system data files" is off */
316 if (!CFPreferencesSynchronize(kSecSUPrefDomain, kCFPreferencesAnyUser, kCFPreferencesCurrentHost)) {
317 secerror("OTATrust: unable to synchronize SoftwareUpdate prefs");
322 if (CFPreferencesAppValueIsForced(kSecSUScanPrefConfigDataInstallKey, kSecSUPrefDomain)) {
323 value = CFBridgingRelease(CFPreferencesCopyAppValue(kSecSUScanPrefConfigDataInstallKey, kSecSUPrefDomain));
325 value = CFBridgingRelease(CFPreferencesCopyValue(kSecSUScanPrefConfigDataInstallKey, kSecSUPrefDomain,
326 kCFPreferencesAnyUser, kCFPreferencesCurrentHost));
328 if (isNSNumber(value)) {
329 result = [value boolValue];
332 if (!result) { secnotice("OTATrust", "User has disabled system data installation."); }
334 /* MobileAsset.framework isn't mastered into the BaseSystem. Check that the MA classes are linked. */
335 if (![ASAssetQuery class] || ![ASAsset class] || ![MAAssetQuery class] || ![MAAsset class]) {
336 secnotice("OTATrust", "Weak-linked MobileAsset framework missing.");
343 static BOOL ShouldUpdateWithAsset(NSNumber *asset_version) {
344 if (![asset_version isKindOfClass:[NSNumber class]]) {
347 CFErrorRef error = nil;
348 uint64_t current_version = SecOTAPKIGetCurrentAssetVersion(&error);
350 CFReleaseNull(error);
353 if ([asset_version compare:[NSNumber numberWithUnsignedLongLong:current_version]] == NSOrderedDescending) {
359 static bool verify_create_path(const char *path) {
360 int ret = mkpath_np(path, 0755);
361 if (!(ret == 0 || ret == EEXIST)) {
362 secerror("could not create path: %s (%s)", path, strerror(ret));
368 // MARK: File management functions
369 static NSURL *GetAssetFileURL(NSString *filename) {
370 /* Make sure the /Library/Keychains directory is there */
372 NSURL *keychainsDirectory = CFBridgingRelease(SecCopyURLForFileInKeychainDirectory(nil));
374 NSURL *keychainsDirectory = [NSURL fileURLWithFileSystemRepresentation:"/Library/Keychains/" isDirectory:YES relativeToURL:nil];
376 NSURL *directory = [keychainsDirectory URLByAppendingPathComponent:@"SupplementalsAssets/" isDirectory:YES];
377 if (!verify_create_path([directory fileSystemRepresentation])) {
382 return [directory URLByAppendingPathComponent:filename];
388 static void DeleteFileWithName(NSString *filename) {
389 NSURL *fileURL = GetAssetFileURL(filename);
390 if (remove([fileURL fileSystemRepresentation]) == -1) {
392 if (error != ENOENT) {
393 secnotice("OTATrust", "failed to remove %@: %s", fileURL, strerror(error));
398 static BOOL UpdateOTAContextOnDisk(NSString *key, id value, NSError **error) {
399 if (SecOTAPKIIsSystemTrustd()) {
400 /* Get current context, if applicable, and update/add key/value */
401 NSURL *otaContextFile = GetAssetFileURL(kOTATrustContextFilename);
402 NSDictionary *currentContext = [NSDictionary dictionaryWithContentsOfURL:otaContextFile];
403 NSMutableDictionary *newContext = nil;
404 if (currentContext) {
405 newContext = [currentContext mutableCopy];
407 newContext = [NSMutableDictionary dictionary];
409 newContext[key] = value;
411 /* Write dictionary to disk */
412 if (![newContext writeToURL:otaContextFile error:error]) {
413 secerror("OTATrust: unable to write OTA Context to disk: %@", error ? *error : nil);
414 LogRemotely(OTATrustLogLevelError, error);
422 static BOOL UpdateOTAContext(NSNumber *asset_version, NSError **error) {
423 return UpdateOTAContextOnDisk(kOTATrustContentVersionKey, asset_version, error) && UpdateOTACheckInDate();
426 /* Delete only the asset data but not the check-in time. */
427 static void DeleteOldAssetData(void) {
428 if (SecOTAPKIIsSystemTrustd()) {
429 /* Delete the asset files, but keep the check-in time and version */
430 DeleteFileWithName(kOTATrustTrustedCTLogsFilename);
431 DeleteFileWithName(kOTATrustAnalyticsSamplingRatesFilename);
432 DeleteFileWithName(kOTATrustAppleCertifcateAuthoritiesFilename);
436 /* Delete all asset data, intended for error cases */
437 static BOOL DeleteAssetFromDisk(void) {
438 if (SecOTAPKIIsSystemTrustd()) {
439 DeleteOldAssetData();
440 DeleteFileWithName(kOTATrustContextFilename);
446 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
447 static bool ChangeFileProtectionToClassD(NSURL *fileURL, NSError **error) {
449 int file_fd = open([fileURL fileSystemRepresentation], O_RDONLY);
451 int retval = fcntl(file_fd, F_SETPROTECTIONCLASS, PROTECTION_CLASS_D);
453 MakeOTATrustError(error, OTATrustLogLevelError, NSPOSIXErrorDomain, errno,
454 @"set proteciton class error for asset %d: %s", errno, strerror(errno));
459 MakeOTATrustError(error, OTATrustLogLevelError, NSPOSIXErrorDomain, errno,
460 @"open error for asset %d: %s", errno, strerror(errno));
467 static BOOL CopyFileToDisk(NSString *filename, NSURL *localURL, NSError **error) {
468 if (SecOTAPKIIsSystemTrustd()) {
469 NSURL *toFileURL = GetAssetFileURL(filename);
470 secdebug("OTATrust", "will copy asset file data from \"%@\"", localURL);
471 copyfile_state_t state = copyfile_state_alloc();
472 int retval = copyfile([localURL fileSystemRepresentation], [toFileURL fileSystemRepresentation],
473 state, COPYFILE_DATA);
474 copyfile_state_free(state);
476 MakeOTATrustError(error, OTATrustLogLevelError, NSPOSIXErrorDomain, errno,
477 @"copyfile error for asset %d: %s", errno, strerror(errno));
480 /* make sure we can read this file before first unlock */
481 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
482 return ChangeFileProtectionToClassD(toFileURL, error);
491 static void GetKillSwitchAttributes(NSDictionary *attributes) {
492 bool killSwitchEnabled = false;
495 NSNumber *ctKillSwitch = [attributes objectForKey:kOTATrustCTKillSwitch];
496 if (isNSNumber(ctKillSwitch)) {
497 NSError *error = nil;
498 UpdateOTAContextOnDisk(kOTATrustCTKillSwitch, ctKillSwitch, &error);
499 UpdateKillSwitch(kOTATrustCTKillSwitch, [ctKillSwitch boolValue]);
500 secnotice("OTATrust", "got CT kill switch = %d", [ctKillSwitch boolValue]);
501 killSwitchEnabled = true;
504 /* Other kill switches TBD.
505 * When adding one, make sure to add to the Analytics Samplers since these kill switches
506 * are installed before the full asset is downloaded and installed. (A device can have the
507 * kill switches without having the asset version that contained them.) */
509 // notify the other trustds if any kill switch was read
510 if (SecOTAPKIIsSystemTrustd() && killSwitchEnabled) {
511 notify_post(kOTATrustKillSwitchNotification);
515 // MARK: Fetch and Update Functions
517 static NSNumber *UpdateAndPurgeAsset(MAAsset *asset, NSNumber *asset_version, NSError **error) {
518 if (SecPinningDbUpdateFromURL([asset getLocalFileUrl], error) &&
519 UpdateFromAsset([asset getLocalFileUrl], asset_version, error)) {
520 secnotice("OTATrust", "finished update to version %@ from installed asset. purging asset.", asset_version);
521 #if ENABLE_TRUSTD_ANALYTICS
522 [[TrustdHealthAnalytics logger] logSuccessForEventNamed:TrustdHealthAnalyticsEventOTAPKIEvent];
523 #endif // ENABLE_TRUSTD_ANALYTICS
524 [asset purge:^(MAPurgeResult purge_result) {
525 if (purge_result != MAPurgeSucceeded) {
526 secerror("OTATrust: purge failed: %ld", (long)purge_result);
529 return asset_version;
531 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecCallbackFailed,
532 @"Failed to install new asset version %@ from %@", asset_version, [asset getLocalFileUrl]);
537 static MADownloadOptions *GetMADownloadOptions(BOOL wait) {
538 /* default behavior */
539 MADownloadOptions *options = [[MADownloadOptions alloc] init];
540 options.discretionary = YES;
541 options.allowsCellularAccess = NO;
543 /* If an XPC interface is waiting on this, all expenses allowed */
545 options.discretionary = NO;
546 options.allowsCellularAccess = YES;
550 /* If last asset check-in was too long ago, use more expensive options */
551 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
552 if (!SecOTAPKIAssetStalenessLessThanSeconds(otapkiref, kSecOTAPKIAssetStalenessWarning)) {
553 secnotice("OTATrust", "Asset staleness state: warning");
554 options.allowsCellularAccess = YES;
555 options.discretionary = NO;
556 } else if (!SecOTAPKIAssetStalenessLessThanSeconds(otapkiref, kSecOTAPKIAssetStalenessAtRisk)) {
557 secnotice("OTATrust", "Asset staleness state: at risk");
558 options.discretionary = NO;
560 CFReleaseNull(otapkiref);
564 static BOOL DownloadOTATrustAsset(BOOL isLocalOnly, BOOL wait, NSError **error) {
565 if (!CanCheckMobileAsset()) {
566 MakeOTATrustError(error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecServiceNotAvailable,
567 @"MobileAsset disabled, skipping check.");
571 __block NSNumber *updated_version = nil;
572 __block dispatch_semaphore_t done = wait ? dispatch_semaphore_create(0) : nil;
573 __block NSError *ma_error = nil;
574 secnotice("OTATrust", "begin MobileAsset query for catalog");
575 [MAAsset startCatalogDownload:(NSString *)OTATrustMobileAssetType options:GetMADownloadOptions(wait) then:^(MADownLoadResult result) {
577 os_transaction_t transaction = os_transaction_create("com.apple.trustd.PKITrustSupplementals.download");
578 if (result != MADownloadSucceesful) {
579 MakeOTATrustError(&ma_error, OTATrustLogLevelError, @"MADownLoadResult", (OSStatus)result,
580 @"failed to download catalog: %ld", (long)result);
581 if (result == MADownloadDaemonNotReady) {
582 /* mobileassetd has to wait for first unlock to downalod. trustd usually launches before first unlock. */
583 TriggerUnlockNotificationOTATrustAssetCheck(kOTABackgroundQueue);
587 MAAssetQuery *query = [[MAAssetQuery alloc] initWithType:(NSString *)OTATrustMobileAssetType];
588 [query augmentResultsWithState:true];
590 secnotice("OTATrust", "begin MobileAsset metadata sync request");
591 MAQueryResult queryResult = [query queryMetaDataSync];
592 if (queryResult != MAQuerySucceesful) {
593 MakeOTATrustError(&ma_error, OTATrustLogLevelError, @"MAQueryResult", (OSStatus)queryResult,
594 @"failed to query MobileAsset metadata: %ld", (long)queryResult);
598 if (!query.results) {
599 MakeOTATrustError(&ma_error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternal,
600 @"no results in MobileAsset query");
604 bool began_async_job = false;
605 for (MAAsset *asset in query.results) {
606 /* Check Compatibility Version against this software version */
607 NSNumber *compatibilityVersion = [asset assetProperty:@"_CompatibilityVersion"];
608 if (!isNSNumber(compatibilityVersion) ||
609 [compatibilityVersion unsignedIntegerValue] != OTATrustMobileAssetCompatibilityVersion) {
610 MakeOTATrustError(&ma_error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecIncompatibleVersion,
611 @"skipping asset because Compatibility Version doesn't match %@", compatibilityVersion);
615 /* Check Content Version against the current content version */
616 NSNumber *asset_version = [asset assetProperty:@"_ContentVersion"];
617 if (!ShouldUpdateWithAsset(asset_version)) {
618 /* write the version and last (successful) check-in time */
619 UpdateOTAContext(asset_version, &ma_error);
620 NSDictionary *eventAttributes = @{
621 @"assetVersion" : asset_version,
622 @"systemVersion" : @(GetSystemVersion((__bridge CFStringRef)kOTATrustContentVersionKey)),
623 @"installedVersion" : @(SecOTAPKIGetCurrentAssetVersion(nil)),
625 MakeOTATrustErrorWithAttributes(&ma_error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecDuplicateItem, eventAttributes,
626 @"skipping asset because we already have _ContentVersion %@ (or newer)", asset_version);
630 GetKillSwitchAttributes(asset.attributes);
632 switch (asset.state) {
634 MakeOTATrustError(&ma_error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternal,
635 @"unknown asset state %ld", (long)asset.state);
638 /* The asset is already in the cache, get it from disk. */
639 secdebug("OTATrust", "OTATrust asset already installed");
640 updated_version = UpdateAndPurgeAsset(asset, asset_version, &ma_error);
643 MakeOTATrustError(&ma_error, OTATrustLogLevelError, @"MAAssetState", (OSStatus)asset.state,
644 @"asset is unknown");
647 secnotice("OTATrust", "asset is downloading");
650 secnotice("OTATrust", "begin download of OTATrust asset");
651 began_async_job = true;
652 [asset startDownload:GetMADownloadOptions(wait) then:^(MADownLoadResult downloadResult) {
654 os_transaction_t inner_transaction = os_transaction_create("com.apple.trustd.PKITrustSupplementals.downloadAsset");
655 if (downloadResult != MADownloadSucceesful) {
656 MakeOTATrustError(&ma_error, OTATrustLogLevelError, @"MADownLoadResult", (OSStatus)downloadResult,
657 @"failed to download asset: %ld", (long)downloadResult);
660 updated_version = UpdateAndPurgeAsset(asset, asset_version, &ma_error);
662 dispatch_semaphore_signal(done);
664 (void)inner_transaction; // dead store
665 inner_transaction = nil;
669 } /* switch (asset.state) */
670 } /* for (MAAsset.. */
671 if (wait && !began_async_job) {
672 dispatch_semaphore_signal(done);
674 /* Done with the transaction */
675 (void)transaction; // dead store
677 } /* autoreleasepool */
678 }]; /* [MAAsset startCatalogDownload: ] */
680 /* If the caller is waiting for a response, wait up to one minute for the update to complete.
681 * If the MAAsset callback does not complete in that time, report a timeout.
682 * If the MAAsset callback completes and did not successfully update, it should report an error;
683 * forward that error to the caller.
684 * If the MAAsset callback completes and did not update and did not provide an error; report
685 * an unknown error. */
688 if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60)) != 0) {
689 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecNetworkFailure,
690 @"Failed to get asset metadata within 1 minute.");
692 result = (updated_version != nil);
693 if (error && ma_error) {
695 } else if (!result) {
696 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternalComponent,
697 @"Unknown error occurred.");
704 static void TriggerUnlockNotificationOTATrustAssetCheck(dispatch_queue_t queue) {
705 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
706 /* If the last check-in is recent enough, wait for our regularly scheduled check-in. */
707 if (SecOTAPKIAssetStalenessLessThanSeconds(otapkiref, kSecOTAPKIAssetStalenessAtRisk)) {
708 CFReleaseNull(otapkiref);
711 #if !TARGET_OS_SIMULATOR
712 /* register for unlock notifications */
714 notify_register_dispatch(kMobileKeyBagLockStatusNotificationID, &out_token, queue, ^(int token) {
715 secnotice("OTATrust", "Got lock status notification for at-risk last check-in after MA daemon error");
716 (void)DownloadOTATrustAsset(NO, NO, nil);
717 notify_cancel(token);
721 #else /* !TARGET_OS_IPHONE */
722 /* <rdar://problem/30879827> MobileAssetV2 fails on macOS, so use V1 */
723 static NSNumber *UpdateAndPurgeAsset(ASAsset *asset, NSNumber *asset_version, NSError **error) {
724 if (SecPinningDbUpdateFromURL([asset localURL], error) &&
725 UpdateFromAsset([asset localURL], asset_version, error)) {
726 secnotice("OTATrust", "finished update to version %@ from installed asset. purging asset.", asset_version);
727 #if ENABLE_TRUSTD_ANALYTICS
728 [[TrustdHealthAnalytics logger] logSuccessForEventNamed:TrustdHealthAnalyticsEventOTAPKIEvent];
729 #endif // ENABLE_TRUSTD_ANALYTICS
730 [asset purge:^(NSError *ma_error) {
732 secerror("OTATrust: purge failed %@", ma_error);
735 return asset_version;
737 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecCallbackFailed,
738 @"Failed to install new asset version %@ from %@", asset_version, [asset localURL]);
743 static NSDictionary *GetASDownloadOptions(BOOL wait) {
744 /* default behavior */
745 NSMutableDictionary *options = [NSMutableDictionary dictionary];
746 options[ASDownloadOptionPriority] = ASDownloadPriorityNormal;
748 /* If an XPC interface is waiting on this, all expenses allowed */
750 options[ASDownloadOptionPriority] = ASDownloadPriorityHigh;
751 options[ASDownloadOptionAllowBatteryPower] = @YES;
755 /* If last asset check-in was too long ago, use more expensive options */
756 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
757 if (!SecOTAPKIAssetStalenessLessThanSeconds(otapkiref, kSecOTAPKIAssetStalenessWarning)) {
758 secnotice("OTATrust", "Asset staleness state: warning");
759 options[ASDownloadOptionPriority] = ASDownloadPriorityHigh;
760 options[ASDownloadOptionAllowBatteryPower] = @YES;
761 } else if (!SecOTAPKIAssetStalenessLessThanSeconds(otapkiref, kSecOTAPKIAssetStalenessAtRisk)) {
762 secnotice("OTATrust", "Asset staleness state: at risk");
763 options[ASDownloadOptionPriority] = ASDownloadPriorityHigh;
765 CFReleaseNull(otapkiref);
769 static BOOL DownloadOTATrustAsset(BOOL isLocalOnly, BOOL wait, NSError **error) {
770 if (!CanCheckMobileAsset()) {
771 MakeOTATrustError(error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecServiceNotAvailable,
772 @"MobileAsset disabled, skipping check.");
776 NSError *localError = nil; // -[ASAssetQuery runQueryAndReturnError:] leaks if you pass null
777 ASAssetQuery *query = [[ASAssetQuery alloc] initWithAssetType:(NSString *)OTATrustMobileAssetType];
778 [query setQueriesLocalAssetInformationOnly:isLocalOnly]; // Omitting this leads to a notifcation loop.
779 NSArray<ASAsset *>*query_results = [query runQueryAndReturnError:&localError];
780 if (!query_results) {
782 secerror("OTATrust: asset query failed: %@", localError);
783 LogRemotely(OTATrustLogLevelError, &localError);
784 if (error) { *error = localError; }
789 __block NSNumber *updated_version = nil;
790 __block NSError *handler_error = nil;
791 __block dispatch_semaphore_t done = wait ? dispatch_semaphore_create(0) : nil;
792 bool began_async_job = false;
793 for (ASAsset *asset in query_results) {
794 NSDictionary *attributes = [asset attributes];
796 /* Check Compatibility Version against this software version */
797 NSNumber *compatibilityVersion = [attributes objectForKey:ASAttributeCompatibilityVersion];
798 if (!isNSNumber(compatibilityVersion) ||
799 [compatibilityVersion unsignedIntegerValue] != OTATrustMobileAssetCompatibilityVersion) {
800 MakeOTATrustError(error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecIncompatibleVersion,
801 @"skipping asset because Compatibility Version doesn't match %@", compatibilityVersion);
805 /* Check Content Version against the current content version */
806 NSNumber *contentVersion = [attributes objectForKey:ASAttributeContentVersion];
807 if (!ShouldUpdateWithAsset(contentVersion)) {
808 /* write the version and last (successful) check-in time */
809 UpdateOTAContext(contentVersion, error);
810 NSDictionary *eventAttributes = @{
811 @"assetVersion" : contentVersion,
812 @"systemVersion" : @(GetSystemVersion((__bridge CFStringRef)kOTATrustContentVersionKey)),
813 @"installedVersion" : @(SecOTAPKIGetCurrentAssetVersion(nil)),
815 MakeOTATrustErrorWithAttributes(error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecDuplicateItem, eventAttributes,
816 @"skipping asset because we already have _ContentVersion %@ (or newer)", contentVersion);
820 GetKillSwitchAttributes(attributes);
822 ASProgressHandler OTATrustHandler = ^(NSDictionary *state, NSError *progressError){
823 NSString *operationState = nil;
825 secerror("OTATrust: progress handler failed: %@", progressError);
826 LogRemotely(OTATrustLogLevelError, &progressError);
827 handler_error = [progressError copy];
829 dispatch_semaphore_signal(done);
835 MakeOTATrustError(&handler_error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternal,
836 @"no asset state in progress handler");
838 dispatch_semaphore_signal(done);
843 operationState = [state objectForKey:ASStateOperation];
844 secdebug("OTATrust", "Asset state is %@", operationState);
846 if (operationState && [operationState isEqualToString:ASOperationCompleted]) {
847 updated_version = UpdateAndPurgeAsset(asset, contentVersion, &handler_error);
849 dispatch_semaphore_signal(done);
852 /* Other states keep calling our progress handler until completed so don't signal */
855 switch ([asset state]) {
856 case ASAssetStateNotPresent:
857 secdebug("OTATrust", "OTATrust asset needs to be downloaded");
858 asset.progressHandler= OTATrustHandler;
859 asset.userInitiatedDownload = YES;
860 [asset beginDownloadWithOptions:GetASDownloadOptions(wait)];
861 began_async_job = true;
863 case ASAssetStateInstalled:
864 /* The asset is already in the cache, get it from disk. */
865 secdebug("OTATrust", "OTATrust asset already installed");
866 updated_version = UpdateAndPurgeAsset(asset, contentVersion, error);
868 case ASAssetStatePaused:
869 secdebug("OTATrust", "OTATrust asset download paused");
870 asset.progressHandler = OTATrustHandler;
871 asset.userInitiatedDownload = YES;
872 [asset adjustDownloadOptions:GetASDownloadOptions(wait) completion:nil];
873 if (![asset resumeDownloadAndReturnError:&localError]) {
875 secerror("OTATrust: failed to resume download of asset: %@", localError);
876 LogRemotely(OTATrustLogLevelError, &localError);
877 if (error) { *error = localError; }
880 began_async_job = true;
883 case ASAssetStateStalled:
884 secdebug("OTATrust", "OTATrust asset stalled");
886 case ASAssetStateDownloading:
887 secdebug("OTATrust", "OTATrust asset downloading");
888 asset.progressHandler = OTATrustHandler;
889 asset.userInitiatedDownload = YES;
890 [asset adjustDownloadOptions:GetASDownloadOptions(wait) completion:nil];
891 began_async_job = true;
894 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternal,
895 @"unhandled asset state %ld", (long)asset.state);
900 /* If the caller is waiting for a response, wait up to one minute for the update to complete.
901 * If the OTATrustHandler does not complete in the time, report a timeout.
902 * If the OTATrustHandler completes and did not successfully update and it reported an error;
903 * forward that error to the caller. */
904 BOOL result = (updated_version != nil);
905 if (wait && began_async_job) {
906 if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60)) != 0) {
907 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecNetworkFailure,
908 @"Failed to get asset metadata within 1 minute.");
910 /* finished an async job, update the result */
911 result = (updated_version != nil);
912 if (error && handler_error) {
913 *error = handler_error;
918 /* If we failed and don't know why, report an unknown error */
919 if (!result && error && (*error == NULL)) {
920 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternalComponent,
921 @"Unknown error occurred.");
925 #endif /* !TARGET_OS_IPHONE */
927 static bool InitializeKillSwitch(NSString *key) {
928 #if !TARGET_OS_BRIDGE
929 NSError *error = nil;
930 NSDictionary *OTAPKIContext = [NSDictionary dictionaryWithContentsOfURL:GetAssetFileURL(kOTATrustContextFilename) error:&error];
931 if (isNSDictionary(OTAPKIContext)) {
932 NSNumber *killSwitchValue = OTAPKIContext[key];
933 if (isNSNumber(killSwitchValue)) {
934 secinfo("OTATrust", "found on-disk kill switch %{public}@ with value %d", key, [killSwitchValue boolValue]);
935 return [killSwitchValue boolValue];
937 MakeOTATrustError(&error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecInvalidValue,
938 @"OTAContext.plist missing check-in");
941 MakeOTATrustError(&error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecMissingValue,
942 @"OTAContext.plist missing dictionary");
948 static void InitializeOTATrustAsset(dispatch_queue_t queue) {
949 /* Only the "system" trustd does updates */
950 if (SecOTAPKIIsSystemTrustd()) {
951 /* Asynchronously ask MobileAsset for most recent asset. */
952 dispatch_async(queue, ^{
953 secnotice("OTATrust", "Initial check with MobileAsset for newer PKITrustSupplementals asset");
954 (void)DownloadOTATrustAsset(NO, NO, nil);
957 /* Register for changes in our asset */
958 if (CanCheckMobileAsset()) {
960 notify_register_dispatch(kOTATrustMobileAssetNotification, &out_token, queue, ^(int __unused token) {
961 secnotice("OTATrust", "Got notification about a new PKITrustSupplementals asset from mobileassetd.");
962 (void)DownloadOTATrustAsset(YES, NO, nil);
966 /* Register for changes signaled by the system trustd */
967 secnotice("OTATrust", "Intializing listener for Asset changes from system trustd.");
969 notify_register_dispatch(kOTATrustOnDiskAssetNotification, &out_token, queue, ^(int __unused token) {
970 secnotice("OTATrust", "Got notification about a new PKITrustSupplementals asset from system trustd.");
971 NSError *nserror = nil;
972 CFErrorRef error = nil;
973 NSNumber *asset_version = [NSNumber numberWithUnsignedLongLong:GetAssetVersion(&error)];
975 nserror = CFBridgingRelease(error);
977 if (!UpdateFromAsset(GetAssetFileURL(nil), asset_version, &nserror)) {
978 secerror("OTATrust: failed to update from asset after notification: %@", nserror);
979 /* Reset our last check-in time and reset the asset version to the system asset version -- even
980 * though we may be using something newer than that (but not as new as what's on disk). On re-launch
981 * (provided reading from disk still fails) we'd be using the system asset version anyway. */
982 SecOTAPKIResetCurrentAssetVersion(&error);
986 notify_register_dispatch(kOTATrustCheckInNotification, &out_token2, queue, ^(int __unused token) {
987 secinfo("OTATrust", "Got notification about successful PKITrustSupplementals asset check-in");
988 (void)UpdateOTACheckInDate();
991 notify_register_dispatch(kOTATrustKillSwitchNotification, &out_token3, queue, ^(int __unused token) {
992 UpdateKillSwitch(kOTATrustCTKillSwitch, InitializeKillSwitch(kOTATrustCTKillSwitch));
997 static void TriggerPeriodicOTATrustAssetChecks(dispatch_queue_t queue) {
998 if (SecOTAPKIIsSystemTrustd()) {
999 static sec_action_t action;
1000 static bool first_launch = true;
1001 static dispatch_once_t onceToken;
1002 dispatch_once(&onceToken, ^{
1003 NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.apple.security"];
1004 NSNumber *updateDeltas = [defaults valueForKey:@"PKITrustSupplementalsUpdatePeriod"];
1005 int delta = kOTATrustDefaultUpdatePeriod;
1006 if (isNSNumber(updateDeltas)) {
1007 delta = [updateDeltas intValue];
1008 if (delta < kOTATrustMinimumUpdatePeriod) {
1009 delta = kOTATrustMinimumUpdatePeriod;
1012 secnotice("OTATrust", "Setting periodic update delta to %d seconds", delta);
1013 action = sec_action_create_with_queue(queue,"OTATrust", delta);
1014 sec_action_set_handler(action, ^{
1015 if (!first_launch) {
1016 (void)DownloadOTATrustAsset(NO, NO, nil);
1018 first_launch = false;
1021 sec_action_perform(action);
1024 #endif /* !TARGET_OS_BRIDGE */
1027 /* MARK: Initialization functions */
1028 static CFPropertyListRef CFPropertyListCopyFromSystem(CFStringRef asset) {
1029 CFPropertyListRef plist = NULL;
1030 CFDataRef xmlData = SecSystemTrustStoreCopyResourceContents(asset, CFSTR("plist"), NULL);
1033 plist = CFPropertyListCreateWithData(kCFAllocatorDefault, xmlData, kCFPropertyListImmutable, NULL, NULL);
1040 static uint64_t GetSystemVersion(CFStringRef key) {
1041 uint64_t system_version = 0;
1042 int64_t asset_number = 0;
1044 CFDataRef assetVersionData = SecSystemTrustStoreCopyResourceContents(CFSTR("AssetVersion"), CFSTR("plist"), NULL);
1045 if (NULL != assetVersionData) {
1046 CFPropertyListFormat propFormat;
1047 CFDictionaryRef versionPlist = CFPropertyListCreateWithData(kCFAllocatorDefault, assetVersionData, 0, &propFormat, NULL);
1048 if (NULL != versionPlist && CFDictionaryGetTypeID() == CFGetTypeID(versionPlist)) {
1049 CFNumberRef versionNumber = (CFNumberRef)CFDictionaryGetValue(versionPlist, (const void *)key);
1050 if (NULL != versionNumber){
1051 CFNumberGetValue(versionNumber, kCFNumberSInt64Type, &asset_number);
1052 if (asset_number < 0) { // Not valid
1055 system_version = (uint64_t)asset_number;
1058 CFReleaseSafe(versionPlist);
1059 CFReleaseSafe(assetVersionData);
1062 return system_version;
1065 static bool initialization_error_from_asset_data = false;
1067 static bool ShouldInitializeWithAsset(void) {
1068 uint64_t system_version = GetSystemVersion((__bridge CFStringRef)kOTATrustContentVersionKey);
1069 uint64_t asset_version = GetAssetVersion(nil);
1071 if (asset_version > system_version) {
1072 secnotice("OTATrust", "Using asset v%llu instead of system v%llu", asset_version, system_version);
1073 return !initialization_error_from_asset_data;
1078 static CFSetRef CFSetCreateFromPropertyList(CFPropertyListRef plist) {
1079 CFSetRef result = NULL;
1082 CFMutableSetRef tempSet = NULL;
1083 if (CFGetTypeID(plist) == CFArrayGetTypeID()) {
1084 tempSet = CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks);
1085 if (NULL == tempSet) {
1088 CFArrayRef array = (CFArrayRef)plist;
1089 CFIndex num_keys = CFArrayGetCount(array);
1090 for (CFIndex idx = 0; idx < num_keys; idx++) {
1091 CFDataRef data = (CFDataRef)CFArrayGetValueAtIndex(array, idx);
1092 CFSetAddValue(tempSet, data);
1103 static CF_RETURNS_RETAINED CFSetRef InitializeBlackList() {
1104 CFPropertyListRef plist = CFPropertyListCopyFromSystem(CFSTR("Blocked"));
1105 CFSetRef result = CFSetCreateFromPropertyList(plist);
1106 CFReleaseSafe(plist);
1111 static CF_RETURNS_RETAINED CFSetRef InitializeGrayList() {
1112 CFPropertyListRef plist = CFPropertyListCopyFromSystem(CFSTR("GrayListedKeys"));
1113 CFSetRef result = CFSetCreateFromPropertyList(plist);
1114 CFReleaseSafe(plist);
1119 static CF_RETURNS_RETAINED CFURLRef InitializePinningList() {
1120 return SecSystemTrustStoreCopyResourceURL(CFSTR("CertificatePinning"), CFSTR("plist"), NULL);
1123 static CF_RETURNS_RETAINED CFDictionaryRef InitializeAllowList() {
1124 CFPropertyListRef allowList = CFPropertyListCopyFromSystem(CFSTR("Allowed"));
1126 if (allowList && (CFGetTypeID(allowList) == CFDictionaryGetTypeID())) {
1129 CFReleaseNull(allowList);
1134 static CF_RETURNS_RETAINED CFArrayRef InitializeTrustedCTLogs() {
1135 NSArray *trustedCTLogs = nil;
1136 NSError *error = nil;
1137 #if !TARGET_OS_BRIDGE
1138 if (ShouldInitializeWithAsset()) {
1139 trustedCTLogs = [NSArray arrayWithContentsOfURL:GetAssetFileURL(kOTATrustTrustedCTLogsFilename) error:&error];
1140 if (!isNSArray(trustedCTLogs)) {
1141 secerror("OTATrust: failed to read CT list from asset data: %@", error);
1142 LogRemotely(OTATrustLogLevelError, &error);
1143 if (!DeleteAssetFromDisk()) {
1144 initialization_error_from_asset_data = true;
1149 if (!isNSArray(trustedCTLogs)) {
1150 trustedCTLogs = [NSArray arrayWithContentsOfURL:SecSystemTrustStoreCopyResourceNSURL(kOTATrustTrustedCTLogsFilename)];
1152 if (isNSArray(trustedCTLogs)) {
1153 return CFBridgingRetain(trustedCTLogs);
1158 static CF_RETURNS_RETAINED CFDictionaryRef InitializeEVPolicyToAnchorDigestsTable() {
1159 CFDictionaryRef result = NULL;
1160 CFPropertyListRef evroots = CFPropertyListCopyFromSystem(CFSTR("EVRoots"));
1163 if (CFGetTypeID(evroots) == CFDictionaryGetTypeID()) {
1164 /* @@@ Ensure that each dictionary key is a dotted list of digits,
1165 each value is an NSArrayRef and each element in the array is a
1167 result = (CFDictionaryRef)evroots;
1170 secwarning("EVRoot.plist is wrong type.");
1178 static CFIndex InitializeValidSnapshotVersion(CFIndex *outFormat) {
1179 CFIndex validVersion = 0;
1180 CFIndex validFormat = 0;
1181 CFDataRef validVersionData = SecSystemTrustStoreCopyResourceContents(CFSTR("ValidUpdate"), CFSTR("plist"), NULL);
1182 if (NULL != validVersionData)
1184 CFPropertyListFormat propFormat;
1185 CFDictionaryRef versionPlist = CFPropertyListCreateWithData(kCFAllocatorDefault, validVersionData, 0, &propFormat, NULL);
1186 if (NULL != versionPlist && CFDictionaryGetTypeID() == CFGetTypeID(versionPlist))
1188 CFNumberRef versionNumber = (CFNumberRef)CFDictionaryGetValue(versionPlist, (const void *)CFSTR("Version"));
1189 if (NULL != versionNumber)
1191 CFNumberGetValue(versionNumber, kCFNumberCFIndexType, &validVersion);
1193 CFNumberRef formatNumber = (CFNumberRef)CFDictionaryGetValue(versionPlist, (const void *)CFSTR("Format"));
1194 if (NULL != formatNumber)
1196 CFNumberGetValue(formatNumber, kCFNumberCFIndexType, &validFormat);
1199 CFReleaseSafe(versionPlist);
1200 CFReleaseSafe(validVersionData);
1203 *outFormat = validFormat;
1205 return validVersion;
1208 static Boolean PathExists(const char* path, size_t* pFileSize) {
1209 const char *checked_path = (path) ? path : "";
1210 Boolean result = false;
1213 if (NULL != pFileSize) {
1217 int stat_result = stat(checked_path, &sb);
1218 result = (stat_result == 0);
1220 if (result && !S_ISDIR(sb.st_mode)) {
1222 if (NULL != pFileSize) {
1223 *pFileSize = (size_t)sb.st_size;
1230 static const char* InitializeValidSnapshotData(CFStringRef filename_str) {
1231 char *result = NULL;
1232 const char *base_error_str = "could not get valid snapshot";
1234 CFURLRef valid_url = SecSystemTrustStoreCopyResourceURL(filename_str, CFSTR("sqlite3"), NULL);
1235 if (NULL == valid_url) {
1236 secerror("%s", base_error_str);
1238 CFStringRef valid_str = CFURLCopyFileSystemPath(valid_url, kCFURLPOSIXPathStyle);
1239 char file_path_buffer[PATH_MAX];
1240 memset(file_path_buffer, 0, PATH_MAX);
1241 if (NULL == valid_str) {
1242 secerror("%s path", base_error_str);
1244 const char *valid_cstr = CFStringGetCStringPtr(valid_str, kCFStringEncodingUTF8);
1245 if (NULL == valid_cstr) {
1246 if (CFStringGetCString(valid_str, file_path_buffer, PATH_MAX, kCFStringEncodingUTF8)) {
1247 valid_cstr = file_path_buffer;
1250 if (NULL == valid_cstr) {
1251 secerror("%s path as UTF8 string", base_error_str);
1253 asprintf(&result, "%s", valid_cstr);
1256 CFReleaseSafe(valid_str);
1258 CFReleaseSafe(valid_url);
1259 if (result && !PathExists(result, NULL)) {
1263 return (const char*)result;
1266 static const char* InitializeValidDatabaseSnapshot() {
1267 return InitializeValidSnapshotData(CFSTR("valid"));
1270 static const uint8_t* MapFile(const char* path, size_t* out_file_size) {
1272 const uint8_t *buf = NULL;
1276 if (NULL == path || NULL == out_file_size) {
1282 fd = open(path, O_RDONLY);
1283 if (fd < 0) { return NULL; }
1284 rtn = fstat(fd, &sb);
1285 if (rtn || (sb.st_size > (off_t) ((UINT32_MAX >> 1)-1))) {
1289 size = (size_t)sb.st_size;
1291 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1292 if (!buf || buf == MAP_FAILED) {
1293 secerror("unable to map %s (errno %d)", path, errno);
1299 *out_file_size = size;
1303 static void UnMapFile(void* mapped_data, size_t data_size) {
1307 int rtn = munmap(mapped_data, data_size);
1309 secerror("unable to unmap %ld bytes at %p (error %d)", data_size, mapped_data, rtn);
1313 struct index_record {
1314 unsigned char hash[CC_SHA1_DIGEST_LENGTH];
1317 typedef struct index_record index_record;
1319 static bool InitializeAnchorTable(CFDictionaryRef* pLookupTable, const char** ppAnchorTable) {
1321 bool result = false;
1323 if (NULL == pLookupTable || NULL == ppAnchorTable) {
1327 *pLookupTable = NULL;
1328 *ppAnchorTable = NULL;;
1330 CFDataRef cert_index_file_data = NULL;
1331 char file_path_buffer[PATH_MAX];
1332 CFURLRef table_data_url = NULL;
1333 CFStringRef table_data_cstr_path = NULL;
1334 const char* table_data_path = NULL;
1335 const index_record* pIndex = NULL;
1336 size_t index_offset = 0;
1337 size_t index_data_size = 0;
1338 CFMutableDictionaryRef anchorLookupTable = NULL;
1339 uint32_t offset_int_value = 0;
1340 CFNumberRef index_offset_value = NULL;
1341 CFDataRef index_hash = NULL;
1342 CFMutableArrayRef offsets = NULL;
1343 Boolean release_offset = false;
1345 char* local_anchorTable = NULL;
1346 size_t local_anchorTableSize = 0;
1348 // local_anchorTable is still NULL so the asset in the system trust store bundle needs to be used.
1349 CFReleaseSafe(cert_index_file_data);
1350 cert_index_file_data = SecSystemTrustStoreCopyResourceContents(CFSTR("certsIndex"), CFSTR("data"), NULL);
1351 if (!cert_index_file_data) {
1352 secerror("could not find certsIndex");
1354 table_data_url = SecSystemTrustStoreCopyResourceURL(CFSTR("certsTable"), CFSTR("data"), NULL);
1355 if (!table_data_url) {
1356 secerror("could not find certsTable");
1359 if (NULL != table_data_url) {
1360 table_data_cstr_path = CFURLCopyFileSystemPath(table_data_url, kCFURLPOSIXPathStyle);
1361 if (NULL != table_data_cstr_path) {
1362 memset(file_path_buffer, 0, PATH_MAX);
1363 table_data_path = CFStringGetCStringPtr(table_data_cstr_path, kCFStringEncodingUTF8);
1364 if (NULL == table_data_path) {
1365 if (CFStringGetCString(table_data_cstr_path, file_path_buffer, PATH_MAX, kCFStringEncodingUTF8)) {
1366 table_data_path = file_path_buffer;
1369 local_anchorTable = (char *)MapFile(table_data_path, &local_anchorTableSize);
1370 CFReleaseSafe(table_data_cstr_path);
1373 CFReleaseSafe(table_data_url);
1375 if (NULL == local_anchorTable || NULL == cert_index_file_data) {
1376 // we are in trouble
1377 if (NULL != local_anchorTable) {
1378 UnMapFile(local_anchorTable, local_anchorTableSize);
1379 local_anchorTable = NULL;
1380 local_anchorTableSize = 0;
1382 CFReleaseSafe(cert_index_file_data);
1386 // ------------------------------------------------------------------------
1387 // Now that the locations of the files are known and the table file has
1388 // been mapped into memory, create a dictionary that maps the SHA1 hash of
1389 // normalized issuer to the offset in the mapped anchor table file which
1390 // contains a index_record to the correct certificate
1391 // ------------------------------------------------------------------------
1392 pIndex = (const index_record*)CFDataGetBytePtr(cert_index_file_data);
1393 index_data_size = CFDataGetLength(cert_index_file_data);
1395 anchorLookupTable = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
1396 &kCFTypeDictionaryKeyCallBacks,
1397 &kCFTypeDictionaryValueCallBacks);
1399 for (index_offset = index_data_size; index_offset > 0; index_offset -= sizeof(index_record), pIndex++) {
1400 offset_int_value = pIndex->offset;
1402 index_offset_value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &offset_int_value);
1403 index_hash = CFDataCreate(kCFAllocatorDefault, pIndex->hash, CC_SHA1_DIGEST_LENGTH);
1405 // see if the dictionary already has this key
1406 release_offset = false;
1407 offsets = (CFMutableArrayRef)CFDictionaryGetValue(anchorLookupTable, index_hash);
1408 if (NULL == offsets) {
1409 offsets = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
1410 release_offset = true;
1414 CFArrayAppendValue(offsets, index_offset_value);
1416 // set the key value pair in the dictionary
1417 CFDictionarySetValue(anchorLookupTable, index_hash, offsets);
1419 CFRelease(index_offset_value);
1420 CFRelease(index_hash);
1421 if (release_offset) {
1426 CFRelease(cert_index_file_data);
1428 if (NULL != anchorLookupTable && NULL != local_anchorTable) {
1429 *pLookupTable = anchorLookupTable;
1430 *ppAnchorTable = local_anchorTable;
1433 CFReleaseSafe(anchorLookupTable);
1434 if (NULL != local_anchorTable) {
1435 UnMapFile(local_anchorTable, local_anchorTableSize);
1436 local_anchorTable = NULL;
1437 local_anchorTableSize = 0;
1444 static void InitializeEscrowCertificates(CFArrayRef *escrowRoots, CFArrayRef *escrowPCSRoots) {
1445 CFDataRef file_data = SecSystemTrustStoreCopyResourceContents(CFSTR("AppleESCertificates"), CFSTR("plist"), NULL);
1447 if (NULL == file_data) {
1451 CFPropertyListFormat propFormat;
1452 CFDictionaryRef certsDictionary = CFPropertyListCreateWithData(kCFAllocatorDefault, file_data, 0, &propFormat, NULL);
1453 if (NULL != certsDictionary && CFDictionaryGetTypeID() == CFGetTypeID((CFTypeRef)certsDictionary)) {
1454 CFArrayRef certs = (CFArrayRef)CFDictionaryGetValue(certsDictionary, CFSTR("ProductionEscrowKey"));
1455 if (NULL != certs && CFArrayGetTypeID() == CFGetTypeID((CFTypeRef)certs) && CFArrayGetCount(certs) > 0) {
1456 *escrowRoots = CFArrayCreateCopy(kCFAllocatorDefault, certs);
1458 CFArrayRef pcs_certs = (CFArrayRef)CFDictionaryGetValue(certsDictionary, CFSTR("ProductionPCSEscrowKey"));
1459 if (NULL != pcs_certs && CFArrayGetTypeID() == CFGetTypeID((CFTypeRef)pcs_certs) && CFArrayGetCount(pcs_certs) > 0) {
1460 *escrowPCSRoots = CFArrayCreateCopy(kCFAllocatorDefault, pcs_certs);
1463 CFReleaseSafe(certsDictionary);
1464 CFRelease(file_data);
1467 static CF_RETURNS_RETAINED CFDictionaryRef InitializeEventSamplingRates() {
1468 NSDictionary *analyticsSamplingRates = nil;
1469 NSDictionary *eventSamplingRates = nil;
1470 NSError *error = nil;
1471 #if !TARGET_OS_BRIDGE
1472 if (ShouldInitializeWithAsset()) {
1473 analyticsSamplingRates = [NSDictionary dictionaryWithContentsOfURL:GetAssetFileURL(kOTATrustAnalyticsSamplingRatesFilename) error:&error];
1474 if (!isNSDictionary(analyticsSamplingRates)) {
1475 secerror("OTATrust: failed to read sampling rates from asset data: %@", error);
1476 LogRemotely(OTATrustLogLevelError, &error);
1477 if (!DeleteAssetFromDisk()) {
1478 initialization_error_from_asset_data = true;
1481 eventSamplingRates = analyticsSamplingRates[@"Events"];
1484 if (!isNSDictionary(eventSamplingRates)) {
1485 analyticsSamplingRates = [NSDictionary dictionaryWithContentsOfURL:SecSystemTrustStoreCopyResourceNSURL(kOTATrustAnalyticsSamplingRatesFilename)];
1487 if (isNSDictionary(analyticsSamplingRates)) {
1488 eventSamplingRates = analyticsSamplingRates[@"Events"];
1489 if (isNSDictionary(eventSamplingRates)) {
1490 return CFBridgingRetain(eventSamplingRates);
1496 static CF_RETURNS_RETAINED CFArrayRef InitializeAppleCertificateAuthorities() {
1497 NSArray *appleCAs = nil;
1498 NSError *error = nil;
1499 #if !TARGET_OS_BRIDGE
1500 if (ShouldInitializeWithAsset()) {
1501 appleCAs = [NSArray arrayWithContentsOfURL:GetAssetFileURL(kOTATrustAppleCertifcateAuthoritiesFilename) error:&error];
1502 if (!isNSArray(appleCAs)) {
1503 secerror("OTATrust: failed to read Apple CAs list from asset data: %@", error);
1504 LogRemotely(OTATrustLogLevelError, &error);
1505 if (!DeleteAssetFromDisk()) {
1506 initialization_error_from_asset_data = true;
1511 if (!isNSArray(appleCAs)) {
1512 appleCAs = [NSArray arrayWithContentsOfURL:SecSystemTrustStoreCopyResourceNSURL(kOTATrustAppleCertifcateAuthoritiesFilename)];
1514 if (isNSArray(appleCAs)) {
1515 return CFBridgingRetain(appleCAs);
1523 /* We keep track of one OTAPKI reference */
1524 static SecOTAPKIRef kCurrentOTAPKIRef = NULL;
1525 /* This queue is for making changes to the OTAPKI reference */
1526 static dispatch_queue_t kOTAQueue = NULL;
1528 struct _OpaqueSecOTAPKI {
1529 CFRuntimeBase _base;
1530 CFSetRef _blackListSet;
1531 CFSetRef _grayListSet;
1532 CFDictionaryRef _allowList;
1533 CFArrayRef _trustedCTLogs;
1534 CFURLRef _pinningList;
1535 CFArrayRef _escrowCertificates;
1536 CFArrayRef _escrowPCSCertificates;
1537 CFDictionaryRef _evPolicyToAnchorMapping;
1538 CFDictionaryRef _anchorLookupTable;
1539 const char* _anchorTable;
1540 uint64_t _trustStoreVersion;
1541 const char* _validDatabaseSnapshot;
1542 CFIndex _validSnapshotVersion;
1543 CFIndex _validSnapshotFormat;
1544 uint64_t _assetVersion;
1545 CFDateRef _lastAssetCheckIn;
1546 CFDictionaryRef _eventSamplingRates;
1547 CFArrayRef _appleCAs;
1551 CFGiblisFor(SecOTAPKI)
1553 static CF_RETURNS_RETAINED CFStringRef SecOTAPKICopyFormatDescription(CFTypeRef cf, CFDictionaryRef formatOptions) {
1554 SecOTAPKIRef otapkiRef = (SecOTAPKIRef)cf;
1555 return CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR("<SecOTAPKIRef: version %llu/%llu>"),
1556 otapkiRef->_trustStoreVersion, otapkiRef->_assetVersion);
1559 static void SecOTAPKIDestroy(CFTypeRef cf) {
1560 SecOTAPKIRef otapkiref = (SecOTAPKIRef)cf;
1562 CFReleaseNull(otapkiref->_blackListSet);
1563 CFReleaseNull(otapkiref->_grayListSet);
1564 CFReleaseNull(otapkiref->_escrowCertificates);
1565 CFReleaseNull(otapkiref->_escrowPCSCertificates);
1567 CFReleaseNull(otapkiref->_evPolicyToAnchorMapping);
1568 CFReleaseNull(otapkiref->_anchorLookupTable);
1570 CFReleaseNull(otapkiref->_trustedCTLogs);
1571 CFReleaseNull(otapkiref->_pinningList);
1572 CFReleaseNull(otapkiref->_eventSamplingRates);
1573 CFReleaseNull(otapkiref->_appleCAs);
1574 CFReleaseNull(otapkiref->_lastAssetCheckIn);
1576 if (otapkiref->_anchorTable) {
1577 free((void *)otapkiref->_anchorTable);
1578 otapkiref->_anchorTable = NULL;
1580 if (otapkiref->_validDatabaseSnapshot) {
1581 free((void *)otapkiref->_validDatabaseSnapshot);
1582 otapkiref->_validDatabaseSnapshot = NULL;
1586 static uint64_t GetSystemTrustStoreVersion(void) {
1587 return GetSystemVersion(CFSTR("VersionNumber"));
1590 static uint64_t GetAssetVersion(CFErrorRef *error) {
1592 /* Get system asset version */
1593 uint64_t version = GetSystemVersion((__bridge CFStringRef)kOTATrustContentVersionKey);
1595 #if !TARGET_OS_BRIDGE
1596 uint64_t asset_version = 0;
1597 NSError *nserror = nil;
1598 NSDictionary *OTAPKIContext = [NSDictionary dictionaryWithContentsOfURL:GetAssetFileURL(kOTATrustContextFilename) error:&nserror];
1599 if (isNSDictionary(OTAPKIContext)) {
1600 NSNumber *tmpNumber = OTAPKIContext[kOTATrustContentVersionKey];
1601 if (isNSNumber(tmpNumber)) {
1602 asset_version = [tmpNumber unsignedLongLongValue];
1604 MakeOTATrustError(&nserror, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecInvalidValue,
1605 @"OTAContext.plist missing version");
1608 MakeOTATrustError(&nserror, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecMissingValue,
1609 @"OTAContext.plist missing dictionary");
1612 if (asset_version > version) {
1613 return asset_version;
1615 /* Don't delete the last check-in time so that we know we're up to date with the MobileAsset. */
1617 /* only log this if we're tracking errors */
1618 secnotice("OTATrust", "asset (%llu) is not newer than the system version (%llu); deleting stale data", asset_version, version);
1619 *error = CFRetainSafe((__bridge CFErrorRef)nserror);
1621 DeleteOldAssetData();
1628 static CF_RETURNS_RETAINED CFDateRef InitializeLastAssetCheckIn(void) {
1629 #if !TARGET_OS_BRIDGE
1630 NSError *error = nil;
1631 NSDictionary *OTAPKIContext = [NSDictionary dictionaryWithContentsOfURL:GetAssetFileURL(kOTATrustContextFilename) error:&error];
1632 if (isNSDictionary(OTAPKIContext)) {
1633 NSDate *checkIn = OTAPKIContext[kOTATrustLastCheckInKey];
1634 if (isNSDate(checkIn)) {
1635 return CFRetainSafe((__bridge CFDateRef)checkIn);
1637 MakeOTATrustError(&error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecInvalidValue,
1638 @"OTAContext.plist missing check-in");
1641 MakeOTATrustError(&error, OTATrustLogLevelNotice, NSOSStatusErrorDomain, errSecMissingValue,
1642 @"OTAContext.plist missing dictionary");
1648 static SecOTAPKIRef SecOTACreate() {
1650 SecOTAPKIRef otapkiref = NULL;
1652 otapkiref = CFTypeAllocate(SecOTAPKI, struct _OpaqueSecOTAPKI , kCFAllocatorDefault);
1654 if (NULL == otapkiref) {
1658 // Make sure that if this routine has to bail that the clean up
1659 // will do the right thing
1660 memset(otapkiref, 0, sizeof(*otapkiref));
1662 // Start off by getting the trust store version
1663 otapkiref->_trustStoreVersion = GetSystemTrustStoreVersion();
1665 // Get the set of black listed keys
1666 CFSetRef blackKeysSet = InitializeBlackList();
1667 if (NULL == blackKeysSet) {
1668 CFReleaseNull(otapkiref);
1671 otapkiref->_blackListSet = blackKeysSet;
1673 // Get the set of gray listed keys
1674 CFSetRef grayKeysSet = InitializeGrayList();
1675 if (NULL == grayKeysSet) {
1676 CFReleaseNull(otapkiref);
1679 otapkiref->_grayListSet = grayKeysSet;
1681 // Get the allow list dictionary
1682 // (now loaded lazily in SecOTAPKICopyAllowList)
1684 // Get the trusted Certificate Transparency Logs
1685 otapkiref->_trustedCTLogs = InitializeTrustedCTLogs();
1687 // Get the pinning list
1688 otapkiref->_pinningList = InitializePinningList();
1690 // Get the Event Sampling Rates
1691 otapkiref->_eventSamplingRates = InitializeEventSamplingRates();
1693 // Get the list of CAs used by Apple
1694 otapkiref->_appleCAs = InitializeAppleCertificateAuthorities();
1696 // Get the asset version (after possible reset due to missing asset data)
1697 if (!initialization_error_from_asset_data) {
1698 CFErrorRef error = nil;
1699 otapkiref->_assetVersion = GetAssetVersion(&error);
1700 otapkiref->_lastAssetCheckIn = InitializeLastAssetCheckIn();
1701 CFReleaseNull(error);
1703 otapkiref->_assetVersion = GetSystemVersion((__bridge CFStringRef)kOTATrustContentVersionKey);
1706 // Get the valid update snapshot version and format
1707 CFIndex update_format = 0;
1708 otapkiref->_validSnapshotVersion = InitializeValidSnapshotVersion(&update_format);
1709 otapkiref->_validSnapshotFormat = update_format;
1711 // Get the valid database snapshot path (if it exists, NULL otherwise)
1712 otapkiref->_validDatabaseSnapshot = InitializeValidDatabaseSnapshot();
1714 CFArrayRef escrowCerts = NULL;
1715 CFArrayRef escrowPCSCerts = NULL;
1716 InitializeEscrowCertificates(&escrowCerts, &escrowPCSCerts);
1717 if (NULL == escrowCerts || NULL == escrowPCSCerts) {
1718 CFReleaseNull(escrowCerts);
1719 CFReleaseNull(escrowPCSCerts);
1720 CFReleaseNull(otapkiref);
1723 otapkiref->_escrowCertificates = escrowCerts;
1724 otapkiref->_escrowPCSCertificates = escrowPCSCerts;
1726 // Get the mapping of EV Policy OIDs to Anchor digest
1727 CFDictionaryRef evOidToAnchorDigestMap = InitializeEVPolicyToAnchorDigestsTable();
1728 if (NULL == evOidToAnchorDigestMap) {
1729 CFReleaseNull(otapkiref);
1732 otapkiref->_evPolicyToAnchorMapping = evOidToAnchorDigestMap;
1734 CFDictionaryRef anchorLookupTable = NULL;
1735 const char* anchorTablePtr = NULL;
1737 if (!InitializeAnchorTable(&anchorLookupTable, &anchorTablePtr)) {
1738 CFReleaseSafe(anchorLookupTable);
1739 if (anchorTablePtr) {
1740 free((void *)anchorTablePtr);
1742 CFReleaseNull(otapkiref);
1745 otapkiref->_anchorLookupTable = anchorLookupTable;
1746 otapkiref->_anchorTable = anchorTablePtr;
1748 #if !TARGET_OS_BRIDGE
1749 /* Initialize our update handling */
1750 InitializeOTATrustAsset(kOTABackgroundQueue);
1751 otapkiref->_ctKillSwitch = InitializeKillSwitch(kOTATrustCTKillSwitch);
1752 #else // TARGET_OS_BRIDGE
1753 otapkiref->_ctKillSwitch = true; // bridgeOS never enforces CT
1754 #endif // TARGET_OS_BRIDGE
1759 SecOTAPKIRef SecOTAPKICopyCurrentOTAPKIRef() {
1760 __block SecOTAPKIRef result = NULL;
1761 static dispatch_once_t kInitializeOTAPKI = 0;
1762 dispatch_once(&kInitializeOTAPKI, ^{
1764 kOTAQueue = dispatch_queue_create("com.apple.security.OTAPKIQueue", NULL);
1765 dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,
1766 QOS_CLASS_BACKGROUND, 0);
1767 attr = dispatch_queue_attr_make_with_autorelease_frequency(attr, DISPATCH_AUTORELEASE_FREQUENCY_WORK_ITEM);
1768 kOTABackgroundQueue = dispatch_queue_create("com.apple.security.OTAPKIBackgroundQueue", attr);
1769 if (!kOTAQueue || !kOTABackgroundQueue) {
1770 secerror("Failed to create OTAPKI Queues. May crash later.");
1772 dispatch_sync(kOTAQueue, ^{
1773 kCurrentOTAPKIRef = SecOTACreate();
1778 dispatch_sync(kOTAQueue, ^{
1779 result = kCurrentOTAPKIRef;
1780 CFRetainSafe(result);
1785 #if !TARGET_OS_BRIDGE
1786 static BOOL UpdateOTACheckInDate(void) {
1787 __block NSDate *checkIn = [NSDate date];
1788 dispatch_sync(kOTAQueue, ^{
1789 CFRetainAssign(kCurrentOTAPKIRef->_lastAssetCheckIn, (__bridge CFDateRef)checkIn);
1792 if (SecOTAPKIIsSystemTrustd()) {
1793 /* Let the other trustds know we successfully checked in */
1794 notify_post(kOTATrustCheckInNotification);
1796 /* Update the on-disk check-in date, so when we re-launch we remember */
1797 NSError *error = nil;
1799 if (!(result = UpdateOTAContextOnDisk(kOTATrustLastCheckInKey, checkIn, &error))) {
1800 secerror("OTATrust: failed to write last check-in time: %@", error);
1808 static void UpdateKillSwitch(NSString *key, bool value) {
1809 dispatch_sync(kOTAQueue, ^{
1810 if ([key isEqualToString:kOTATrustCTKillSwitch]) {
1811 kCurrentOTAPKIRef->_ctKillSwitch = value;
1816 static BOOL UpdateFromAsset(NSURL *localURL, NSNumber *asset_version, NSError **error) {
1817 if (!localURL || !asset_version) {
1818 MakeOTATrustError(error, OTATrustLogLevelError, NSOSStatusErrorDomain, errSecInternal,
1819 @"missing url and version for downloaded asset");
1822 __block NSArray *newTrustedCTLogs = NULL;
1823 __block uint64_t version = [asset_version unsignedLongLongValue];
1824 __block NSDictionary *newAnalyticsSamplingRates = NULL;
1825 __block NSArray *newAppleCAs = NULL;
1827 NSURL *TrustedCTLogsFileLoc = [NSURL URLWithString:kOTATrustTrustedCTLogsFilename
1828 relativeToURL:localURL];
1829 newTrustedCTLogs = [NSArray arrayWithContentsOfURL:TrustedCTLogsFileLoc error:error];
1830 if (!newTrustedCTLogs) {
1831 secerror("OTATrust: unable to create TrustedCTLogs from asset file: %@", error ? *error: nil);
1832 LogRemotely(OTATrustLogLevelError, error);
1836 NSURL *AnalyticsSamplingRatesFileLoc = [NSURL URLWithString:kOTATrustAnalyticsSamplingRatesFilename
1837 relativeToURL:localURL];
1838 newAnalyticsSamplingRates = [NSDictionary dictionaryWithContentsOfURL:AnalyticsSamplingRatesFileLoc error:error];
1839 if (!newAnalyticsSamplingRates) {
1840 secerror("OTATrust: unable to create AnalyticsSamplingRates from asset file: %@", error ? *error: nil);
1841 LogRemotely(OTATrustLogLevelError, error);
1845 NSURL *AppleCAsFileLoc = [NSURL URLWithString:kOTATrustAppleCertifcateAuthoritiesFilename
1846 relativeToURL:localURL];
1847 newAppleCAs = [NSArray arrayWithContentsOfURL:AppleCAsFileLoc error:error];
1849 secerror("OTATrust: unable to create AppleCAs from asset file: %@", error ? *error: nil);
1850 LogRemotely(OTATrustLogLevelError, error);
1854 /* Update the Current OTAPKIRef with the new data */
1855 dispatch_sync(kOTAQueue, ^{
1856 secnotice("OTATrust", "updating asset version from %llu to %llu", kCurrentOTAPKIRef->_assetVersion, version);
1857 CFRetainAssign(kCurrentOTAPKIRef->_trustedCTLogs, (__bridge CFArrayRef)newTrustedCTLogs);
1858 CFRetainAssign(kCurrentOTAPKIRef->_eventSamplingRates, (__bridge CFDictionaryRef)newAnalyticsSamplingRates);
1859 CFRetainAssign(kCurrentOTAPKIRef->_appleCAs, (__bridge CFArrayRef)newAppleCAs);
1860 kCurrentOTAPKIRef->_assetVersion = version;
1863 /* Write the data to disk (so that we don't have to re-download the asset on re-launch) */
1864 DeleteAssetFromDisk();
1865 if (CopyFileToDisk(kOTATrustTrustedCTLogsFilename, TrustedCTLogsFileLoc, error) &&
1866 CopyFileToDisk(kOTATrustAnalyticsSamplingRatesFilename, AnalyticsSamplingRatesFileLoc, error) &&
1867 CopyFileToDisk(kOTATrustAppleCertifcateAuthoritiesFilename, AppleCAsFileLoc, error) &&
1868 UpdateOTAContext(asset_version, error)) { // Set version and check-in time last (after success)
1869 /* If we successfully updated the "asset" on disk, signal the other trustds to pick up the changes */
1870 notify_post(kOTATrustOnDiskAssetNotification);
1877 #endif // !TARGET_OS_BRIDGE
1880 CFSetRef SecOTAPKICopyBlackListSet(SecOTAPKIRef otapkiRef) {
1881 if (NULL == otapkiRef) {
1885 return CFRetainSafe(otapkiRef->_blackListSet);
1889 CFSetRef SecOTAPKICopyGrayList(SecOTAPKIRef otapkiRef) {
1890 if (NULL == otapkiRef) {
1894 return CFRetainSafe(otapkiRef->_grayListSet);
1897 CFDictionaryRef SecOTAPKICopyAllowList(SecOTAPKIRef otapkiRef) {
1898 if (NULL == otapkiRef) {
1902 CFDictionaryRef result = otapkiRef->_allowList;
1904 result = InitializeAllowList();
1905 otapkiRef->_allowList = result;
1908 return CFRetainSafe(result);
1911 CFArrayRef SecOTAPKICopyAllowListForAuthKeyID(SecOTAPKIRef otapkiRef, CFStringRef authKeyID) {
1912 // %%% temporary performance optimization:
1913 // only load dictionary if we know an allow list exists for this key
1914 const CFStringRef keyIDs[3] = {
1915 CFSTR("7C724B39C7C0DB62A54F9BAA183492A2CA838259"),
1916 CFSTR("65F231AD2AF7F7DD52960AC702C10EEFA6D53B11"),
1917 CFSTR("D2A716207CAFD9959EEB430A19F2E0B9740EA8C7")
1919 CFArrayRef result = NULL;
1920 bool hasAllowList = false;
1921 CFIndex count = (sizeof(keyIDs) / sizeof(keyIDs[0]));
1922 for (CFIndex ix=0; ix<count && authKeyID; ix++) {
1923 if (kCFCompareEqualTo == CFStringCompare(authKeyID, keyIDs[ix], 0)) {
1924 hasAllowList = true;
1928 if (!hasAllowList || !otapkiRef) {
1932 CFDictionaryRef allowListDict = SecOTAPKICopyAllowList(otapkiRef);
1933 if (!allowListDict) {
1937 // return a retained copy of the allow list array (or NULL)
1938 result = CFDictionaryGetValue(allowListDict, authKeyID);
1939 CFRetainSafe(result);
1940 CFReleaseSafe(allowListDict);
1944 CFArrayRef SecOTAPKICopyTrustedCTLogs(SecOTAPKIRef otapkiRef) {
1945 CFArrayRef result = NULL;
1946 if (NULL == otapkiRef) {
1950 #if !TARGET_OS_BRIDGE
1951 /* Trigger periodic background MA checks in system trustd
1952 * We also check on trustd launch and listen for notifications. */
1953 TriggerPeriodicOTATrustAssetChecks(kOTABackgroundQueue);
1956 result = otapkiRef->_trustedCTLogs;
1957 CFRetainSafe(result);
1961 CFURLRef SecOTAPKICopyPinningList(SecOTAPKIRef otapkiRef) {
1962 if (NULL == otapkiRef) {
1966 return CFRetainSafe(otapkiRef->_pinningList);
1970 /* Returns an array of certificate data (CFDataRef) */
1971 CFArrayRef SecOTAPKICopyEscrowCertificates(uint32_t escrowRootType, SecOTAPKIRef otapkiRef) {
1972 CFMutableArrayRef result = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
1973 if (NULL == otapkiRef) {
1977 switch (escrowRootType) {
1978 // Note: we shouldn't be getting called to return baseline roots,
1979 // since this function vends production roots by definition.
1980 case kSecCertificateBaselineEscrowRoot:
1981 case kSecCertificateProductionEscrowRoot:
1982 case kSecCertificateBaselineEscrowBackupRoot:
1983 case kSecCertificateProductionEscrowBackupRoot:
1984 if (otapkiRef->_escrowCertificates) {
1985 CFArrayRef escrowCerts = otapkiRef->_escrowCertificates;
1986 CFArrayAppendArray(result, escrowCerts, CFRangeMake(0, CFArrayGetCount(escrowCerts)));
1989 case kSecCertificateBaselineEscrowEnrollmentRoot:
1990 case kSecCertificateProductionEscrowEnrollmentRoot:
1991 if (otapkiRef->_escrowCertificates) {
1992 // for enrollment purposes, exclude the v100 root
1993 static const unsigned char V100EscrowRoot[] = {
1994 0x65,0x5C,0xB0,0x3C,0x39,0x3A,0x32,0xA6,0x0B,0x96,
1995 0x40,0xC0,0xCA,0x73,0x41,0xFD,0xC3,0x9E,0x96,0xB3
1997 CFArrayRef escrowCerts = otapkiRef->_escrowCertificates;
1998 CFIndex idx, count = CFArrayGetCount(escrowCerts);
1999 for (idx=0; idx < count; idx++) {
2000 CFDataRef tmpData = (CFDataRef) CFArrayGetValueAtIndex(escrowCerts, idx);
2001 SecCertificateRef tmpCert = (tmpData) ? SecCertificateCreateWithData(NULL, tmpData) : NULL;
2002 CFDataRef sha1Hash = (tmpCert) ? SecCertificateGetSHA1Digest(tmpCert) : NULL;
2003 const uint8_t *dp = (sha1Hash) ? CFDataGetBytePtr(sha1Hash) : NULL;
2004 if (!(dp && !memcmp(V100EscrowRoot, dp, sizeof(V100EscrowRoot))) && tmpData) {
2005 CFArrayAppendValue(result, tmpData);
2007 CFReleaseSafe(tmpCert);
2011 case kSecCertificateBaselinePCSEscrowRoot:
2012 case kSecCertificateProductionPCSEscrowRoot:
2013 if (otapkiRef->_escrowPCSCertificates) {
2014 CFArrayRef escrowPCSCerts = otapkiRef->_escrowPCSCertificates;
2015 CFArrayAppendArray(result, escrowPCSCerts, CFRangeMake(0, CFArrayGetCount(escrowPCSCerts)));
2026 CFDictionaryRef SecOTAPKICopyEVPolicyToAnchorMapping(SecOTAPKIRef otapkiRef) {
2027 if (NULL == otapkiRef) {
2031 return CFRetainSafe(otapkiRef->_evPolicyToAnchorMapping);
2035 CFDictionaryRef SecOTAPKICopyAnchorLookupTable(SecOTAPKIRef otapkiRef) {
2036 if (NULL == otapkiRef) {
2040 return CFRetainSafe(otapkiRef->_anchorLookupTable);
2043 const char* SecOTAPKIGetAnchorTable(SecOTAPKIRef otapkiRef) {
2044 if (NULL == otapkiRef) {
2048 return otapkiRef->_anchorTable;
2051 const char* SecOTAPKIGetValidDatabaseSnapshot(SecOTAPKIRef otapkiRef) {
2052 if (NULL == otapkiRef) {
2056 return otapkiRef->_validDatabaseSnapshot;
2059 CFIndex SecOTAPKIGetValidSnapshotVersion(SecOTAPKIRef otapkiRef) {
2060 if (NULL == otapkiRef) {
2064 return otapkiRef->_validSnapshotVersion;
2067 CFIndex SecOTAPKIGetValidSnapshotFormat(SecOTAPKIRef otapkiRef) {
2068 if (NULL == otapkiRef) {
2072 return otapkiRef->_validSnapshotFormat;
2075 uint64_t SecOTAPKIGetTrustStoreVersion(SecOTAPKIRef otapkiRef) {
2076 if (NULL == otapkiRef) {
2080 return otapkiRef->_trustStoreVersion;
2083 uint64_t SecOTAPKIGetAssetVersion(SecOTAPKIRef otapkiRef) {
2084 if (NULL == otapkiRef) {
2088 return otapkiRef->_assetVersion;
2091 CFDateRef SecOTAPKICopyLastAssetCheckInDate(SecOTAPKIRef otapkiRef) {
2092 if (NULL == otapkiRef) {
2095 return CFRetainSafe(otapkiRef->_lastAssetCheckIn);
2098 bool SecOTAPKIAssetStalenessLessThanSeconds(SecOTAPKIRef otapkiRef, CFTimeInterval seconds) {
2099 if (NULL == otapkiRef || !isDate(otapkiRef->_lastAssetCheckIn)) {
2102 if(fabs([(__bridge NSDate *)otapkiRef->_lastAssetCheckIn timeIntervalSinceNow]) < seconds) {
2108 NSNumber *SecOTAPKIGetSamplingRateForEvent(SecOTAPKIRef otapkiRef, NSString *eventName) {
2109 if (NULL == otapkiRef) {
2113 #if !TARGET_OS_BRIDGE
2114 /* Trigger periodic background MA checks in system trustd
2115 * We also check on trustd launch and listen for notifications. */
2116 TriggerPeriodicOTATrustAssetChecks(kOTABackgroundQueue);
2119 if (otapkiRef->_eventSamplingRates) {
2120 CFTypeRef value = CFDictionaryGetValue(otapkiRef->_eventSamplingRates, (__bridge CFStringRef)eventName);
2121 if (isNumberOfType(value, kCFNumberSInt64Type)) {
2122 return (__bridge NSNumber *)value;
2128 CFArrayRef SecOTAPKICopyAppleCertificateAuthorities(SecOTAPKIRef otapkiRef) {
2129 if (NULL == otapkiRef) {
2133 #if !TARGET_OS_BRIDGE
2134 /* Trigger periodic background MA checks in system trustd
2135 * We also check on trustd launch and listen for notifications. */
2136 TriggerPeriodicOTATrustAssetChecks(kOTABackgroundQueue);
2139 return CFRetainSafe(otapkiRef->_appleCAs);
2142 bool SecOTAPKIKillSwitchEnabled(SecOTAPKIRef otapkiRef, CFStringRef key) {
2143 if (NULL == otapkiRef || NULL == key) {
2146 if (CFEqualSafe(key, kOTAPKIKillSwitchCT)) {
2147 return otapkiRef->_ctKillSwitch;
2152 /* Returns an array of certificate data (CFDataRef) */
2153 CFArrayRef SecOTAPKICopyCurrentEscrowCertificates(uint32_t escrowRootType, CFErrorRef* error) {
2154 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
2155 if (NULL == otapkiref) {
2156 SecError(errSecInternal, error, CFSTR("Unable to get the current OTAPKIRef"));
2160 CFArrayRef result = SecOTAPKICopyEscrowCertificates(escrowRootType, otapkiref);
2161 CFRelease(otapkiref);
2163 if (NULL == result) {
2164 SecError(errSecInternal, error, CFSTR("Could not get escrow certificates from the current OTAPKIRef"));
2169 uint64_t SecOTAPKIGetCurrentTrustStoreVersion(CFErrorRef* error){
2170 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
2171 if (NULL == otapkiref) {
2172 SecError(errSecInternal, error, CFSTR("Unable to get the current OTAPKIRef"));
2176 return otapkiref->_trustStoreVersion;
2179 uint64_t SecOTAPKIGetCurrentAssetVersion(CFErrorRef* error) {
2180 SecOTAPKIRef otapkiref = SecOTAPKICopyCurrentOTAPKIRef();
2181 if (NULL == otapkiref) {
2182 SecError(errSecInternal, error, CFSTR("Unable to get the current OTAPKIRef"));
2186 return otapkiref->_assetVersion;
2189 uint64_t SecOTAPKIResetCurrentAssetVersion(CFErrorRef* error) {
2190 uint64_t system_version = GetSystemVersion((__bridge CFStringRef)kOTATrustContentVersionKey);
2192 dispatch_sync(kOTAQueue, ^{
2193 kCurrentOTAPKIRef->_assetVersion = system_version;
2194 CFReleaseNull(kCurrentOTAPKIRef->_lastAssetCheckIn);
2195 kCurrentOTAPKIRef->_lastAssetCheckIn = NULL;
2198 #if !TARGET_OS_BRIDGE
2199 DeleteAssetFromDisk();
2201 return system_version;
2204 uint64_t SecOTAPKISignalNewAsset(CFErrorRef* error) {
2205 NSError *nserror = nil;
2206 uint64_t version = 0;
2207 #if !TARGET_OS_BRIDGE
2208 if (SecOTAPKIIsSystemTrustd()) {
2209 if (!DownloadOTATrustAsset(NO, YES, &nserror) && error) {
2210 *error = CFRetainSafe((__bridge CFErrorRef)nserror);
2213 SecError(errSecServiceNotAvailable, error, CFSTR("This function may ony be performed by the system trustd."));
2215 version = GetAssetVersion(nil);
2217 SecError(errSecUnsupportedService, error, CFSTR("This function is not available on this platform"));
2218 version = GetAssetVersion(error);