2 * Copyright (c) 2016 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 #include <AssertMacros.h>
28 #import <Foundation/Foundation.h>
30 #import <CloudKit/CloudKit.h>
31 #import <CloudKit/CloudKit_Private.h>
32 #import "keychain/ckks/CKKSDeviceStateEntry.h"
33 #import "keychain/ckks/CKKSKeychainView.h"
34 #include <Security/SecureObjectSync/SOSAccount.h>
36 @implementation CKKSDeviceStateEntry
38 - (instancetype)initForDevice:(NSString*)device
39 osVersion:(NSString*)osVersion
40 lastUnlockTime:(NSDate*)lastUnlockTime
41 octagonPeerID:(NSString*)octagonPeerID
42 octagonStatus:(OTCliqueStatusWrapper*)octagonStatus
43 circlePeerID:(NSString*)circlePeerID
44 circleStatus:(SOSCCStatus)circleStatus
45 keyState:(CKKSZoneKeyState*)keyState
46 currentTLKUUID:(NSString*)currentTLKUUID
47 currentClassAUUID:(NSString*)currentClassAUUID
48 currentClassCUUID:(NSString*)currentClassCUUID
49 zoneID:(CKRecordZoneID*)zoneID
50 encodedCKRecord:(NSData*)encodedrecord
52 if((self = [super initWithCKRecordType:SecCKRecordDeviceStateType
53 encodedCKRecord:encodedrecord
56 _osVersion = osVersion;
57 _lastUnlockTime = lastUnlockTime;
59 _octagonPeerID = octagonPeerID;
60 _octagonStatus = octagonStatus;
62 _circleStatus = circleStatus;
65 _circlePeerID = circlePeerID;
67 _currentTLKUUID = currentTLKUUID;
68 _currentClassAUUID = currentClassAUUID;
69 _currentClassCUUID = currentClassCUUID;
74 #define kSOSCCErrorPositive 111
76 -(id)sosCCStatusToCKType:(SOSCCStatus)status {
77 // kSOSCCError is -1, but without a size.
78 // make it a special number
79 if(status == kSOSCCError) {
80 return [NSNumber numberWithInt:kSOSCCErrorPositive];
82 return [NSNumber numberWithInt:status];
85 -(SOSCCStatus)cktypeToSOSCCStatus:(id)object {
86 if(![object isKindOfClass:[NSNumber class]]) {
89 NSNumber* number = (NSNumber*)object;
91 uint32_t n = [number unsignedIntValue];
94 case (uint32_t)kSOSCCInCircle:
95 return kSOSCCInCircle;
96 case (uint32_t)kSOSCCNotInCircle:
97 return kSOSCCNotInCircle;
98 case (uint32_t)kSOSCCRequestPending:
99 return kSOSCCRequestPending;
100 case (uint32_t)kSOSCCCircleAbsent:
101 return kSOSCCCircleAbsent;
102 case (uint32_t)kSOSCCErrorPositive: // Use the magic number
104 case (uint32_t)kSOSCCError: // And, if by some miracle, you end up with -1 as a uint32_t, accept that too
107 secerror("ckks: %d is not an SOSCCStatus?", n);
112 - (id)cliqueStatusToCKType:(OTCliqueStatusWrapper* _Nullable)status {
116 // kSOSCCError is -1, but without a size.
117 // make it a special number
118 if(status.status == CliqueStatusError) {
119 return [NSNumber numberWithInt:kSOSCCErrorPositive];
121 return [NSNumber numberWithInt:(int)status.status];
124 + (OTCliqueStatusWrapper* _Nullable)cktypeToOTCliqueStatusWrapper:(id)object {
128 if(![object isKindOfClass:[NSNumber class]]) {
131 NSNumber* number = (NSNumber*)object;
133 uint32_t n = [number unsignedIntValue];
136 case (uint32_t)CliqueStatusIn:
137 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusIn];
138 case (uint32_t)CliqueStatusNotIn:
139 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusNotIn];
140 case (uint32_t)CliqueStatusPending:
141 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusPending];
142 case (uint32_t)CliqueStatusAbsent:
143 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusAbsent];
144 case (uint32_t)CliqueStatusNoCloudKitAccount:
145 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusNoCloudKitAccount];
146 case (uint32_t)kSOSCCErrorPositive: // Use the magic number
147 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusError];
149 secerror("ckks: %d is not an OTCliqueStatus?", n);
150 return [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusError];;
154 +(NSString*)nameFromCKRecordID:(CKRecordID*)recordID {
155 // Strip off the prefix from the recordName
156 NSString* prefix = @"ckid-";
157 NSString* name = recordID.recordName;
159 if ([name hasPrefix:prefix]) {
160 name = [name substringFromIndex:[prefix length]];
165 -(NSString*)description {
166 NSDate* updated = self.storedCKRecord.modificationDate;
168 return [NSString stringWithFormat:@"<CKKSDeviceStateEntry(%@,%@,%@,%@,%@,%@): %@ %@ %@ %@ %@ %@ upd:%@>",
174 self.zoneID.zoneName,
175 SOSAccountGetSOSCCStatusString(self.circleStatus),
176 self.octagonStatus ? OTCliqueStatusToString(self.octagonStatus.status) : @"CliqueMissing",
179 self.currentClassAUUID,
180 self.currentClassCUUID,
181 updated ? updated : @"unknown"
185 - (BOOL)isEqual: (id) object {
186 if(![object isKindOfClass:[CKKSDeviceStateEntry class]]) {
190 CKKSDeviceStateEntry* obj = (CKKSDeviceStateEntry*) object;
192 return ([self.zoneID isEqual: obj.zoneID] &&
193 ((self.device == nil && obj.device == nil) || [self.device isEqual: obj.device]) &&
194 ((self.osVersion == nil && obj.osVersion == nil) || [self.osVersion isEqual:obj.osVersion]) &&
195 ((self.lastUnlockTime == nil && obj.lastUnlockTime == nil) || [self.lastUnlockTime isEqual:obj.lastUnlockTime]) &&
196 ((self.octagonPeerID == nil && obj.octagonPeerID == nil) || [self.octagonPeerID isEqual: obj.octagonPeerID]) &&
197 ((self.octagonStatus == nil && obj.octagonStatus == nil) || [self.octagonStatus isEqual: obj.octagonStatus]) &&
198 ((self.circlePeerID == nil && obj.circlePeerID == nil) || [self.circlePeerID isEqual: obj.circlePeerID]) &&
199 (self.circleStatus == obj.circleStatus) &&
200 ((self.keyState == nil && obj.keyState == nil) || [self.keyState isEqual: obj.keyState]) &&
201 ((self.currentTLKUUID == nil && obj.currentTLKUUID == nil) || [self.currentTLKUUID isEqual: obj.currentTLKUUID]) &&
202 ((self.currentClassAUUID == nil && obj.currentClassAUUID == nil) || [self.currentClassAUUID isEqual: obj.currentClassAUUID]) &&
203 ((self.currentClassCUUID == nil && obj.currentClassCUUID == nil) || [self.currentClassCUUID isEqual: obj.currentClassCUUID]) &&
207 #pragma mark - Database Operations
209 + (instancetype)fromDatabase:(NSString*)device zoneID:(CKRecordZoneID*)zoneID error:(NSError * __autoreleasing *)error {
210 return [self fromDatabaseWhere: @{@"device":CKKSNilToNSNull(device), @"ckzone": CKKSNilToNSNull(zoneID.zoneName)} error:error];
213 + (instancetype)tryFromDatabase:(NSString*)device zoneID:(CKRecordZoneID*)zoneID error:(NSError * __autoreleasing *)error {
214 return [self tryFromDatabaseWhere: @{@"device":CKKSNilToNSNull(device), @"ckzone": CKKSNilToNSNull(zoneID.zoneName)} error:error];
217 + (instancetype)tryFromDatabaseFromCKRecordID:(CKRecordID*)recordID error:(NSError * __autoreleasing *)error {
218 return [self tryFromDatabaseWhere: @{@"device":CKKSNilToNSNull([self nameFromCKRecordID:recordID]), @"ckzone": CKKSNilToNSNull(recordID.zoneID.zoneName)} error:error];
221 + (NSArray<CKKSDeviceStateEntry*>*)allInZone:(CKRecordZoneID*)zoneID error:(NSError * __autoreleasing *)error {
222 return [self allWhere:@{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)} error:error];
225 #pragma mark - CKKSCKRecordHolder methods
227 - (NSString*)CKRecordName {
228 return [NSString stringWithFormat:@"ckid-%@", self.device];
231 - (CKRecord*)updateCKRecord: (CKRecord*) record zoneID: (CKRecordZoneID*) zoneID {
232 if(![record.recordID.recordName isEqualToString: [self CKRecordName]]) {
234 exceptionWithName:@"WrongCKRecordNameException"
235 reason:[NSString stringWithFormat: @"CKRecord name (%@) was not %@", record.recordID.recordName, [self CKRecordName]]
238 if(![record.recordType isEqualToString: SecCKRecordDeviceStateType]) {
240 exceptionWithName:@"WrongCKRecordTypeException"
241 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordDeviceStateType]
245 record[SecCKSRecordOSVersionKey] = self.osVersion;
246 record[SecCKSRecordLastUnlockTime] = self.lastUnlockTime;
248 record[SecCKRecordOctagonPeerID] = self.octagonPeerID;
249 record[SecCKRecordOctagonStatus] = [self cliqueStatusToCKType:self.octagonStatus];
251 record[SecCKRecordCircleStatus] = [self sosCCStatusToCKType: self.circleStatus];
252 record[SecCKRecordKeyState] = CKKSZoneKeyToNumber(self.keyState);
254 record[SecCKRecordCirclePeerID] = self.circlePeerID;
256 #define CKKeyRef(uuid) (!uuid ? nil : [[CKReference alloc] initWithRecordID:[[CKRecordID alloc] initWithRecordName:uuid \
257 zoneID:self.zoneID] \
258 action: CKReferenceActionNone])
260 record[SecCKRecordCurrentTLK] = CKKeyRef(self.currentTLKUUID);
261 record[SecCKRecordCurrentClassA] = CKKeyRef(self.currentClassAUUID);
262 record[SecCKRecordCurrentClassC] = CKKeyRef(self.currentClassCUUID);
267 - (bool)matchesCKRecord: (CKRecord*) record {
268 if(![record.recordType isEqualToString: SecCKRecordDeviceStateType]) {
272 if(![record.recordID.recordName isEqualToString: [self CKRecordName]]) {
276 if((!(self.lastUnlockTime == nil && record[SecCKSRecordLastUnlockTime] == nil)) &&
277 ![record[SecCKSRecordLastUnlockTime] isEqual: self.lastUnlockTime]) {
281 if((!(self.osVersion == nil && record[SecCKSRecordOSVersionKey] == nil)) &&
282 ![record[SecCKSRecordOSVersionKey] isEqualToString: self.osVersion]) {
286 if((!(self.circlePeerID == nil && record[SecCKRecordCirclePeerID] == nil)) &&
287 ![record[SecCKRecordCirclePeerID] isEqualToString: self.circlePeerID]) {
291 if((!(self.octagonPeerID == nil && record[SecCKRecordOctagonPeerID] == nil)) &&
292 ![record[SecCKRecordOctagonPeerID] isEqualToString:self.octagonPeerID]) {
296 if((!(self.octagonStatus == nil && record[SecCKRecordOctagonStatus] == nil)) &&
297 [self.octagonStatus isEqual: [CKKSDeviceStateEntry cktypeToOTCliqueStatusWrapper:record[SecCKRecordOctagonStatus]]]) {
301 if([self cktypeToSOSCCStatus: record[SecCKRecordCircleStatus]] != self.circleStatus) {
305 if(![CKKSZoneKeyRecover(record[SecCKRecordKeyState]) isEqualToString: self.keyState]) {
309 if(![[[record[SecCKRecordCurrentTLK] recordID] recordName] isEqualToString: self.currentTLKUUID]) {
312 if(![[[record[SecCKRecordCurrentClassA] recordID] recordName] isEqualToString: self.currentTLKUUID]) {
315 if(![[[record[SecCKRecordCurrentClassC] recordID] recordName] isEqualToString: self.currentTLKUUID]) {
322 - (void)setFromCKRecord: (CKRecord*) record {
323 if(![record.recordType isEqualToString: SecCKRecordDeviceStateType]) {
325 exceptionWithName:@"WrongCKRecordTypeException"
326 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordDeviceStateType]
330 [self setStoredCKRecord:record];
332 self.osVersion = record[SecCKSRecordOSVersionKey];
333 self.lastUnlockTime = record[SecCKSRecordLastUnlockTime];
334 self.device = [CKKSDeviceStateEntry nameFromCKRecordID: record.recordID];
336 self.octagonPeerID = record[SecCKRecordOctagonPeerID];
337 self.octagonStatus = [CKKSDeviceStateEntry cktypeToOTCliqueStatusWrapper:record[SecCKRecordOctagonStatus]];
339 self.circlePeerID = record[SecCKRecordCirclePeerID];
341 self.circleStatus = [self cktypeToSOSCCStatus:record[SecCKRecordCircleStatus]];
343 self.keyState = CKKSZoneKeyRecover(record[SecCKRecordKeyState]);
345 self.currentTLKUUID = [[record[SecCKRecordCurrentTLK] recordID] recordName];
346 self.currentClassAUUID = [[record[SecCKRecordCurrentClassA] recordID] recordName];
347 self.currentClassCUUID = [[record[SecCKRecordCurrentClassC] recordID] recordName];
350 #pragma mark - CKKSSQLDatabaseObject methods
352 + (NSString*)sqlTable {
353 return @"ckdevicestate";
356 + (NSArray<NSString*>*)sqlColumns {
357 // NOTE: due to schedule reasons, in this release we can't modify the DB schema, so octagon status and peer ID can't be stored
358 // in normal columns. So, they're stored in the ckrecord field. Good luck!
359 return @[@"device", @"ckzone", @"osversion", @"lastunlock", @"peerid", @"circlestatus", @"keystate", @"currentTLK", @"currentClassA", @"currentClassC", @"ckrecord"];
362 - (NSDictionary<NSString*,NSString*>*)whereClauseToFindSelf {
363 return @{@"device":self.device, @"ckzone":self.zoneID.zoneName};
366 - (NSDictionary<NSString*,NSString*>*)sqlValues {
367 NSISO8601DateFormatter* dateFormat = [[NSISO8601DateFormatter alloc] init];
369 return @{@"device": self.device,
370 @"ckzone": CKKSNilToNSNull(self.zoneID.zoneName),
371 @"osversion": CKKSNilToNSNull(self.osVersion),
372 @"lastunlock": CKKSNilToNSNull(self.lastUnlockTime ? [dateFormat stringFromDate:self.lastUnlockTime] : nil),
373 @"peerid": CKKSNilToNSNull(self.circlePeerID),
374 @"circlestatus": (__bridge NSString*)SOSAccountGetSOSCCStatusString(self.circleStatus),
375 @"keystate": CKKSNilToNSNull(self.keyState),
376 @"currentTLK": CKKSNilToNSNull(self.currentTLKUUID),
377 @"currentClassA": CKKSNilToNSNull(self.currentClassAUUID),
378 @"currentClassC": CKKSNilToNSNull(self.currentClassCUUID),
379 @"ckrecord": CKKSNilToNSNull([self.encodedCKRecord base64EncodedStringWithOptions:0]),
383 + (instancetype)fromDatabaseRow:(NSDictionary*)row {
384 NSISO8601DateFormatter* dateFormat = [[NSISO8601DateFormatter alloc] init];
386 CKKSDeviceStateEntry* entry =
387 [[CKKSDeviceStateEntry alloc] initForDevice:row[@"device"]
388 osVersion:CKKSNSNullToNil(row[@"osversion"])
389 lastUnlockTime:[row[@"lastunlock"] isEqual: [NSNull null]] ? nil : [dateFormat dateFromString: row[@"lastunlock"]]
392 circlePeerID:CKKSNSNullToNil(row[@"peerid"])
393 circleStatus:SOSAccountGetSOSCCStatusFromString((__bridge CFStringRef) CKKSNSNullToNil(row[@"circlestatus"]))
394 keyState:CKKSNSNullToNil(row[@"keystate"])
395 currentTLKUUID:CKKSNSNullToNil(row[@"currentTLK"])
396 currentClassAUUID:CKKSNSNullToNil(row[@"currentClassA"])
397 currentClassCUUID:CKKSNSNullToNil(row[@"currentClassC"])
398 zoneID:[[CKRecordZoneID alloc] initWithZoneName: row[@"ckzone"] ownerName:CKCurrentUserDefaultName]
399 encodedCKRecord:CKKSUnbase64NullableString(row[@"ckrecord"])
402 // NOTE: due to schedule reasons, in this release we can't modify the DB schema, so octagon status and peer ID can't be stored
403 // in normal columns. So, if they're stored in the ckrecord field, use that!
404 CKRecord* record = entry.storedCKRecord;
406 entry.octagonPeerID = record[SecCKRecordOctagonPeerID];
407 entry.octagonStatus = [self cktypeToOTCliqueStatusWrapper:record[SecCKRecordOctagonStatus]];