1 #import <CloudKit/CKContainer_Private.h>
2 #import <CloudKit/CloudKit.h>
3 #import <CoreFoundation/CFPriv.h>
4 #import <Foundation/Foundation.h>
5 #import <Foundation/NSURLSession.h>
6 #import <dispatch/dispatch.h>
7 #import <os/variant_private.h>
9 #include "policy_dryrun.h"
15 #include <Security/SecItem.h>
16 #include <Security/SecItemPriv.h>
17 #include <Security/Security.h>
18 #include <keychain/SecureObjectSync/SOSCloudCircle.h>
19 #include <keychain/SecureObjectSync/SOSViews.h>
20 #import "TrustedPeers/TrustedPeers.h"
22 #include "tool_errors.h"
24 // Depends on a modern enough TrustedPeers framework.
25 // If the machine doesn't have one installed, set DYLD_FRAMEWORK_PATH
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];
40 if ([itemClass isEqualToString: (NSString*)kSecClassKey] && [ag isEqualToString: @"com.apple.security.sos"]) {
41 return (NSString*)kSOSViewiCloudIdentity;
42 } else if ([ag isEqualToString: @"com.apple.cfnetwork"]) {
43 return (NSString*)kSOSViewAutofillPasswords;
44 } else if ([ag isEqualToString: @"com.apple.safari.credit-cards"]) {
45 return (NSString*)kSOSViewSafariCreditCards;
46 } else if ([itemClass isEqualToString: (NSString*)kSecClassGenericPassword]) {
47 if ([ag isEqualToString: @"apple"] &&
48 [object[(NSString*)kSecAttrService] isEqualToString: @"AirPort"]) {
49 return (NSString*)kSOSViewWiFi;
50 } else if ([ag isEqualToString: @"com.apple.sbd"]) {
51 return (NSString*)kSOSViewBackupBagV0;
53 return (NSString*)kSOSViewOtherSyncable; // (genp)
56 return (NSString*)kSOSViewOtherSyncable; // (inet || keys)
61 static inline NSNumber *now_msecs() {
62 return @(((long)[[NSDate date] timeIntervalSince1970] * 1000));
65 static NSString* cloudKitDeviceID() {
66 __block NSString* ret = nil;
68 if (!os_variant_has_internal_diagnostics("com.apple.security")) {
71 CKContainer *container = [CKContainer containerWithIdentifier:@"com.apple.security.keychain"];
72 dispatch_semaphore_t sem = dispatch_semaphore_create(0);
73 [container fetchCurrentDeviceIDWithCompletionHandler:^(NSString* deviceID, NSError* error) {
75 NSLog(@"failed to fetch CK deviceID: %@", error);
79 dispatch_semaphore_signal(sem);
81 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
85 static void reportStats(unsigned expected_mismatches, unsigned real_mismatches, NSArray<NSDictionary*>* reportedMismatches) {
87 NSURLSessionConfiguration *defaultConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
88 NSURLSession *session = [NSURLSession sessionWithConfiguration:defaultConfiguration];
89 NSURL *endpoint = [NSURL URLWithString:@"https://xp.apple.com/report/2/xp_sear_keysync"];
90 NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
92 req.HTTPMethod = @"POST";
93 NSMutableDictionary *dict = [@{
94 @"expectedMismatches": @(expected_mismatches),
95 @"realMismatches": @(real_mismatches),
96 @"eventTime": now_msecs(),
97 @"topic": @"xp_sear_keysync",
98 @"eventType": @"policy-dryrun",
100 NSDictionary *version = CFBridgingRelease(_CFCopySystemVersionDictionary());
101 NSString *build = version[(__bridge NSString *)_kCFSystemVersionBuildVersionKey];
103 dict[@"build"] = build;
105 NSLog(@"Unable to find out build version");
107 NSString *product = version[(__bridge NSString *)_kCFSystemVersionProductNameKey];
108 if (product != nil) {
109 dict[@"product"] = product;
111 NSLog(@"Unable to find out build product");
113 NSString* ckDeviceID = cloudKitDeviceID();
115 dict[@"SFAnalyticsDeviceID"] = ckDeviceID;
117 NSLog(@"Unable to fetch CK device ID");
120 dict[@"mismatches"] = reportedMismatches;
122 NSArray<NSDictionary*>* events = @[dict];
123 NSDictionary *wrapper = @{
124 @"postTime": @([[NSDate date] timeIntervalSince1970] * 1000),
127 NSData* data = [NSJSONSerialization dataWithJSONObject:wrapper options:0 error:&error];
128 if (data == nil || error != nil) {
129 NSLog(@"failed to encode data: %@", error);
132 NSLog(@"logging %@, %@", wrapper, 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 int policy_dryrun(int argc, char * const *argv) {
160 NSError* error = nil;
161 // From Swift.policy, policy v5
163 TPPolicyDocument *tpd = [TPPolicyDocument policyDocWithHash:@"SHA256:O/ECQlWhvNlLmlDNh2+nal/yekUC87bXpV3k+6kznSo="
164 data:[[NSData alloc] initWithBase64EncodedString:
165 @"CAUSDgoGaVBob25lEgRmdWxsEgwKBGlQYWQSBGZ1bGwSDAoEaVBvZBIEZnVsbBILCgNNYWMSBGZ1bGwSDAoEaU1hYxIEZnVsbBINCgdBcHBsZVRWEgJ0dhIOCgVXYXRjaBIFd2F0Y2gSFwoOQXVkaW9BY2Nlc3NvcnkSBWF1ZGlvGhsKDEFwcGxpY2F0aW9ucxIEZnVsbBIFd2F0Y2gaHwoQU2VjdXJlT2JqZWN0U3luYxIEZnVsbBIFd2F0Y2gaHAoNRGV2aWNlUGFpcmluZxIEZnVsbBIFd2F0Y2gaGgoLQ3JlZGl0Q2FyZHMSBGZ1bGwSBXdhdGNoGhUKBkhlYWx0aBIEZnVsbBIFd2F0Y2gaLQoTTGltaXRlZFBlZXJzQWxsb3dlZBIEZnVsbBIFd2F0Y2gSAnR2EgVhdWRpbxokChVQcm90ZWN0ZWRDbG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zdHJ5JBIcAAQiGAIEdndodAoQXldhdGNoTWlncmF0aW9uJBINRGV2aWNlUGFpcmluZzIOCgIABhIIQmFja3N0b3A=" options:0]];
166 TPPolicy *policy = [tpd policyWithSecrets:@{} decrypter:nil error:&error];
168 NSLog(@"policy error: %@", error);
172 NSLog(@"policy is nil");
175 unsigned real_mismatches = 0;
176 unsigned expected_mismatches = 0;
177 NSMutableArray<NSDictionary*>* reportedMismatches = [[NSMutableArray<NSDictionary*> alloc] init];
179 NSArray<NSString*>* keychainClasses = @[(id)kSecClassInternetPassword,
180 (id)kSecClassGenericPassword,
182 (id)kSecClassCertificate];
184 for(NSString* itemClass in keychainClasses) {
185 NSLog(@"itemClass: %@", itemClass);
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);