]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSUpdateDeviceStateOperation.m
Security-58286.1.32.tar.gz
[apple/security.git] / keychain / ckks / CKKSUpdateDeviceStateOperation.m
1 /*
2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #if OCTAGON
25
26 #import "keychain/ckks/CKKSKeychainView.h"
27 #import "keychain/ckks/CKKSUpdateDeviceStateOperation.h"
28 #import "keychain/ckks/CKKSCurrentKeyPointer.h"
29 #import "keychain/ckks/CKKSKey.h"
30 #import "keychain/ckks/CKKSLockStateTracker.h"
31 #import "keychain/ckks/CKKSSQLDatabaseObject.h"
32
33 @interface CKKSUpdateDeviceStateOperation ()
34 @property CKModifyRecordsOperation* modifyRecordsOperation;
35 @property CKOperationGroup* group;
36 @property bool rateLimit;
37 @end
38
39 @implementation CKKSUpdateDeviceStateOperation
40
41 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks rateLimit:(bool)rateLimit ckoperationGroup:(CKOperationGroup*)group {
42 if((self = [super init])) {
43 _ckks = ckks;
44 _group = group;
45 _rateLimit = rateLimit;
46 }
47 return self;
48 }
49
50 - (void)groupStart {
51 CKKSKeychainView* ckks = self.ckks;
52 if(!ckks) {
53 ckkserror("ckksdevice", ckks, "no CKKS object");
54 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
55 return;
56 }
57
58 CKKSCKAccountStateTracker* accountTracker = ckks.accountTracker;
59 if(!accountTracker) {
60 ckkserror("ckksdevice", ckks, "no AccountTracker object");
61 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no AccountTracker object"}];
62 return;
63 }
64
65 __weak __typeof(self) weakSelf = self;
66
67 // We must have the ck device ID to run this operation.
68 if([accountTracker.ckdeviceIDInitialized wait:200*NSEC_PER_SEC]) {
69 ckkserror("ckksdevice", ckks, "CK device ID not initialized, quitting");
70 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"CK device ID not initialized"}];
71 return;
72 }
73
74 if(!accountTracker.ckdeviceID) {
75 ckkserror("ckksdevice", ckks, "CK device ID not initialized, quitting");
76 self.error = [NSError errorWithDomain:@"securityd"
77 code:errSecInternalError
78 userInfo:@{NSLocalizedDescriptionKey: @"CK device ID null", NSUnderlyingErrorKey:CKKSNilToNSNull(accountTracker.ckdeviceIDError)}];
79 return;
80 }
81
82 [ckks dispatchSyncWithAccountQueue:^bool {
83 NSError* error = nil;
84
85 CKKSDeviceStateEntry* cdse = [ckks _onqueueCurrentDeviceStateEntry:&error];
86 if(error) {
87 ckkserror("ckksdevice", ckks, "Error creating device state entry; quitting: %@", error);
88 return false;
89 }
90
91 if(self.rateLimit) {
92 NSDate* lastUpdate = cdse.storedCKRecord.modificationDate;
93
94 // Only upload this every 3 days
95 NSDate* now = [NSDate date];
96 NSDateComponents* offset = [[NSDateComponents alloc] init];
97 [offset setHour:-3 * 24];
98 NSDate* deadline = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:now options:0];
99
100 if(lastUpdate == nil || [lastUpdate compare: deadline] == NSOrderedAscending) {
101 ckksnotice("ckksdevice", ckks, "Not rate-limiting: last updated %@ vs %@", lastUpdate, deadline);
102 } else {
103 ckksnotice("ckksdevice", ckks, "Last update is within 3 days (%@); rate-limiting this operation", lastUpdate);
104 self.error = [NSError errorWithDomain:@"securityd"
105 code:errSecInternalError
106 userInfo:@{NSLocalizedDescriptionKey: @"Rate-limited the CKKSUpdateDeviceStateOperation"}];
107 return false;
108 }
109 }
110
111 ckksnotice("ckksdevice", ckks, "Saving new device state %@", cdse);
112
113 NSArray* recordsToSave = @[[cdse CKRecordWithZoneID:ckks.zoneID]];
114
115 // Start a CKModifyRecordsOperation to save this new/updated record.
116 NSBlockOperation* modifyComplete = [[NSBlockOperation alloc] init];
117 modifyComplete.name = @"updateDeviceState-modifyRecordsComplete";
118 [self dependOnBeforeGroupFinished: modifyComplete];
119
120 self.modifyRecordsOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:nil];
121 self.modifyRecordsOperation.atomic = TRUE;
122 self.modifyRecordsOperation.timeoutIntervalForRequest = 2;
123 self.modifyRecordsOperation.qualityOfService = NSQualityOfServiceUtility;
124 self.modifyRecordsOperation.savePolicy = CKRecordSaveAllKeys; // Overwrite anything in CloudKit: this is our state now
125 self.modifyRecordsOperation.group = self.group;
126
127 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
128 __strong __typeof(weakSelf) strongSelf = weakSelf;
129 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
130
131 if(!error) {
132 ckksnotice("ckksdevice", blockCKKS, "Device state record upload successful for %@: %@", record.recordID.recordName, record);
133 } else {
134 ckkserror("ckksdevice", blockCKKS, "error on row: %@ %@", error, record);
135 }
136 };
137
138 self.modifyRecordsOperation.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *ckerror) {
139 __strong __typeof(weakSelf) strongSelf = weakSelf;
140 __strong __typeof(strongSelf.ckks) strongCKKS = strongSelf.ckks;
141 if(!strongSelf || !strongCKKS) {
142 ckkserror("ckksdevice", strongCKKS, "received callback for released object");
143 strongSelf.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
144 [strongSelf runBeforeGroupFinished:modifyComplete];
145 return;
146 }
147
148 if(ckerror) {
149 ckkserror("ckksdevice", strongCKKS, "CloudKit returned an error: %@", ckerror);
150 strongSelf.error = ckerror;
151 [strongSelf runBeforeGroupFinished:modifyComplete];
152 return;
153 }
154
155 __block NSError* error = nil;
156
157 [strongCKKS dispatchSync: ^bool{
158 for(CKRecord* record in savedRecords) {
159 // Save the item records
160 if([record.recordType isEqualToString: SecCKRecordDeviceStateType]) {
161 CKKSDeviceStateEntry* newcdse = [[CKKSDeviceStateEntry alloc] initWithCKRecord:record];
162 [newcdse saveToDatabase:&error];
163 if(error) {
164 ckkserror("ckksdevice", strongCKKS, "Couldn't save new device state(%@) to database: %@", newcdse, error);
165 }
166 }
167 }
168 return true;
169 }];
170
171 strongSelf.error = error;
172 [strongSelf runBeforeGroupFinished:modifyComplete];
173 };
174
175 [self dependOnBeforeGroupFinished: self.modifyRecordsOperation];
176 [ckks.database addOperation: self.modifyRecordsOperation];
177
178 return true;
179 }];
180 }
181
182 @end
183
184 #endif // OCTAGON