1 #include "PolicyReporter.h"
3 #import <CloudKit/CKContainer_Private.h>
4 #import <CloudKit/CloudKit.h>
5 #import <CoreFoundation/CFPriv.h>
6 #import <Foundation/Foundation.h>
7 #import <Foundation/NSURLSession.h>
8 #import <dispatch/dispatch.h>
9 #import <os/feature_private.h>
10 #import <os/variant_private.h>
17 #include <xpc/private.h>
18 #include <Security/SecItem.h>
19 #include <Security/SecItemPriv.h>
20 #include <Security/Security.h>
21 #include <keychain/SecureObjectSync/SOSCloudCircle.h>
22 #include <keychain/SecureObjectSync/SOSViews.h>
23 #include <utilities/SecAKSWrappers.h>
24 #import "utilities/debugging.h"
25 #import "TrustedPeers/TrustedPeers.h"
27 // Stolen from keychain/SecureObjectSync/SOSEngine.c
29 static NSString* getSOSView(id object, NSString* itemClass) {
30 if (![object isKindOfClass:[NSDictionary class]]) {
34 NSString *viewHint = object[(NSString*)kSecAttrSyncViewHint];
35 if (viewHint != nil) {
38 NSString *ag = object[(NSString*)kSecAttrAccessGroup];
39 if ([itemClass isEqualToString: (NSString*)kSecClassKey] && [ag isEqualToString: @"com.apple.security.sos"]) {
40 return (NSString*)kSOSViewiCloudIdentity;
41 } else if ([ag isEqualToString: @"com.apple.cfnetwork"]) {
42 return (NSString*)kSOSViewAutofillPasswords;
43 } else if ([ag isEqualToString: @"com.apple.safari.credit-cards"]) {
44 return (NSString*)kSOSViewSafariCreditCards;
45 } else if ([itemClass isEqualToString: (NSString*)kSecClassGenericPassword]) {
46 if ([ag isEqualToString: @"apple"] &&
47 [object[(NSString*)kSecAttrService] isEqualToString: @"AirPort"]) {
48 return (NSString*)kSOSViewWiFi;
49 } else if ([ag isEqualToString: @"com.apple.sbd"]) {
50 return (NSString*)kSOSViewBackupBagV0;
52 return (NSString*)kSOSViewOtherSyncable; // (genp)
55 return (NSString*)kSOSViewOtherSyncable; // (inet || keys)
60 static inline NSNumber *now_msecs() {
61 return @(((long)[[NSDate date] timeIntervalSince1970] * 1000));
64 static NSString* cloudKitDeviceID() {
65 __block NSString* ret = nil;
67 if (!os_variant_has_internal_diagnostics("com.apple.security")) {
70 CKContainer *container = [CKContainer containerWithIdentifier:@"com.apple.security.keychain"];
71 dispatch_semaphore_t sem = dispatch_semaphore_create(0);
72 [container fetchCurrentDeviceIDWithCompletionHandler:^(NSString* deviceID, NSError* error) {
74 NSLog(@"failed to fetch CK deviceID: %@", error);
78 dispatch_semaphore_signal(sem);
80 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
84 static void reportStats(unsigned expected_mismatches, unsigned real_mismatches, NSArray<NSDictionary*>* reportedMismatches) {
85 NSURLSessionConfiguration *defaultConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
86 NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfiguration];
87 NSURL *endpoint = [NSURL URLWithString:@"https://xp.apple.com/report/2/xp_sear_keysync"];
88 NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
90 req.HTTPMethod = @"POST";
91 NSMutableDictionary *dict = [@{
92 @"expectedMismatches": @(expected_mismatches),
93 @"realMismatches": @(real_mismatches),
94 @"eventTime": now_msecs(),
95 @"topic": @"xp_sear_keysync",
96 @"eventType": @"policy-dryrun",
98 NSDictionary *version = CFBridgingRelease(_CFCopySystemVersionDictionary());
99 NSString *build = version[(__bridge NSString *)_kCFSystemVersionBuildVersionKey];
101 dict[@"build"] = build;
103 NSLog(@"Unable to find out build version");
105 NSString *product = version[(__bridge NSString *)_kCFSystemVersionProductNameKey];
106 if (product != nil) {
107 dict[@"product"] = product;
109 NSLog(@"Unable to find out build product");
111 NSString* ckDeviceID = cloudKitDeviceID();
113 dict[@"SFAnalyticsDeviceID"] = ckDeviceID;
114 dict[@"ckdeviceID"] = ckDeviceID;
116 NSLog(@"Unable to fetch CK device ID");
119 dict[@"mismatches"] = reportedMismatches;
121 NSArray<NSDictionary*>* events = @[dict];
122 NSDictionary *wrapper = @{
123 @"postTime": @([[NSDate date] timeIntervalSince1970] * 1000),
126 NSError *encodeError = nil;
127 NSData* post_data = [NSJSONSerialization dataWithJSONObject:wrapper options:0 error:&encodeError];
128 if (post_data == nil || encodeError != nil) {
129 NSLog(@"failed to encode data: %@", encodeError);
132 NSLog(@"logging %@, %@", wrapper, post_data);
133 req.HTTPBody = post_data;
134 dispatch_semaphore_t sem = dispatch_semaphore_create(0);
135 NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
137 NSLog(@"splunk upload failed: %@", error);
140 NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*)response;
141 if (httpResp.statusCode != 200) {
142 NSLog(@"HTTP Post error: %@", httpResp);
144 NSLog(@"%@", httpResp);
146 size_t length = [data length];
147 char *buf = malloc(length);
148 [data getBytes:buf length:length];
149 NSLog(@"%.*s", (int)length, buf);
152 dispatch_semaphore_signal(sem);
155 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
158 static void oneReport(void) {
159 NSError* error = nil;
161 // From Swift.policy, policy v5
162 TPPolicyDocument *tpd = [TPPolicyDocument policyDocWithHash:@"SHA256:O/ECQlWhvNlLmlDNh2+nal/yekUC87bXpV3k+6kznSo="
163 data:[[NSData alloc] initWithBase64EncodedString:
164 @"CAUSDgoGaVBob25lEgRmdWxsEgwKBGlQYWQSBGZ1bGwSDAoEaVBvZBIEZnVsbBILCgNNYWMSBGZ1bGwSDAoEaU1hYxIEZnVsbBINCgdBcHBsZVRWEgJ0dhIOCgVXYXRjaBIFd2F0Y2gSFwoOQXVkaW9BY2Nlc3NvcnkSBWF1ZGlvGhsKDEFwcGxpY2F0aW9ucxIEZnVsbBIFd2F0Y2gaHwoQU2VjdXJlT2JqZWN0U3luYxIEZnVsbBIFd2F0Y2gaHAoNRGV2aWNlUGFpcmluZxIEZnVsbBIFd2F0Y2gaGgoLQ3JlZGl0Q2FyZHMSBGZ1bGwSBXdhdGNoGhUKBkhlYWx0aBIEZnVsbBIFd2F0Y2gaLQoTTGltaXRlZFBlZXJzQWxsb3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oSXkFjY2Vzc29yeVBhaXJpbmckEhoABCIWAgR2d2h0Cg5eTmFub1JlZ2lzdHJ5JBIcAAQiGAIEdndodAoQXldhdGNoTWlncmF0aW9uJBINRGV2aWNlUGFpcmluZzIOCgIABhIIQmFja3N0b3A=" options:0]];
166 TPPolicy *policy = [tpd policyWithSecrets:@{} decrypter:nil error:&error];
168 NSLog(@"policy error: %@", error);
172 NSLog(@"policy is nil");
176 unsigned real_mismatches = 0;
177 unsigned expected_mismatches = 0;
178 NSMutableArray<NSDictionary*>* reportedMismatches = [[NSMutableArray<NSDictionary*> alloc] init];
180 NSArray<NSString*>* keychainClasses = @[(id)kSecClassInternetPassword,
181 (id)kSecClassGenericPassword,
183 (id)kSecClassCertificate];
185 for(NSString* itemClass in keychainClasses) {
186 NSDictionary *query = @{ (id)kSecMatchLimit : (id)kSecMatchLimitAll,
187 (id)kSecClass : (id)itemClass,
188 (id)kSecReturnAttributes : @YES,
189 (id)kSecAttrSynchronizable: @YES,
190 (id)kSecUseDataProtectionKeychain: @YES,
191 (id)kSecUseAuthenticationUI : (id)kSecUseAuthenticationUISkip,
196 OSStatus status = SecItemCopyMatching((CFDictionaryRef)query, (void*)&result);
198 if (status == errSecItemNotFound) {
199 NSLog(@"no items found matching: %@", query);
202 NSLog(@"SecItemCopyMatching(%@) failed: %d", query, (int)status);
207 if (![result isKindOfClass:[NSArray class]]) {
208 NSLog(@"expected NSArray result from SecItemCopyMatching");
212 for (id a in result) {
214 NSString *oldView = getSOSView(a, itemClass);
215 if (oldView != nil) {
216 NSLog(@"old: %@", oldView);
219 NSMutableDictionary* mutA = [a mutableCopy];
220 mutA[(id)kSecClass] = (id)itemClass;
222 NSString* newView = [policy mapKeyToView:mutA];
223 if (newView != nil) {
224 NSLog(@"new: %@", newView);
226 if(oldView == nil ^ newView == nil) {
227 NSLog(@"real mismatch: old view (%@) != new view (%@)", oldView, newView);
229 [reportedMismatches addObject: a];
231 } else if (oldView && newView && ![oldView isEqualToString: newView]) {
232 if ([oldView hasPrefix:@"PCS-"] && [newView isEqualToString: @"ProtectedCloudStorage"]) {
233 NSLog(@"(expected PCS mismatch): old view (%@) != new view (%@)", oldView, newView);
234 ++expected_mismatches;
236 } else if([oldView isEqualToString:@"OtherSyncable"] && [newView isEqualToString: @"Applications"]) {
237 NSLog(@"(expected 3rd party mismatch): old view (%@) != new view (%@)", oldView, newView);
238 ++expected_mismatches;
240 } else if([oldView isEqualToString:@"OtherSyncable"] && [newView isEqualToString: @"Backstop"]) {
241 NSLog(@"(expected backstop mismatch): old view (%@) != new view (%@)", oldView, newView);
242 ++expected_mismatches;
244 } else if([newView isEqualToString:@"NotSynced"]) {
245 NSLog(@"(expected NotSynced mismatch): old view (%@) != new view (%@)", oldView, newView);
246 ++expected_mismatches;
248 } else if(([oldView isEqualToString:@"BackupBagV0"] || [oldView isEqualToString:@"iCloudIdentity"]) && [newView isEqualToString:@"SecureObjectSync"]) {
249 NSLog(@"(expected BackupBag - SecureObjectSync mismatch): old view (%@) != new view (%@)", oldView, newView);
250 ++expected_mismatches;
252 } else if(([oldView isEqualToString:@"AccessoryPairing"]
253 || [oldView isEqualToString:@"NanoRegistry"]
254 || [oldView isEqualToString:@"WatchMigration"]) && [newView isEqualToString:@"DevicePairing"]) {
255 NSLog(@"(expected DevicePairing mismatch): old view (%@) != new view (%@)", oldView, newView);
256 ++expected_mismatches;
259 NSLog(@"real mismatch: old view (%@) != new view (%@)", oldView, newView);
261 [reportedMismatches addObject: a];
267 NSLog(@"%d expected_mismatches", expected_mismatches);
268 NSLog(@"%d real_mismatches", real_mismatches);
269 reportStats(expected_mismatches, real_mismatches, reportedMismatches);
272 static dispatch_queue_t queue;
274 static void report(void);
276 static void maybeReport(void) {
277 CFErrorRef error = NULL;
279 if (!SecAKSGetIsLocked(&locked, &error)) {
280 secerror("PolicyReporter: %@", error);
281 CFReleaseNull(error);
282 xpc_object_t options = xpc_dictionary_create(NULL, NULL, 0);
283 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_DELAY, random() % 60);
284 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_GRACE_PERIOD, 30);
285 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REPEATING, false);
286 xpc_dictionary_set_bool(options, XPC_ACTIVITY_ALLOW_BATTERY, true);
287 xpc_dictionary_set_string(options, XPC_ACTIVITY_PRIORITY, XPC_ACTIVITY_PRIORITY_UTILITY);
288 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REQUIRE_NETWORK_CONNECTIVITY, true);
290 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REQUIRES_CLASS_A, true);
292 xpc_activity_register("com.apple.security.securityd.policy-reporting2",
293 options, ^(xpc_activity_t activity) {
301 notify_register_dispatch(kUserKeybagStateChangeNotification, &token, queue, ^(int t) {
309 static void report() {
315 void InitPolicyReporter(void) {
316 if (!os_feature_enabled(Security, securitydReportPolicy)) {
317 secnotice("securityd-PolicyReporter", "not enabled by feature flag");
321 srandom(getpid() ^ (int)time(NULL));
322 queue = dispatch_queue_create("com.apple.security.securityd_reporting", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
323 xpc_object_t options = xpc_dictionary_create(NULL, NULL, 0);
324 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_DELAY, random() % 3600);
325 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_GRACE_PERIOD, 1800);
326 xpc_dictionary_set_uint64(options, XPC_ACTIVITY_INTERVAL, 3600);
327 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REPEATING, true);
328 xpc_dictionary_set_bool(options, XPC_ACTIVITY_ALLOW_BATTERY, true);
329 xpc_dictionary_set_string(options, XPC_ACTIVITY_PRIORITY, XPC_ACTIVITY_PRIORITY_UTILITY);
330 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REQUIRE_NETWORK_CONNECTIVITY, true);
332 xpc_dictionary_set_bool(options, XPC_ACTIVITY_REQUIRES_CLASS_A, true);
335 xpc_activity_register("com.apple.security.securityd.policy-reporting",
336 options, ^(xpc_activity_t activity) {