2 * Copyright (c) 2017-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 #if !TARGET_OS_SIMULATOR
28 #import "SFAnalyticsDefines.h"
29 #import "SFAnalyticsSQLiteStore.h"
30 #import <Security/SFAnalytics.h>
32 #include <utilities/SecFileLocations.h>
33 #import "utilities/debugging.h"
34 #import <os/variant_private.h>
37 #import "keychain/ckks/CKKSControl.h"
40 #import <AuthKit/AKAppleIDAuthenticationContext.h>
41 #import <AuthKit/AKAppleIDAuthenticationController.h>
42 #import <AuthKit/AKAppleIDAuthenticationController_Private.h>
45 #include "dirhelper_priv.h"
46 #include <membership.h>
50 #import <CrashReporterSupport/CrashReporterSupportPrivate.h>
52 #import <CrashReporterSupport/CrashReporterSupport.h>
55 #import <Accounts/Accounts.h>
56 #import <Accounts/ACAccountStore_Private.h>
57 #import <Accounts/ACAccountType_Private.h>
58 #import <Accounts/ACAccountStore.h>
59 #import <AppleAccount/AppleAccount.h>
60 #import <AppleAccount/ACAccount+AppleAccount.h>
61 #import <AppleAccount/ACAccountStore+AppleAccount.h>
63 #import "utilities/simulatecrash_assert.h"
66 NSString* const SFAnalyticsSplunkTopic = @"topic";
67 NSString* const SFAnalyticsClientId = @"clientId";
68 NSString* const SFAnalyticsInternal = @"internal";
70 NSString* const SFAnalyticsMetricsBase = @"metricsBase";
71 NSString* const SFAnalyticsDeviceID = @"ckdeviceID";
72 NSString* const SFAnalyticsAltDSID = @"altDSID";
74 NSString* const SFAnalyticsEventCorrelationID = @"eventLinkID";
76 NSString* const SFAnalyticsSecondsCustomerKey = @"SecondsBetweenUploadsCustomer";
77 NSString* const SFAnalyticsSecondsInternalKey = @"SecondsBetweenUploadsInternal";
78 NSString* const SFAnalyticsSecondsSeedKey = @"SecondsBetweenUploadsSeed";
79 NSString* const SFAnalyticsMaxEventsKey = @"NumberOfEvents";
80 NSString* const SFAnalyticsDevicePercentageCustomerKey = @"DevicePercentageCustomer";
81 NSString* const SFAnalyticsDevicePercentageInternalKey = @"DevicePercentageInternal";
82 NSString* const SFAnalyticsDevicePercentageSeedKey = @"DevicePercentageSeed";
84 NSString* const SupdErrorDomain = @"com.apple.security.supd";
86 #define SFANALYTICS_SPLUNK_DEV 0
87 #define OS_CRASH_TRACER_LOG_BUG_TYPE "226"
89 #if SFANALYTICS_SPLUNK_DEV
90 NSUInteger const secondsBetweenUploadsCustomer = 10;
91 NSUInteger const secondsBetweenUploadsInternal = 10;
92 NSUInteger const secondsBetweenUploadsSeed = 10;
93 #else // SFANALYTICS_SPLUNK_DEV
94 NSUInteger const secondsBetweenUploadsCustomer = (3 * (60 * 60 * 24));
95 NSUInteger const secondsBetweenUploadsInternal = (60 * 60 * 24);
96 NSUInteger const secondsBetweenUploadsSeed = (60 * 60 * 24);
97 #endif // SFANALYTICS_SPLUNK_DEV
99 @implementation SFAnalyticsReporter
100 - (BOOL)saveReport:(NSData *)reportData fileName:(NSString *)fileName
102 BOOL writtenToLog = NO;
104 NSDictionary *optionsDictionary = @{ (__bridge NSString *)kCRProblemReportSubmissionPolicyKey: (__bridge NSString *)kCRSubmissionPolicyAlternate };
105 #else // !TARGET_OS_OSX
106 NSDictionary *optionsDictionary = nil; // The keys above are not defined or required on iOS.
107 #endif // !TARGET_OS_OSX
110 secdebug("saveReport", "calling out to `OSAWriteLogForSubmission`");
111 writtenToLog = OSAWriteLogForSubmission(@OS_CRASH_TRACER_LOG_BUG_TYPE, fileName,
112 nil, optionsDictionary, ^(NSFileHandle *fileHandle) {
113 secnotice("OSAWriteLogForSubmission", "Writing log data to report: %@", fileName);
114 [fileHandle writeData:reportData];
120 #define DEFAULT_SPLUNK_MAX_EVENTS_TO_REPORT 1000
121 #define DEFAULT_SPLUNK_DEVICE_PERCENTAGE 100
123 static supd *_supdInstance = nil;
125 BOOL runningTests = NO;
126 BOOL deviceAnalyticsOverride = NO;
127 BOOL deviceAnalyticsEnabled = NO;
128 BOOL iCloudAnalyticsOverride = NO;
129 BOOL iCloudAnalyticsEnabled = NO;
132 _isDeviceAnalyticsEnabled(void)
134 // This flag is only set during tests.
135 if (deviceAnalyticsOverride) {
136 return deviceAnalyticsEnabled;
139 static BOOL dataCollectionEnabled = NO;
140 static dispatch_once_t onceToken;
141 dispatch_once(&onceToken, ^{
143 dataCollectionEnabled = DiagnosticLogSubmissionEnabled();
145 dataCollectionEnabled = CRIsAutoSubmitEnabled();
148 return dataCollectionEnabled;
154 ACAccountStore *accountStore = [[ACAccountStore alloc] init];
155 ACAccount *primaryAccount = [accountStore aa_primaryAppleAccount];
156 if (primaryAccount == nil) {
159 return [primaryAccount aa_altDSID];
162 static NSString *const kAnalyticsiCloudIdMSKey = @"com.apple.idms.config.privacy.icloud.data";
164 static NSDictionary *
165 _getiCloudConfigurationInfoWithError(NSError **outError)
167 __block NSDictionary *outConfigurationInfo = nil;
168 __block NSError *localError = nil;
170 NSString *altDSID = accountAltDSID();
171 if (altDSID != nil) {
172 secnotice("_getiCloudConfigurationInfoWithError", "Fetching configuration info");
174 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
175 AKAppleIDAuthenticationController *authController = [AKAppleIDAuthenticationController new];
176 [authController configurationInfoWithIdentifiers:@[kAnalyticsiCloudIdMSKey]
178 completion:^(NSDictionary<NSString *, id<NSSecureCoding>> *configurationInfo, NSError *error) {
180 secerror("_getiCloudConfigurationInfoWithError: Error fetching configurationInfo: %@", error);
182 } else if (![configurationInfo isKindOfClass:[NSDictionary class]]) {
183 secerror("_getiCloudConfigurationInfoWithError: configurationInfo dict was not a dict, it was a %{public}@", [configurationInfo class]);
185 configurationInfo = nil;
187 secnotice("_getiCloudConfigurationInfoWithError", "fetched configurationInfo %@", configurationInfo);
188 outConfigurationInfo = configurationInfo;
190 dispatch_semaphore_signal(sema);
192 dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)(5 * NSEC_PER_SEC)));
194 secerror("_getiCloudConfigurationInfoWithError: Failed to fetch primary account info.");
197 if (localError && outError) {
198 *outError = localError;
200 return outConfigurationInfo;
204 _isiCloudAnalyticsEnabled()
206 // This flag is only set during tests.
207 if (iCloudAnalyticsOverride) {
208 return iCloudAnalyticsEnabled;
211 static bool cachedAllowsICloudAnalytics = false;
213 static dispatch_once_t onceToken;
214 dispatch_once(&onceToken, ^{
215 NSError *error = nil;
216 NSDictionary *accountConfiguration = _getiCloudConfigurationInfoWithError(&error);
217 if (error == nil && accountConfiguration != nil) {
218 id iCloudAnalyticsOptIn = accountConfiguration[kAnalyticsiCloudIdMSKey];
219 if (iCloudAnalyticsOptIn != nil) {
220 BOOL iCloudAnalyticsOptInHasCorrectType = ([iCloudAnalyticsOptIn isKindOfClass:[NSNumber class]] || [iCloudAnalyticsOptIn isKindOfClass:[NSString class]]);
221 if (iCloudAnalyticsOptInHasCorrectType) {
222 NSNumber *iCloudAnalyticsOptInNumber = @([iCloudAnalyticsOptIn integerValue]);
223 cachedAllowsICloudAnalytics = ![iCloudAnalyticsOptInNumber isEqualToNumber:[NSNumber numberWithInteger:0]];
226 } else if (error != nil) {
227 secerror("_isiCloudAnalyticsEnabled: %@", error);
231 return cachedAllowsICloudAnalytics;
234 /* NSData GZip category based on GeoKit's implementation */
235 @interface NSData (GZip)
236 - (NSData *)supd_gzipDeflate;
239 #define GZIP_OFFSET 16
240 #define GZIP_STRIDE_LEN 16384
242 @implementation NSData (Gzip)
243 - (NSData *)supd_gzipDeflate
245 if ([self length] == 0) {
250 memset(&strm, 0, sizeof(strm));
251 strm.next_in=(uint8_t *)[self bytes];
252 strm.avail_in = (unsigned int)[self length];
255 if (Z_OK != deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED,
256 MAX_WBITS + GZIP_OFFSET, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) {
260 NSMutableData *compressed = [NSMutableData dataWithLength:GZIP_STRIDE_LEN];
263 if (strm.total_out >= [compressed length]) {
264 [compressed increaseLengthBy: 16384];
267 strm.next_out = [compressed mutableBytes] + strm.total_out;
268 strm.avail_out = (int)[compressed length] - (int)strm.total_out;
270 deflate(&strm, Z_FINISH);
272 } while (strm.avail_out == 0);
276 [compressed setLength: strm.total_out];
277 if (strm.avail_in == 0) {
278 return [NSData dataWithData:compressed];
285 @implementation SFAnalyticsClient {
288 BOOL _requireDeviceAnalytics;
289 BOOL _requireiCloudAnalytics;
292 @synthesize storePath = _path;
293 @synthesize name = _name;
295 - (instancetype)initWithStorePath:(NSString*)path name:(NSString*)name
296 deviceAnalytics:(BOOL)deviceAnalytics iCloudAnalytics:(BOOL)iCloudAnalytics {
297 if (self = [super init]) {
300 _requireDeviceAnalytics = deviceAnalytics;
301 _requireiCloudAnalytics = iCloudAnalytics;
308 @interface SFAnalyticsTopic ()
309 @property NSURL* _splunkUploadURL;
311 @property BOOL allowInsecureSplunkCert;
312 @property BOOL ignoreServersMessagesTellingUsToGoAway;
313 @property BOOL disableUploads;
314 @property BOOL disableClientId;
316 @property NSUInteger secondsBetweenUploads;
317 @property NSUInteger maxEventsToReport;
318 @property float devicePercentage; // for sampling reporting devices
320 @property NSDictionary* metricsBase; // data the server provides and wants us to send back
321 @property NSArray* blacklistedFields;
322 @property NSArray* blacklistedEvents;
325 @implementation SFAnalyticsTopic
327 - (void)setupClientsForTopic:(NSString *)topicName
329 NSMutableArray<SFAnalyticsClient*>* clients = [NSMutableArray<SFAnalyticsClient*> new];
330 if ([topicName isEqualToString:SFAnalyticsTopicKeySync]) {
331 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForCKKS]
332 name:@"ckks" deviceAnalytics:NO iCloudAnalytics:YES]];
333 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForSOS]
334 name:@"sos" deviceAnalytics:NO iCloudAnalytics:YES]];
335 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForPCS]
336 name:@"pcs" deviceAnalytics:NO iCloudAnalytics:YES]];
337 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForSignIn]
338 name:@"signins" deviceAnalytics:NO iCloudAnalytics:YES]];
339 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForLocal]
340 name:@"local" deviceAnalytics:YES iCloudAnalytics:NO]];
341 } else if ([topicName isEqualToString:SFAnalyticsTopicCloudServices]) {
342 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForCloudServices]
343 name:@"CloudServices"
345 iCloudAnalytics:NO]];
346 } else if ([topicName isEqualToString:SFAnalyticsTopicTrust]) {
347 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForTrust]
348 name:@"trust" deviceAnalytics:YES iCloudAnalytics:NO]];
350 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForRootTrust]
351 name:@"rootTrust" deviceAnalytics:YES iCloudAnalytics:NO]];
353 } else if ([topicName isEqualToString:SFAnalyticsTopicNetworking]) {
354 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForNetworking]
355 name:@"networking" deviceAnalytics:YES iCloudAnalytics:NO]];
357 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForRootNetworking]
358 name:@"rootNetworking" deviceAnalytics:YES iCloudAnalytics:NO]];
360 } else if ([topicName isEqualToString:SFAnalyticsTopicTransparency]) {
361 [clients addObject:[[SFAnalyticsClient alloc] initWithStorePath:[self.class databasePathForTransparency]
362 name:@"transparency" deviceAnalytics:NO iCloudAnalytics:YES]];
365 _topicClients = clients;
368 - (instancetype)initWithDictionary:(NSDictionary *)dictionary name:(NSString *)topicName samplingRates:(NSDictionary *)rates {
369 if (self = [super init]) {
370 _internalTopicName = topicName;
371 [self setupClientsForTopic:topicName];
372 _splunkTopicName = dictionary[@"splunk_topic"];
373 __splunkUploadURL = [NSURL URLWithString:dictionary[@"splunk_uploadURL"]];
374 _splunkBagURL = [NSURL URLWithString:dictionary[@"splunk_bagURL"]];
375 _allowInsecureSplunkCert = [[dictionary valueForKey:@"splunk_allowInsecureCertificate"] boolValue];
376 _uploadSizeLimit = [[dictionary valueForKey:@"uploadSizeLimit"] unsignedIntegerValue];
378 NSString* splunkEndpoint = dictionary[@"splunk_endpointDomain"];
379 if (dictionary[@"disableClientId"]) {
380 _disableClientId = YES;
383 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SFAnalyticsUserDefaultsSuite];
384 NSString* userDefaultsSplunkTopic = [defaults stringForKey:@"splunk_topic"];
385 if (userDefaultsSplunkTopic) {
386 _splunkTopicName = userDefaultsSplunkTopic;
389 NSURL* userDefaultsSplunkUploadURL = [NSURL URLWithString:[defaults stringForKey:@"splunk_uploadURL"]];
390 if (userDefaultsSplunkUploadURL) {
391 __splunkUploadURL = userDefaultsSplunkUploadURL;
394 NSURL* userDefaultsSplunkBagURL = [NSURL URLWithString:[defaults stringForKey:@"splunk_bagURL"]];
395 if (userDefaultsSplunkBagURL) {
396 _splunkBagURL = userDefaultsSplunkBagURL;
399 NSInteger userDefaultsUploadSizeLimit = [defaults integerForKey:@"uploadSizeLimit"];
400 if (userDefaultsUploadSizeLimit > 0) {
401 _uploadSizeLimit = userDefaultsUploadSizeLimit;
404 BOOL userDefaultsAllowInsecureSplunkCert = [defaults boolForKey:@"splunk_allowInsecureCertificate"];
405 _allowInsecureSplunkCert |= userDefaultsAllowInsecureSplunkCert;
407 NSString* userDefaultsSplunkEndpoint = [defaults stringForKey:@"splunk_endpointDomain"];
408 if (userDefaultsSplunkEndpoint) {
409 splunkEndpoint = userDefaultsSplunkEndpoint;
412 #if SFANALYTICS_SPLUNK_DEV
413 _secondsBetweenUploads = secondsBetweenUploadsInternal;
414 _maxEventsToReport = SFAnalyticsMaxEventsToReport;
415 _devicePercentage = DEFAULT_SPLUNK_DEVICE_PERCENTAGE;
417 bool internal = os_variant_has_internal_diagnostics("com.apple.security");
420 NSNumber *secondsNum = internal ? rates[SFAnalyticsSecondsInternalKey] : rates[SFAnalyticsSecondsSeedKey];
421 NSNumber *percentageNum = internal ? rates[SFAnalyticsDevicePercentageInternalKey] : rates[SFAnalyticsDevicePercentageSeedKey];
423 NSNumber *secondsNum = internal ? rates[SFAnalyticsSecondsInternalKey] : rates[SFAnalyticsSecondsCustomerKey];
424 NSNumber *percentageNum = internal ? rates[SFAnalyticsDevicePercentageInternalKey] : rates[SFAnalyticsDevicePercentageCustomerKey];
426 _secondsBetweenUploads = [secondsNum integerValue];
427 _maxEventsToReport = [rates[SFAnalyticsMaxEventsKey] unsignedIntegerValue];
428 _devicePercentage = [percentageNum floatValue];
431 _secondsBetweenUploads = internal ? secondsBetweenUploadsInternal : secondsBetweenUploadsSeed;
433 _secondsBetweenUploads = internal ? secondsBetweenUploadsInternal : secondsBetweenUploadsCustomer;
435 _maxEventsToReport = SFAnalyticsMaxEventsToReport;
436 _devicePercentage = DEFAULT_SPLUNK_DEVICE_PERCENTAGE;
439 secnotice("supd", "created %@ with %lu seconds between uploads, %lu max events, %f percent of uploads",
440 _internalTopicName, (unsigned long)_secondsBetweenUploads, (unsigned long)_maxEventsToReport, _devicePercentage);
442 #if SFANALYTICS_SPLUNK_DEV
443 _ignoreServersMessagesTellingUsToGoAway = YES;
445 if (!_splunkUploadURL && splunkEndpoint) {
446 NSString* urlString = [NSString stringWithFormat:@"https://%@/report/2/%@", splunkEndpoint, _splunkTopicName];
447 _splunkUploadURL = [NSURL URLWithString:urlString];
450 (void)splunkEndpoint;
456 - (BOOL)isSampledUpload
458 uint32_t sample = arc4random();
459 if ((double)_devicePercentage < ((double)1 / UINT32_MAX) * 100) {
460 /* Requested percentage is smaller than we can sample. just do 1 out of UINT32_MAX */
465 if ((double)sample <= (double)UINT32_MAX * ((double)_devicePercentage / 100)) {
472 - (BOOL)postJSON:(NSData*)json toEndpoint:(NSURL*)endpoint error:(NSError**)error
476 NSString *description = [NSString stringWithFormat:@"No endpoint for %@", _internalTopicName];
477 *error = [NSError errorWithDomain:@"SupdUploadErrorDomain"
479 userInfo:@{NSLocalizedDescriptionKey : description}];
484 * Create the NSURLSession
485 * We use the ephemeral session config because we don't need cookies or cache
487 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
489 configuration.HTTPAdditionalHeaders = @{ @"User-Agent" : [NSString stringWithFormat:@"securityd/%s", SECURITY_BUILD_VERSION]};
491 NSURLSession* postSession = [NSURLSession sessionWithConfiguration:configuration
495 NSMutableURLRequest* postRequest = [[NSMutableURLRequest alloc] init];
496 postRequest.URL = endpoint;
497 postRequest.HTTPMethod = @"POST";
498 postRequest.HTTPBody = [json supd_gzipDeflate];
499 [postRequest setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
502 * Create the upload task.
504 dispatch_semaphore_t sem = dispatch_semaphore_create(0);
505 __block BOOL uploadSuccess = NO;
506 NSURLSessionDataTask* uploadTask = [postSession dataTaskWithRequest:postRequest
507 completionHandler:^(NSData * _Nullable __unused data, NSURLResponse * _Nullable response, NSError * _Nullable requestError) {
509 secerror("Error in uploading the events to splunk for %@: %@", self->_internalTopicName, requestError);
510 } else if (![response isKindOfClass:NSHTTPURLResponse.class]){
511 Class class = response.class;
512 secerror("Received the wrong kind of response for %@: %@", self->_internalTopicName, NSStringFromClass(class));
514 NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
515 if(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
518 secnotice("upload", "Splunk upload success for %@", self->_internalTopicName);
520 secnotice("upload", "Splunk upload for %@ unexpected status to URL: %@ -- status: %d",
521 self->_internalTopicName, endpoint, (int)(httpResponse.statusCode));
524 dispatch_semaphore_signal(sem);
526 secnotice("upload", "Splunk upload start for %@", self->_internalTopicName);
528 dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)(5 * 60 * NSEC_PER_SEC)));
529 return uploadSuccess;
532 - (BOOL)eventIsBlacklisted:(NSMutableDictionary*)event {
533 return _blacklistedEvents ? [_blacklistedEvents containsObject:event[SFAnalyticsEventType]] : NO;
536 - (void)removeBlacklistedFieldsFromEvent:(NSMutableDictionary*)event {
537 for (NSString* badField in self->_blacklistedFields) {
538 [event removeObjectForKey:badField];
542 - (void)addRequiredFieldsToEvent:(NSMutableDictionary*)event {
543 [_metricsBase enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
550 - (BOOL)prepareEventForUpload:(NSMutableDictionary*)event
551 linkedUUID:(NSUUID *)linkedUUID {
552 if ([self eventIsBlacklisted:event]) {
556 [self removeBlacklistedFieldsFromEvent:event];
557 [self addRequiredFieldsToEvent:event];
558 if (_disableClientId) {
559 event[SFAnalyticsClientId] = @(0);
561 event[SFAnalyticsSplunkTopic] = self->_splunkTopicName ?: [NSNull null];
563 event[SFAnalyticsEventCorrelationID] = [linkedUUID UUIDString];
568 - (void)addFailures:(NSMutableArray<NSArray*>*)failures toUploadRecords:(NSMutableArray*)records threshold:(NSUInteger)threshold linkedUUID:(NSUUID *)linkedUUID
570 // The first 0 through 'threshold' items are getting uploaded in any case (which might be 0 for lower priority data)
572 for (NSArray* client in failures) {
573 [client enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
574 NSMutableDictionary* event = (NSMutableDictionary*)obj;
575 if (idx >= threshold) {
579 if ([self prepareEventForUpload:event linkedUUID:linkedUUID]) {
580 if ([NSJSONSerialization isValidJSONObject:event]) {
581 [records addObject:event];
583 secerror("supd: Replacing event with errorEvent because invalid JSON: %@", event);
584 NSString* originalType = event[SFAnalyticsEventType];
585 NSDictionary* errorEvent = @{ SFAnalyticsEventType : SFAnalyticsEventTypeErrorEvent,
586 SFAnalyticsEventErrorDestription : [NSString stringWithFormat:@"JSON:%@", originalType]};
587 [records addObject:errorEvent];
593 // Are there more items than we shoved into the upload records?
594 NSInteger excessItems = 0;
595 for (NSArray* client in failures) {
596 NSInteger localExcess = client.count - threshold;
597 excessItems += localExcess > 0 ? localExcess : 0;
600 // Then, if we have space and items left, apply a scaling factor to distribute events across clients to fill upload buffer
601 if (records.count < _maxEventsToReport && excessItems > 0) {
602 double scale = (_maxEventsToReport - records.count) / (double)excessItems;
607 for (NSArray* client in failures) {
608 if (client.count > threshold) {
609 NSRange range = NSMakeRange(threshold, (client.count - threshold) * scale);
610 NSArray* sub = [client subarrayWithRange:range];
611 [sub enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
612 if ([self prepareEventForUpload:obj linkedUUID:linkedUUID]) {
613 [records addObject:obj];
621 - (NSMutableDictionary*)sampleStatisticsForSamples:(NSArray*)samples withName:(NSString*)name
623 NSMutableDictionary* statistics = [NSMutableDictionary dictionary];
624 NSUInteger count = samples.count;
625 NSArray* sortedSamples = [samples sortedArrayUsingSelector:@selector(compare:)];
626 NSArray* samplesAsExpressionArray = @[[NSExpression expressionForConstantValue:sortedSamples]];
629 statistics[name] = samples[0];
631 // NSExpression takes population standard deviation. Our data is a sample of whatever we sampled over time,
632 // but the difference between the two is fairly minor (divide by N before taking sqrt versus divide by N-1).
633 statistics[[NSString stringWithFormat:@"%@-dev", name]] = [[NSExpression expressionForFunction:@"stddev:" arguments:samplesAsExpressionArray] expressionValueWithObject:nil context:nil];
635 statistics[[NSString stringWithFormat:@"%@-min", name]] = [[NSExpression expressionForFunction:@"min:" arguments:samplesAsExpressionArray] expressionValueWithObject:nil context:nil];
636 statistics[[NSString stringWithFormat:@"%@-max", name]] = [[NSExpression expressionForFunction:@"max:" arguments:samplesAsExpressionArray] expressionValueWithObject:nil context:nil];
637 statistics[[NSString stringWithFormat:@"%@-avg", name]] = [[NSExpression expressionForFunction:@"average:" arguments:samplesAsExpressionArray] expressionValueWithObject:nil context:nil];
638 statistics[[NSString stringWithFormat:@"%@-med", name]] = [[NSExpression expressionForFunction:@"median:" arguments:samplesAsExpressionArray] expressionValueWithObject:nil context:nil];
642 NSString* q1 = [NSString stringWithFormat:@"%@-1q", name];
643 NSString* q3 = [NSString stringWithFormat:@"%@-3q", name];
644 // From Wikipedia, which is never wrong
645 if (count % 2 == 0) {
646 // The lower quartile value is the median of the lower half of the data. The upper quartile value is the median of the upper half of the data.
647 statistics[q1] = [[NSExpression expressionForFunction:@"median:" arguments:@[[NSExpression expressionForConstantValue:[sortedSamples subarrayWithRange:NSMakeRange(0, count / 2)]]]] expressionValueWithObject:nil context:nil];
648 statistics[q3] = [[NSExpression expressionForFunction:@"median:" arguments:@[[NSExpression expressionForConstantValue:[sortedSamples subarrayWithRange:NSMakeRange((count / 2), count / 2)]]]] expressionValueWithObject:nil context:nil];
649 } else if (count % 4 == 1) {
650 // If there are (4n+1) data points, then the lower quartile is 25% of the nth data value plus 75% of the (n+1)th data value;
651 // the upper quartile is 75% of the (3n+1)th data point plus 25% of the (3n+2)th data point.
652 // (offset n by -1 since we count from 0)
653 NSUInteger n = count / 4;
654 statistics[q1] = @(([sortedSamples[n - 1] doubleValue] + [sortedSamples[n] doubleValue] * 3.0) / 4.0);
655 statistics[q3] = @(([sortedSamples[(3 * n)] doubleValue] * 3.0 + [sortedSamples[(3 * n) + 1] doubleValue]) / 4.0);
656 } else if (count % 4 == 3){
657 // If there are (4n+3) data points, then the lower quartile is 75% of the (n+1)th data value plus 25% of the (n+2)th data value;
658 // the upper quartile is 25% of the (3n+2)th data point plus 75% of the (3n+3)th data point.
659 // (offset n by -1 since we count from 0)
660 NSUInteger n = count / 4;
661 statistics[q1] = @(([sortedSamples[n] doubleValue] * 3.0 + [sortedSamples[n + 1] doubleValue]) / 4.0);
662 statistics[q3] = @(([sortedSamples[(3 * n) + 1] doubleValue] + [sortedSamples[(3 * n) + 2] doubleValue] * 3.0) / 4.0);
669 - (NSMutableDictionary*)healthSummaryWithName:(NSString*)name store:(SFAnalyticsSQLiteStore*)store uuid:(NSUUID *)uuid
671 __block NSMutableDictionary* summary = [NSMutableDictionary new];
673 // Add some events of our own before pulling in data
674 summary[SFAnalyticsEventType] = [NSString stringWithFormat:@"%@HealthSummary", name];
675 if ([self eventIsBlacklisted:summary]) {
678 summary[SFAnalyticsEventTime] = @([[NSDate date] timeIntervalSince1970] * 1000); // Splunk wants milliseconds
679 [SFAnalytics addOSVersionToEvent:summary];
680 if (store.uploadDate) {
681 summary[SFAnalyticsAttributeLastUploadTime] = @([store.uploadDate timeIntervalSince1970] * 1000);
683 summary[SFAnalyticsAttributeLastUploadTime] = @(0);
687 NSDictionary* successCounts = store.summaryCounts;
688 __block NSInteger totalSuccessCount = 0;
689 __block NSInteger totalHardFailureCount = 0;
690 __block NSInteger totalSoftFailureCount = 0;
691 [successCounts enumerateKeysAndObjectsUsingBlock:^(NSString* _Nonnull eventType, NSDictionary* _Nonnull counts, BOOL* _Nonnull stop) {
692 summary[[NSString stringWithFormat:@"%@-success", eventType]] = counts[SFAnalyticsColumnSuccessCount];
693 summary[[NSString stringWithFormat:@"%@-hardfail", eventType]] = counts[SFAnalyticsColumnHardFailureCount];
694 summary[[NSString stringWithFormat:@"%@-softfail", eventType]] = counts[SFAnalyticsColumnSoftFailureCount];
695 totalSuccessCount += [counts[SFAnalyticsColumnSuccessCount] integerValue];
696 totalHardFailureCount += [counts[SFAnalyticsColumnHardFailureCount] integerValue];
697 totalSoftFailureCount += [counts[SFAnalyticsColumnSoftFailureCount] integerValue];
700 summary[SFAnalyticsColumnSuccessCount] = @(totalSuccessCount);
701 summary[SFAnalyticsColumnHardFailureCount] = @(totalHardFailureCount);
702 summary[SFAnalyticsColumnSoftFailureCount] = @(totalSoftFailureCount);
703 if (os_variant_has_internal_diagnostics("com.apple.security")) {
704 summary[SFAnalyticsInternal] = @YES;
708 NSMutableDictionary<NSString*,NSMutableArray*>* samplesBySampler = [NSMutableDictionary<NSString*,NSMutableArray*> dictionary];
709 for (NSDictionary* sample in [store samples]) {
710 if (!samplesBySampler[sample[SFAnalyticsColumnSampleName]]) {
711 samplesBySampler[sample[SFAnalyticsColumnSampleName]] = [NSMutableArray array];
713 [samplesBySampler[sample[SFAnalyticsColumnSampleName]] addObject:sample[SFAnalyticsColumnSampleValue]];
715 [samplesBySampler enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSMutableArray * _Nonnull obj, BOOL * _Nonnull stop) {
716 NSMutableDictionary* event = [self sampleStatisticsForSamples:obj withName:key];
717 [summary addEntriesFromDictionary:event];
720 // Should always return yes because we already checked for event blacklisting specifically (unless summary itself is blacklisted)
721 if (![self prepareEventForUpload:summary linkedUUID:uuid]) {
722 secwarning("supd: health summary for %@ blacklisted", name);
726 // Seems unlikely because we only insert strings, samplers only take NSNumbers and frankly, sampleStatisticsForSamples probably would have crashed
727 if (![NSJSONSerialization isValidJSONObject:summary]) {
728 secerror("json: health summary for client %@ is invalid JSON: %@", name, summary);
729 return [@{ SFAnalyticsEventType : SFAnalyticsEventTypeErrorEvent,
730 SFAnalyticsEventErrorDestription : [NSString stringWithFormat:@"JSON:%@HealthSummary", name]} mutableCopy];
736 - (void)updateUploadDateForClients:(NSArray<SFAnalyticsClient*>*)clients date:(NSDate *)date clearData:(BOOL)clearData
738 for (SFAnalyticsClient* client in clients) {
739 SFAnalyticsSQLiteStore* store = [SFAnalyticsSQLiteStore storeWithPath:client.storePath schema:SFAnalyticsTableSchema];
740 secnotice("postprocess", "Setting upload date (%@) for client: %@", date, client.name);
741 store.uploadDate = date;
743 secnotice("postprocess", "Clearing collected data for client: %@", client.name);
744 [store clearAllData];
749 - (size_t)serializedEventSize:(NSObject *)event
750 error:(NSError**)error
752 if (![NSJSONSerialization isValidJSONObject:event]) {
753 secnotice("serializedEventSize", "invalid JSON object");
757 NSData *json = [NSJSONSerialization dataWithJSONObject:event
761 return [json length];
763 secnotice("serializedEventSize", "failed to serialize event");
768 - (NSArray<NSArray *> *)chunkFailureSet:(size_t)sizeCapacity
769 events:(NSArray<NSDictionary *> *)events
770 error:(NSError **)error
772 const size_t postBodyLimit = 1000; // 1000 events in a single upload
773 size_t currentSize = 0;
774 size_t currentEventCount = 0;
776 NSMutableArray<NSArray<NSDictionary *> *> *eventChunks = [[NSMutableArray<NSArray<NSDictionary *> *> alloc] init];
777 NSMutableArray<NSDictionary *> *currentEventChunk = [[NSMutableArray<NSDictionary *> alloc] init];
778 for (NSDictionary *event in events) {
779 NSError *localError = nil;
780 size_t eventSize = [self serializedEventSize:event error:&localError];
781 if (localError != nil) {
785 secemergency("Unable to serialize event JSON: %@", [localError localizedDescription]);
789 BOOL countLessThanLimit = currentEventCount < postBodyLimit;
790 BOOL sizeLessThanCapacity = (currentSize + eventSize) <= sizeCapacity;
791 if (!countLessThanLimit || !sizeLessThanCapacity) {
792 [eventChunks addObject:currentEventChunk];
793 currentEventChunk = [[NSMutableArray<NSDictionary *> alloc] init];
794 currentEventCount = 0;
798 [currentEventChunk addObject:event];
800 currentSize += eventSize;
803 if ([currentEventChunk count] > 0) {
804 [eventChunks addObject:currentEventChunk];
810 - (NSDictionary *)createEventDictionary:(NSArray *)healthSummaries
811 failures:(NSArray<NSDictionary *> *)failures
812 error:(NSError **)error
814 NSMutableArray *events = [[NSMutableArray alloc] init];
815 [events addObjectsFromArray:healthSummaries];
817 [events addObjectsFromArray:failures];
820 NSDictionary *eventDictionary = @{
821 SFAnalyticsPostTime : @([[NSDate date] timeIntervalSince1970] * 1000),
825 if (![NSJSONSerialization isValidJSONObject:eventDictionary]) {
826 secemergency("json: final dictionary invalid JSON.");
828 *error = [NSError errorWithDomain:SupdErrorDomain code:SupdInvalidJSONError
829 userInfo:@{NSLocalizedDescriptionKey : [NSString localizedStringWithFormat:@"Final dictionary for upload is invalid JSON: %@", eventDictionary]}];
834 return eventDictionary;
837 - (NSArray<NSDictionary *> *)createChunkedLoggingJSON:(NSArray<NSDictionary *> *)healthSummaries
838 failures:(NSArray<NSDictionary *> *)failures
839 error:(NSError **)error
841 NSError *localError = nil;
842 size_t baseSize = [self serializedEventSize:healthSummaries error:&localError];
843 if (localError != nil) {
844 secemergency("Unable to serialize health summary JSON");
851 NSArray<NSArray *> *chunkedEvents = [self chunkFailureSet:(self.uploadSizeLimit - baseSize) events:failures error:&localError];
853 NSMutableArray<NSDictionary *> *jsonResults = [[NSMutableArray<NSDictionary *> alloc] init];
854 for (NSArray<NSDictionary *> *failureSet in chunkedEvents) {
855 NSDictionary *eventDictionary = [self createEventDictionary:healthSummaries failures:failureSet error:error];
856 if (eventDictionary) {
857 [jsonResults addObject:eventDictionary];
863 if ([jsonResults count] == 0) {
864 NSDictionary *eventDictionary = [self createEventDictionary:healthSummaries failures:nil error:error];
865 if (eventDictionary) {
866 [jsonResults addObject:eventDictionary];
875 - (BOOL)copyEvents:(NSMutableArray<NSDictionary *> **)healthSummaries
876 failures:(NSMutableArray<NSDictionary *> **)failures
877 forUpload:(BOOL)upload
878 participatingClients:(NSMutableArray<SFAnalyticsClient*>**)clients
880 linkedUUID:(NSUUID *)linkedUUID
881 error:(NSError**)error
883 NSMutableArray<SFAnalyticsClient*> *localClients = [[NSMutableArray alloc] init];
884 NSMutableArray<NSDictionary *> *localHealthSummaries = [[NSMutableArray<NSDictionary *> alloc] init];
885 NSMutableArray<NSDictionary *> *localFailures = [[NSMutableArray<NSDictionary *> alloc] init];
886 NSMutableArray<NSArray*> *hardFailures = [[NSMutableArray alloc] init];
887 NSMutableArray<NSArray*> *softFailures = [[NSMutableArray alloc] init];
888 NSString *ckdeviceID = nil;
889 NSString *accountID = nil;
891 if (os_variant_has_internal_diagnostics("com.apple.security") && [_internalTopicName isEqualToString:SFAnalyticsTopicKeySync]) {
892 ckdeviceID = [self askSecurityForCKDeviceID];
893 accountID = accountAltDSID();
895 for (SFAnalyticsClient* client in self->_topicClients) {
897 if (!force && [client requireDeviceAnalytics] && !_isDeviceAnalyticsEnabled()) {
898 // Client required device analytics, yet the user did not opt in.
899 secnotice("getLoggingJSON", "Client '%@' requires device analytics yet user did not opt in.", [client name]);
902 if (!force && [client requireiCloudAnalytics] && !_isiCloudAnalyticsEnabled()) {
903 // Client required iCloud analytics, yet the user did not opt in.
904 secnotice("getLoggingJSON", "Client '%@' requires iCloud analytics yet user did not opt in.", [client name]);
908 SFAnalyticsSQLiteStore* store = [SFAnalyticsSQLiteStore storeWithPath:client.storePath schema:SFAnalyticsTableSchema];
911 NSDate* uploadDate = store.uploadDate;
912 if (!force && uploadDate && [[NSDate date] timeIntervalSinceDate:uploadDate] < _secondsBetweenUploads) {
913 secnotice("json", "ignoring client '%@' for %@ because last upload too recent: %@",
914 client.name, _internalTopicName, uploadDate);
919 secnotice("json", "client '%@' for topic '%@' force-included", client.name, _internalTopicName);
921 secnotice("json", "including client '%@' for topic '%@' for upload", client.name, _internalTopicName);
923 [localClients addObject:client];
926 NSMutableDictionary* healthSummary = [self healthSummaryWithName:client.name store:store uuid:linkedUUID];
929 healthSummary[SFAnalyticsDeviceID] = ckdeviceID;
932 healthSummary[SFAnalyticsAltDSID] = accountID;
934 [localHealthSummaries addObject:healthSummary];
937 [hardFailures addObject:store.hardFailures];
938 [softFailures addObject:store.softFailures];
942 if (upload && [localClients count] == 0) {
944 NSString *description = [NSString stringWithFormat:@"Upload too recent for all clients for %@", _internalTopicName];
945 *error = [NSError errorWithDomain:@"SupdUploadErrorDomain"
947 userInfo:@{NSLocalizedDescriptionKey : description}];
953 *clients = localClients;
957 [self addFailures:hardFailures toUploadRecords:localFailures threshold:_maxEventsToReport/10 linkedUUID:linkedUUID];
958 [self addFailures:softFailures toUploadRecords:localFailures threshold:0 linkedUUID:linkedUUID];
959 [*failures addObjectsFromArray:localFailures];
962 if (healthSummaries) {
963 [*healthSummaries addObjectsFromArray:localHealthSummaries];
969 - (NSArray<NSDictionary *> *)createChunkedLoggingJSON:(bool)pretty
970 forUpload:(BOOL)upload
971 participatingClients:(NSMutableArray<SFAnalyticsClient*>**)clients
972 force:(BOOL)force // supdctl uploads ignore privacy settings and recency
973 error:(NSError**)error
975 NSUUID *linkedUUID = [NSUUID UUID];
976 NSError *localError = nil;
977 NSMutableArray *failures = [[NSMutableArray alloc] init];
978 NSMutableArray *healthSummaries = [[NSMutableArray alloc] init];
979 BOOL copied = [self copyEvents:&healthSummaries
982 participatingClients:clients
984 linkedUUID:linkedUUID
986 if (!copied || localError) {
993 // Trim failures to the max count, based on health summary count
994 if ([failures count] > (_maxEventsToReport - [healthSummaries count])) {
997 range.length = _maxEventsToReport - [healthSummaries count];
998 failures = [[failures subarrayWithRange:range] mutableCopy];
1001 return [self createChunkedLoggingJSON:healthSummaries failures:failures error:error];
1004 - (NSDictionary *)createLoggingJSON:(bool)pretty
1005 forUpload:(BOOL)upload
1006 participatingClients:(NSMutableArray<SFAnalyticsClient*>**)clients
1007 force:(BOOL)force // supdctl uploads ignore privacy settings and recency
1008 error:(NSError**)error
1010 NSError *localError = nil;
1011 NSMutableArray *failures = [[NSMutableArray alloc] init];
1012 NSMutableArray *healthSummaries = [[NSMutableArray alloc] init];
1013 BOOL copied = [self copyEvents:&healthSummaries
1016 participatingClients:clients
1020 if (!copied || localError) {
1022 *error = localError;
1027 // Trim failures to the max count, based on health summary count
1028 if ([failures count] > (_maxEventsToReport - [healthSummaries count])) {
1031 range.length = _maxEventsToReport - [healthSummaries count];
1032 failures = [[failures subarrayWithRange:range] mutableCopy];
1035 return [self createEventDictionary:healthSummaries failures:failures error:error];
1038 // Is at least one client eligible for data collection based on user consent? Otherwise callers should NOT reach off-device.
1039 - (BOOL)haveEligibleClients {
1040 for (SFAnalyticsClient* client in self.topicClients) {
1041 if ((!client.requireDeviceAnalytics || _isDeviceAnalyticsEnabled()) &&
1042 (!client.requireiCloudAnalytics || _isiCloudAnalyticsEnabled())) {
1049 - (NSString*)askSecurityForCKDeviceID
1051 NSError* error = nil;
1052 CKKSControl* rpc = [CKKSControl controlObject:&error];
1054 secerror("unable to obtain CKKS endpoint: %@", error);
1058 __block NSString* localCKDeviceID;
1059 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
1060 [rpc rpcGetCKDeviceIDWithReply:^(NSString* ckdeviceID) {
1061 localCKDeviceID = ckdeviceID;
1062 dispatch_semaphore_signal(sema);
1065 if (dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 10)) != 0) {
1066 secerror("timed out waiting for a response from security");
1070 return localCKDeviceID;
1073 // this method is kind of evil for the fact that it has side-effects in pulling other things besides the metricsURL from the server, and as such should NOT be memoized.
1074 // TODO redo this, probably to return a dictionary.
1075 - (NSURL*)splunkUploadURL:(BOOL)force
1077 if (!force && ![self haveEligibleClients]) { // force is true IFF called from supdctl. Customers don't have it and internal audiences must call it explicitly.
1078 secnotice("getURL", "Not going to talk to server for topic %@ because no eligible clients", [self internalTopicName]);
1082 if (__splunkUploadURL) {
1083 return __splunkUploadURL;
1086 secnotice("getURL", "Asking server for endpoint and config data for topic %@", [self internalTopicName]);
1088 __weak __typeof(self) weakSelf = self;
1089 dispatch_semaphore_t sem = dispatch_semaphore_create(0);
1091 __block NSError* error = nil;
1092 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
1093 NSURLSession* storeBagSession = [NSURLSession sessionWithConfiguration:configuration
1097 NSURL* requestEndpoint = _splunkBagURL;
1098 __block NSURL* result = nil;
1099 NSURLSessionDataTask* storeBagTask = [storeBagSession dataTaskWithURL:requestEndpoint completionHandler:^(NSData * _Nullable data,
1100 NSURLResponse * _Nullable __unused response,
1101 NSError * _Nullable responseError) {
1103 __strong __typeof(self) strongSelf = weakSelf;
1108 if (data && !responseError) {
1109 NSData *responseData = data; // shut up compiler
1110 NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
1111 if([responseDict isKindOfClass:NSDictionary.class] && !error) {
1112 if (!self->_ignoreServersMessagesTellingUsToGoAway) {
1113 self->_disableUploads = [[responseDict valueForKey:@"sendDisabled"] boolValue];
1114 if (self->_disableUploads) {
1115 // then don't upload anything right now
1116 secerror("not returning a splunk URL because uploads are disabled for %@", self->_internalTopicName);
1117 dispatch_semaphore_signal(sem);
1121 // backend works with milliseconds
1122 NSUInteger secondsBetweenUploads = [[responseDict valueForKey:@"postFrequency"] unsignedIntegerValue] / 1000;
1123 if (secondsBetweenUploads > 0) {
1124 if (os_variant_has_internal_diagnostics("com.apple.security") &&
1125 self->_secondsBetweenUploads < secondsBetweenUploads) {
1126 secnotice("getURL", "Overriding server-sent post frequency because device is internal (%lu -> %lu)", (unsigned long)secondsBetweenUploads, (unsigned long)self->_secondsBetweenUploads);
1128 strongSelf->_secondsBetweenUploads = secondsBetweenUploads;
1132 strongSelf->_blacklistedEvents = responseDict[@"blacklistedEvents"];
1133 strongSelf->_blacklistedFields = responseDict[@"blacklistedFields"];
1136 strongSelf->_metricsBase = responseDict[@"metricsBase"];
1138 NSString* metricsEndpoint = responseDict[@"metricsUrl"];
1139 if([metricsEndpoint isKindOfClass:NSString.class]) {
1141 NSString* endpoint = [metricsEndpoint stringByAppendingFormat:@"/2/%@", strongSelf->_splunkTopicName];
1142 secnotice("upload", "got metrics endpoint %@ for %@", endpoint, self->_internalTopicName);
1143 NSURL* endpointURL = [NSURL URLWithString:endpoint];
1144 if([endpointURL.scheme isEqualToString:@"https"]) {
1145 result = endpointURL;
1151 error = responseError;
1154 secnotice("upload", "Unable to fetch splunk endpoint at URL for %@: %@ -- error: %@",
1155 self->_internalTopicName, requestEndpoint, error.description);
1158 secnotice("upload", "Malformed iTunes config payload for %@!", self->_internalTopicName);
1161 dispatch_semaphore_signal(sem);
1164 [storeBagTask resume];
1165 dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)(60 * NSEC_PER_SEC)));
1170 - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
1171 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
1172 assert(completionHandler);
1174 secnotice("upload", "Splunk upload challenge for %@", _internalTopicName);
1175 NSURLCredential *cred = nil;
1177 if ([challenge previousFailureCount] > 0) {
1178 // Previous failures occurred, bail
1179 completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
1181 } else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
1183 * Evaluate trust for the certificate
1186 SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
1187 // Coverity gets upset if we don't check status even though result is all we need.
1188 bool trustResult = SecTrustEvaluateWithError(serverTrust, NULL);
1189 if (_allowInsecureSplunkCert || trustResult) {
1191 * All is well, accept the credentials
1193 if(_allowInsecureSplunkCert) {
1194 secnotice("upload", "Force Accepting Splunk Credential for %@", _internalTopicName);
1196 cred = [NSURLCredential credentialForTrust:serverTrust];
1197 completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
1201 * An error occurred in evaluating trust, bail
1203 completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
1207 * Just perform the default handling
1209 completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
1213 - (NSDictionary*)eventDictWithBlacklistedFieldsStrippedFrom:(NSDictionary*)eventDict
1215 NSMutableDictionary* strippedDict = eventDict.mutableCopy;
1216 for (NSString* blacklistedField in _blacklistedFields) {
1217 [strippedDict removeObjectForKey:blacklistedField];
1219 return strippedDict;
1222 // MARK: Database path retrieval
1224 + (NSString*)databasePathForCKKS
1226 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory((__bridge CFStringRef)@"Analytics/ckks_analytics.db") path];
1229 + (NSString*)databasePathForSOS
1231 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory((__bridge CFStringRef)@"Analytics/sos_analytics.db") path];
1234 + (NSString*)AppSupportPath
1236 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
1237 return @"/var/mobile/Library/Application Support";
1239 NSArray<NSString *>*paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
1240 if ([paths count] < 1) {
1243 return [NSString stringWithString: paths[0]];
1244 #endif /* TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR */
1247 + (NSString*)databasePathForPCS
1249 NSString *appSup = [self AppSupportPath];
1253 NSString *dbpath = [NSString stringWithFormat:@"%@/com.apple.ProtectedCloudStorage/PCSAnalytics.db", appSup];
1254 secnotice("supd", "PCS Database path (%@)", dbpath);
1258 + (NSString*)databasePathForLocal
1260 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory((__bridge CFStringRef)@"Analytics/localkeychain.db") path];
1263 + (NSString*)databasePathForTrust
1265 #if TARGET_OS_IPHONE
1266 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory(CFSTR("Analytics/trust_analytics.db")) path];
1268 return [SFAnalytics defaultProtectedAnalyticsDatabasePath:@"trust_analytics"];
1273 + (NSUUID *)rootUUID
1276 int ret = mbr_uid_to_uuid(0, rootUuid);
1280 return [[NSUUID alloc] initWithUUIDBytes:rootUuid];
1285 + (NSString*)databasePathForRootTrust
1287 return [SFAnalytics defaultProtectedAnalyticsDatabasePath:@"trust_analytics" uuid:[SFAnalyticsTopic rootUUID]];
1291 + (NSString*)databasePathForNetworking
1293 #if TARGET_OS_IPHONE
1294 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory(CFSTR("Analytics/networking_analytics.db")) path];
1296 return [SFAnalytics defaultProtectedAnalyticsDatabasePath:@"networking_analytics"];
1301 + (NSString*)databasePathForRootNetworking
1303 return [SFAnalytics defaultProtectedAnalyticsDatabasePath:@"networking_analytics" uuid:[SFAnalyticsTopic rootUUID]];
1307 + (NSString*)databasePathForSignIn
1309 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory(CFSTR("Analytics/signin_metrics.db")) path];
1312 + (NSString*)databasePathForCloudServices
1314 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory(CFSTR("Analytics/CloudServicesAnalytics.db")) path];
1317 + (NSString*)databasePathForTransparency
1319 return [(__bridge_transfer NSURL*)SecCopyURLForFileInKeychainDirectory((__bridge CFStringRef)@"Analytics/TransparencyAnalytics.db") path];
1325 @property NSDictionary *topicsSamplingRates;
1328 @implementation supd
1331 NSDictionary* systemDefaultValues = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:@"/System/Library/Frameworks/Security.framework"] pathForResource:@"SFAnalytics" ofType:@"plist"]];
1332 NSMutableArray <SFAnalyticsTopic*>* topics = [NSMutableArray array];
1333 for (NSString *topicKey in systemDefaultValues) {
1334 NSDictionary *topicSamplingRates = _topicsSamplingRates[topicKey];
1335 SFAnalyticsTopic *topic = [[SFAnalyticsTopic alloc] initWithDictionary:systemDefaultValues[topicKey] name:topicKey samplingRates:topicSamplingRates];
1336 [topics addObject:topic];
1338 _analyticsTopics = [NSArray arrayWithArray:topics];
1341 + (void)instantiate {
1345 + (instancetype)instance {
1346 if (!_supdInstance) {
1347 _supdInstance = [self new];
1349 return _supdInstance;
1352 // Use this for testing to get rid of any state
1353 + (void)removeInstance {
1354 _supdInstance = nil;
1358 static NSString *SystemTrustStorePath = @"/System/Library/Security/Certificates.bundle";
1359 static NSString *AnalyticsSamplingRatesFilename = @"AnalyticsSamplingRates";
1360 static NSString *ContentVersionKey = @"MobileAssetContentVersion";
1361 static NSString *AssetContextFilename = @"OTAPKIContext.plist";
1363 static NSNumber *getSystemVersion(NSBundle *trustStoreBundle) {
1364 NSDictionary *systemVersionPlist = [NSDictionary dictionaryWithContentsOfURL:[trustStoreBundle URLForResource:@"AssetVersion"
1365 withExtension:@"plist"]];
1366 if (!systemVersionPlist || ![systemVersionPlist isKindOfClass:[NSDictionary class]]) {
1369 NSNumber *systemVersion = systemVersionPlist[ContentVersionKey];
1370 if (systemVersion == nil || ![systemVersion isKindOfClass:[NSNumber class]]) {
1373 return systemVersion;
1376 static NSNumber *getAssetVersion(NSURL *directory) {
1377 NSDictionary *assetContextPlist = [NSDictionary dictionaryWithContentsOfURL:[directory URLByAppendingPathComponent:AssetContextFilename]];
1378 if (!assetContextPlist || ![assetContextPlist isKindOfClass:[NSDictionary class]]) {
1381 NSNumber *assetVersion = assetContextPlist[ContentVersionKey];
1382 if (assetVersion == nil || ![assetVersion isKindOfClass:[NSNumber class]]) {
1385 return assetVersion;
1388 static bool ShouldInitializeWithAsset(NSBundle *trustStoreBundle, NSURL *directory) {
1389 NSNumber *systemVersion = getSystemVersion(trustStoreBundle);
1390 NSNumber *assetVersion = getAssetVersion(directory);
1392 if (assetVersion == nil || systemVersion == nil) {
1395 if ([assetVersion compare:systemVersion] == NSOrderedDescending) {
1401 - (void)setupSamplingRates {
1402 NSBundle *trustStoreBundle = [NSBundle bundleWithPath:SystemTrustStorePath];
1404 NSURL *keychainsDirectory = CFBridgingRelease(SecCopyURLForFileInSystemKeychainDirectory(nil));
1405 NSURL *directory = [keychainsDirectory URLByAppendingPathComponent:@"SupplementalsAssets/" isDirectory:YES];
1407 NSDictionary *analyticsSamplingRates = nil;
1408 if (ShouldInitializeWithAsset(trustStoreBundle, directory)) {
1409 /* Try to get the asset version of the sampling rates */
1410 NSURL *analyticsSamplingRateURL = [directory URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", AnalyticsSamplingRatesFilename]];
1411 analyticsSamplingRates = [NSDictionary dictionaryWithContentsOfURL:analyticsSamplingRateURL];
1412 secnotice("supd", "read sampling rates from SupplementalsAssets dir");
1413 if (!analyticsSamplingRates || ![analyticsSamplingRates isKindOfClass:[NSDictionary class]]) {
1414 analyticsSamplingRates = nil;
1417 if (!analyticsSamplingRates) {
1418 analyticsSamplingRates = [NSDictionary dictionaryWithContentsOfURL: [trustStoreBundle URLForResource:AnalyticsSamplingRatesFilename
1419 withExtension:@"plist"]];
1421 if (analyticsSamplingRates && [analyticsSamplingRates isKindOfClass:[NSDictionary class]]) {
1422 _topicsSamplingRates = analyticsSamplingRates[@"Topics"];
1423 if (!_topicsSamplingRates || ![analyticsSamplingRates isKindOfClass:[NSDictionary class]]) {
1424 _topicsSamplingRates = nil; // Something has gone terribly wrong, so we'll use the hardcoded defaults in this case
1429 - (instancetype)initWithReporter:(SFAnalyticsReporter *)reporter
1431 if (self = [super init]) {
1432 [self setupSamplingRates];
1434 _reporter = reporter;
1436 xpc_activity_register("com.apple.securityuploadd.triggerupload", XPC_ACTIVITY_CHECK_IN, ^(xpc_activity_t activity) {
1437 xpc_activity_state_t activityState = xpc_activity_get_state(activity);
1438 secnotice("supd", "hit xpc activity trigger, state: %ld", activityState);
1439 if (activityState == XPC_ACTIVITY_STATE_RUN) {
1440 // Run our regularly scheduled scan
1441 [self performRegularlyScheduledUpload];
1449 - (instancetype)init {
1450 SFAnalyticsReporter *reporter = [[SFAnalyticsReporter alloc] init];
1451 return [self initWithReporter:reporter];
1454 - (void)sendNotificationForOncePerReportSamplers
1456 notify_post(SFAnalyticsFireSamplersNotification);
1457 [NSThread sleepForTimeInterval:3.0];
1460 - (void)performRegularlyScheduledUpload {
1461 secnotice("upload", "Starting uploads in response to regular trigger");
1462 NSError *error = nil;
1463 if ([self uploadAnalyticsWithError:&error force:NO]) {
1464 secnotice("upload", "Regularly scheduled upload successful");
1466 secerror("upload: Failed to complete regularly scheduled upload: %@", error);
1470 - (NSArray<NSData *> *)serializeLoggingEvents:(NSArray<NSDictionary *> *)events
1471 error:(NSError **)error
1477 NSMutableArray<NSData *> *serializedEvents = [[NSMutableArray<NSData *> alloc] init];
1478 for (NSDictionary *event in events) {
1479 NSError *serializationError = nil;
1480 NSData* serializedEvent = [NSJSONSerialization dataWithJSONObject:event
1482 error:&serializationError];
1483 if (serializedEvent && !serializationError) {
1484 [serializedEvents addObject:serializedEvent];
1486 *error = serializationError;
1491 return serializedEvents;
1494 - (BOOL)uploadAnalyticsWithError:(NSError**)error force:(BOOL)force {
1495 [self sendNotificationForOncePerReportSamplers];
1498 NSError* localError = nil;
1499 for (SFAnalyticsTopic *topic in _analyticsTopics) {
1500 @autoreleasepool { // The logging JSONs get quite large. Ensure they're deallocated between topics.
1501 __block NSURL* endpoint = [topic splunkUploadURL:force]; // has side effects!
1504 secnotice("upload", "Skipping upload for %@ because no endpoint", [topic internalTopicName]);
1508 if ([topic disableUploads]) {
1509 secnotice("upload", "Aborting upload task for %@ because uploads are disabled", [topic internalTopicName]);
1513 NSMutableArray<SFAnalyticsClient*>* clients = [NSMutableArray new];
1514 NSArray<NSDictionary *> *jsonEvents = [topic createChunkedLoggingJSON:false forUpload:YES participatingClients:&clients force:force error:&localError];
1515 if (!jsonEvents || localError) {
1516 if ([[localError domain] isEqualToString:SupdErrorDomain] && [localError code] == SupdInvalidJSONError) {
1517 // Pretend this was a success because at least we'll get rid of bad data.
1518 // If someone keeps logging bad data and we only catch it here then
1519 // this causes sustained data loss for the entire topic.
1520 [topic updateUploadDateForClients:clients date:[NSDate date] clearData:YES];
1522 secerror("upload: failed to create chunked log events for logging topic %@: %@", [topic internalTopicName], localError);
1526 NSArray<NSData *> *serializedEvents = [self serializeLoggingEvents:jsonEvents error:&localError];
1527 if (!serializedEvents || localError) {
1528 if ([[localError domain] isEqualToString:SupdErrorDomain] && [localError code] == SupdInvalidJSONError) {
1529 // Pretend this was a success because at least we'll get rid of bad data.
1530 // If someone keeps logging bad data and we only catch it here then
1531 // this causes sustained data loss for the entire topic.
1532 [topic updateUploadDateForClients:clients date:[NSDate date] clearData:YES];
1534 secerror("upload: failed to serialized chunked log events for logging topic %@: %@", [topic internalTopicName], localError);
1538 if ([topic isSampledUpload]) {
1539 for (NSData *json in serializedEvents) {
1540 if (![self->_reporter saveReport:json fileName:[topic internalTopicName]]) {
1541 secerror("upload: failed to write analytics data to log");
1543 if ([topic postJSON:json toEndpoint:endpoint error:&localError]) {
1544 secnotice("upload", "Successfully posted JSON for %@", [topic internalTopicName]);
1546 [topic updateUploadDateForClients:clients date:[NSDate date] clearData:YES];
1548 secerror("upload: Failed to post JSON for %@: %@", [topic internalTopicName], localError);
1552 /* If we didn't sample this report, update date to prevent trying to upload again sooner
1553 * than we should. Clear data so that per-day calculations remain consistent. */
1554 secnotice("upload", "skipping unsampled upload for %@ and clearing data", [topic internalTopicName]);
1555 [topic updateUploadDateForClients:clients date:[NSDate date] clearData:YES];
1558 if (error && localError) {
1559 *error = localError;
1565 - (NSString*)sysdiagnoseStringForEventRecord:(NSDictionary*)eventRecord
1567 NSMutableDictionary* mutableEventRecord = eventRecord.mutableCopy;
1568 [mutableEventRecord removeObjectForKey:SFAnalyticsSplunkTopic];
1570 NSDate* eventDate = [NSDate dateWithTimeIntervalSince1970:[[eventRecord valueForKey:SFAnalyticsEventTime] doubleValue] / 1000];
1571 [mutableEventRecord removeObjectForKey:SFAnalyticsEventTime];
1573 NSString* eventName = eventRecord[SFAnalyticsEventType];
1574 [mutableEventRecord removeObjectForKey:SFAnalyticsEventType];
1576 SFAnalyticsEventClass eventClass = [[eventRecord valueForKey:SFAnalyticsEventClassKey] integerValue];
1577 NSString* eventClassString = [self stringForEventClass:eventClass];
1578 [mutableEventRecord removeObjectForKey:SFAnalyticsEventClassKey];
1580 NSMutableString* additionalAttributesString = [NSMutableString string];
1581 if (mutableEventRecord.count > 0) {
1582 [additionalAttributesString appendString:@" - Attributes: {" ];
1583 __block BOOL firstAttribute = YES;
1584 [mutableEventRecord enumerateKeysAndObjectsUsingBlock:^(NSString* key, id object, BOOL* stop) {
1585 NSString* openingString = firstAttribute ? @"" : @", ";
1586 [additionalAttributesString appendString:[NSString stringWithFormat:@"%@%@ : %@", openingString, key, object]];
1587 firstAttribute = NO;
1589 [additionalAttributesString appendString:@" }"];
1592 return [NSString stringWithFormat:@"%@ %@: %@%@", eventDate, eventClassString, eventName, additionalAttributesString];
1595 - (NSString*)getSysdiagnoseDump
1597 NSMutableString* sysdiagnose = [[NSMutableString alloc] init];
1599 for (SFAnalyticsTopic* topic in _analyticsTopics) {
1600 for (SFAnalyticsClient* client in topic.topicClients) {
1601 [sysdiagnose appendString:[NSString stringWithFormat:@"Client: %@\n", client.name]];
1602 SFAnalyticsSQLiteStore* store = [SFAnalyticsSQLiteStore storeWithPath:client.storePath schema:SFAnalyticsTableSchema];
1603 NSArray* allEvents = store.allEvents;
1604 for (NSDictionary* eventRecord in allEvents) {
1605 [sysdiagnose appendFormat:@"%@\n", [self sysdiagnoseStringForEventRecord:eventRecord]];
1607 if (allEvents.count == 0) {
1608 [sysdiagnose appendString:@"No data to report for this client\n"];
1615 - (void)setUploadDateWith:(NSDate *)date reply:(void (^)(BOOL, NSError*))reply
1617 for (SFAnalyticsTopic* topic in _analyticsTopics) {
1618 [topic updateUploadDateForClients:topic.topicClients date:date clearData:NO];
1623 - (void)clientStatus:(void (^)(NSDictionary<NSString *, id> *, NSError *))reply
1625 NSMutableDictionary *info = [NSMutableDictionary dictionary];
1626 for (SFAnalyticsTopic* topic in _analyticsTopics) {
1627 for (SFAnalyticsClient *client in topic.topicClients) {
1628 SFAnalyticsSQLiteStore* store = [SFAnalyticsSQLiteStore storeWithPath:client.storePath schema:SFAnalyticsTableSchema];
1630 NSMutableDictionary *clientInfo = [NSMutableDictionary dictionary];
1631 clientInfo[@"uploadDate"] = store.uploadDate;
1632 info[client.name] = clientInfo;
1639 - (NSString*)stringForEventClass:(SFAnalyticsEventClass)eventClass
1641 if (eventClass == SFAnalyticsEventClassNote) {
1642 return @"EventNote";
1644 else if (eventClass == SFAnalyticsEventClassSuccess) {
1645 return @"EventSuccess";
1647 else if (eventClass == SFAnalyticsEventClassHardFailure) {
1648 return @"EventHardFailure";
1650 else if (eventClass == SFAnalyticsEventClassSoftFailure) {
1651 return @"EventSoftFailure";
1654 return @"EventUnknown";
1658 // MARK: XPC Procotol Handlers
1660 - (void)getSysdiagnoseDumpWithReply:(void (^)(NSString*))reply {
1661 reply([self getSysdiagnoseDump]);
1664 - (void)createLoggingJSON:(bool)pretty topic:(NSString *)topicName reply:(void (^)(NSData *, NSError*))reply {
1665 secnotice("rpcCreateLoggingJSON", "Building a JSON blob resembling the one we would have uploaded");
1666 NSError* error = nil;
1667 [self sendNotificationForOncePerReportSamplers];
1668 NSDictionary *eventDictionary = nil;
1669 for (SFAnalyticsTopic* topic in self->_analyticsTopics) {
1670 if ([topic.internalTopicName isEqualToString:topicName]) {
1671 eventDictionary = [topic createLoggingJSON:pretty forUpload:NO participatingClients:nil force:!runningTests error:&error];
1676 if (!eventDictionary) {
1677 secerror("Unable to obtain JSON: %@", error);
1679 data = [NSJSONSerialization dataWithJSONObject:eventDictionary
1680 options:(pretty ? NSJSONWritingPrettyPrinted : 0)
1687 - (void)createChunkedLoggingJSON:(bool)pretty topic:(NSString *)topicName reply:(void (^)(NSData *, NSError*))reply
1689 secnotice("rpcCreateChunkedLoggingJSON", "Building an array of JSON blobs resembling the one we would have uploaded");
1690 NSError* error = nil;
1691 [self sendNotificationForOncePerReportSamplers];
1692 NSArray<NSDictionary *> *events = nil;
1693 for (SFAnalyticsTopic* topic in self->_analyticsTopics) {
1694 if ([topic.internalTopicName isEqualToString:topicName]) {
1695 events = [topic createChunkedLoggingJSON:pretty forUpload:NO participatingClients:nil force:!runningTests error:&error];
1701 secerror("Unable to obtain JSON: %@", error);
1703 data = [NSJSONSerialization dataWithJSONObject:events
1704 options:(pretty ? NSJSONWritingPrettyPrinted : 0)
1711 - (void)forceUploadWithReply:(void (^)(BOOL, NSError*))reply {
1712 secnotice("upload", "Performing upload in response to rpc message");
1713 NSError* error = nil;
1714 BOOL result = [self uploadAnalyticsWithError:&error force:YES];
1715 secnotice("upload", "Result of manually triggered upload: %@, error: %@", result ? @"success" : @"failure", error);
1716 reply(result, error);
1721 #endif // !TARGET_OS_SIMULATOR