2 * Copyright (c) 2017 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 "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"
33 @interface CKKSUpdateDeviceStateOperation ()
34 @property CKModifyRecordsOperation* modifyRecordsOperation;
35 @property CKOperationGroup* group;
36 @property bool rateLimit;
39 @implementation CKKSUpdateDeviceStateOperation
41 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks rateLimit:(bool)rateLimit ckoperationGroup:(CKOperationGroup*)group {
42 if((self = [super init])) {
45 _rateLimit = rateLimit;
51 CKKSKeychainView* ckks = self.ckks;
53 ckkserror("ckksdevice", ckks, "no CKKS object");
54 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
58 CKKSCKAccountStateTracker* accountTracker = ckks.accountTracker;
60 ckkserror("ckksdevice", ckks, "no AccountTracker object");
61 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no AccountTracker object"}];
65 __weak __typeof(self) weakSelf = self;
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"}];
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)}];
82 [ckks dispatchSyncWithAccountQueue:^bool {
85 CKKSDeviceStateEntry* cdse = [ckks _onqueueCurrentDeviceStateEntry:&error];
87 ckkserror("ckksdevice", ckks, "Error creating device state entry; quitting: %@", error);
92 NSDate* lastUpdate = cdse.storedCKRecord.modificationDate;
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];
100 if(lastUpdate == nil || [lastUpdate compare: deadline] == NSOrderedAscending) {
101 ckksnotice("ckksdevice", ckks, "Not rate-limiting: last updated %@ vs %@", lastUpdate, deadline);
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"}];
111 ckksnotice("ckksdevice", ckks, "Saving new device state %@", cdse);
113 NSArray* recordsToSave = @[[cdse CKRecordWithZoneID:ckks.zoneID]];
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];
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;
127 self.modifyRecordsOperation.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
128 __strong __typeof(weakSelf) strongSelf = weakSelf;
129 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
132 ckksnotice("ckksdevice", blockCKKS, "Device state record upload successful for %@: %@", record.recordID.recordName, record);
134 ckkserror("ckksdevice", blockCKKS, "error on row: %@ %@", error, record);
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];
149 ckkserror("ckksdevice", strongCKKS, "CloudKit returned an error: %@", ckerror);
150 strongSelf.error = ckerror;
151 [strongSelf runBeforeGroupFinished:modifyComplete];
155 __block NSError* error = nil;
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];
164 ckkserror("ckksdevice", strongCKKS, "Couldn't save new device state(%@) to database: %@", newcdse, error);
171 strongSelf.error = error;
172 [strongSelf runBeforeGroupFinished:modifyComplete];
175 [self dependOnBeforeGroupFinished: self.modifyRecordsOperation];
176 [ckks.database addOperation: self.modifyRecordsOperation];