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 "CKKSViewManager.h"
27 #import "CKKSKeychainView.h"
28 #import "CKKSCurrentKeyPointer.h"
30 #import "keychain/categories/NSError+UsefulConstructors.h"
31 #include "keychain/securityd/SecItemSchema.h"
32 #include <Security/SecItem.h>
33 #include <Security/SecItemPriv.h>
34 #include "OSX/sec/Security/SecItemShim.h"
36 #include <CloudKit/CloudKit.h>
37 #include <CloudKit/CloudKit_Private.h>
39 #import <Foundation/NSData_Private.h>
41 @implementation CKKSKey
43 - (instancetype)init {
48 - (instancetype) initSelfWrappedWithAESKey: (CKKSAESSIVKey*) aeskey
49 uuid: (NSString*) uuid
50 keyclass: (CKKSKeyClass*)keyclass
51 state: (CKKSProcessedState*) state
52 zoneID: (CKRecordZoneID*) zoneID
53 encodedCKRecord: (NSData*) encodedrecord
54 currentkey: (NSInteger) currentkey
56 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
57 encodedCKRecord:encodedrecord
60 _keycore = [[CKKSKeychainBackedKey alloc] initSelfWrappedWithAESKey:aeskey
68 _currentkey = !!currentkey;
74 - (instancetype) initWrappedBy: (CKKSKey*) wrappingKey
75 AESKey: (CKKSAESSIVKey*) aeskey
76 uuid: (NSString*) uuid
77 keyclass: (CKKSKeyClass*)keyclass
78 state: (CKKSProcessedState*) state
79 zoneID: (CKRecordZoneID*) zoneID
80 encodedCKRecord: (NSData*) encodedrecord
81 currentkey: (NSInteger) currentkey
83 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
84 encodedCKRecord:encodedrecord
86 _keycore = [[CKKSKeychainBackedKey alloc] initWrappedBy:wrappingKey.keycore
95 _currentkey = !!currentkey;
101 - (instancetype) initWithWrappedAESKey: (CKKSWrappedAESSIVKey*) wrappedaeskey
102 uuid: (NSString*) uuid
103 parentKeyUUID: (NSString*) parentKeyUUID
104 keyclass: (CKKSKeyClass*)keyclass
105 state: (CKKSProcessedState*) state
106 zoneID: (CKRecordZoneID*) zoneID
107 encodedCKRecord: (NSData*) encodedrecord
108 currentkey: (NSInteger) currentkey
110 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
111 encodedCKRecord:encodedrecord
114 _keycore = [[CKKSKeychainBackedKey alloc] initWithWrappedAESKey:wrappedaeskey
116 parentKeyUUID:parentKeyUUID
120 _currentkey = !!currentkey;
126 - (instancetype)initWithKeyCore:(CKKSKeychainBackedKey*)core
128 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
130 zoneID:core.zoneID])) {
133 _state = SecCKKSProcessedStateRemote;
141 - (BOOL)isEqual:(id)object {
142 if(![object isKindOfClass:[CKKSKey class]]) {
146 CKKSKey* obj = (CKKSKey*)object;
148 // Equality ignores state, currentkey, and CK record differences. Be careful...
149 return [self.keycore isEqual:obj.keycore] ? YES : NO;
152 // These used to be properties on CKKSKey, but are now properties on the actual key inside
155 return self.keycore.uuid;
158 - (void)setUuid:(NSString *)uuid
160 self.keycore.uuid = uuid;
163 - (NSString*)parentKeyUUID
165 return self.keycore.parentKeyUUID;
168 - (void)setParentKeyUUID:(NSString *)parentKeyUUID
170 self.keycore.parentKeyUUID = parentKeyUUID;
173 - (CKKSKeyClass*)keyclass
175 return self.keycore.keyclass;
178 - (void)setKeyclass:(CKKSKeyClass*)keyclass
180 self.keycore.keyclass = keyclass;
183 - (CKKSWrappedAESSIVKey*)wrappedkey
185 return self.keycore.wrappedkey;
188 - (void)setWrappedkey:(CKKSWrappedAESSIVKey*)wrappedkey
190 self.keycore.wrappedkey = wrappedkey;
193 - (CKKSAESSIVKey*)aessivkey
195 return self.keycore.aessivkey;
199 return [self.keycore wrapsSelf];
202 - (bool)wrapUnder: (CKKSKey*) wrappingKey error: (NSError * __autoreleasing *) error {
203 return [self.keycore wrapUnder:wrappingKey.keycore error:error];
206 + (instancetype) loadKeyWithUUID: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
207 CKKSKey* key = [CKKSKey fromDatabase: uuid zoneID:zoneID error:error];
209 // failed unwrapping means we can't return a key.
210 if(![key ensureKeyLoaded:error]) {
216 + (CKKSKey*) randomKeyWrappedByParent: (CKKSKey*) parentKey error: (NSError * __autoreleasing *) error {
217 return [self randomKeyWrappedByParent: parentKey keyclass:parentKey.keyclass error:error];
220 + (CKKSKey*) randomKeyWrappedByParent: (CKKSKey*) parentKey keyclass:(CKKSKeyClass*)keyclass error: (NSError * __autoreleasing *) error {
221 CKKSAESSIVKey* aessivkey = [CKKSAESSIVKey randomKey:error];
222 if(aessivkey == nil) {
226 CKKSKey* key = [[CKKSKey alloc] initWrappedBy: parentKey
228 uuid:[[NSUUID UUID] UUIDString]
230 state:SecCKKSProcessedStateLocal
231 zoneID: parentKey.zoneID
237 + (instancetype)randomKeyWrappedBySelf: (CKRecordZoneID*) zoneID error: (NSError * __autoreleasing *) error {
238 CKKSAESSIVKey* aessivkey = [CKKSAESSIVKey randomKey:error];
239 if(aessivkey == nil) {
243 NSString* uuid = [[NSUUID UUID] UUIDString];
245 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: aessivkey
247 keyclass:SecCKKSKeyClassTLK
248 state:SecCKKSProcessedStateLocal
256 - (CKKSKey*)topKeyInAnyState: (NSError * __autoreleasing *) error {
257 NSMutableSet<NSString*>* seenUUID = [[NSMutableSet alloc] init];
260 // Find the top-level key in the hierarchy.
262 if([key wrapsSelf]) {
266 // Check for circular references.
267 if([seenUUID containsObject:key.uuid]) {
268 *error = [NSError errorWithDomain:CKKSErrorDomain
269 code:CKKSCircularKeyReference
270 description:@"Circular reference in key hierarchy"];
274 [seenUUID addObject:key.uuid];
276 // Prefer 'remote' parents.
277 CKKSKey* parent = [CKKSKey tryFromDatabaseWhere: @{@"UUID": key.parentKeyUUID, @"state": SecCKKSProcessedStateRemote} error: error];
279 // No remote parent. Fall back to anything.
281 parent = [CKKSKey fromDatabaseWhere: @{@"UUID": key.parentKeyUUID} error: error];
287 // Couldn't get the parent. Error is already filled.
291 - (CKKSAESSIVKey*)ensureKeyLoaded: (NSError * __autoreleasing *) error {
292 NSError* keychainError = nil;
294 CKKSAESSIVKey* sivkey = [self.keycore ensureKeyLoaded:&keychainError];
299 // Uhh, okay, if that didn't work, try to unwrap via the key hierarchy
300 NSError* keyHierarchyError = nil;
301 if([self unwrapViaKeyHierarchy:&keyHierarchyError]) {
302 // Attempt to save this new key, but don't error if it fails
303 NSError* resaveError = nil;
304 if(![self saveKeyMaterialToKeychain:&resaveError] || resaveError) {
305 secerror("ckkskey: Resaving missing key failed, continuing: %@", resaveError);
308 return self.aessivkey;
311 // Pick an error to report
313 *error = keyHierarchyError ? keyHierarchyError : keychainError;
319 - (CKKSAESSIVKey*)unwrapViaKeyHierarchy: (NSError * __autoreleasing *) error {
321 return self.aessivkey;
324 NSError* localerror = nil;
326 // Attempt to load this key from the keychain
327 if([self.keycore loadKeyMaterialFromKeychain:&localerror]) {
329 return self.aessivkey;
332 // First, check if we're a TLK.
333 if([self.keyclass isEqual: SecCKKSKeyClassTLK]) {
334 // Okay, not loading the key from the keychain above is an issue. If we have a parent key, then fall through to the recursion below.
335 if(!self.parentKeyUUID || [self.parentKeyUUID isEqualToString: self.uuid]) {
343 // Recursively unwrap our parent.
344 CKKSKey* parent = [CKKSKey fromDatabaseAnyState:self.parentKeyUUID zoneID:self.zoneID error:error];
346 // TODO: do we need loop detection here?
347 if(![parent unwrapViaKeyHierarchy: error]) {
351 self.keycore.aessivkey = [parent unwrapAESKey:self.wrappedkey error:error];
352 return self.aessivkey;
355 - (bool)trySelfWrappedKeyCandidate:(CKKSAESSIVKey*)candidate error:(NSError * __autoreleasing *) error {
356 return [self.keycore trySelfWrappedKeyCandidate:candidate error:error];
359 - (CKKSWrappedAESSIVKey*)wrapAESKey: (CKKSAESSIVKey*) keyToWrap error: (NSError * __autoreleasing *) error {
360 return [self.keycore wrapAESKey:keyToWrap error:error];
363 - (CKKSAESSIVKey*)unwrapAESKey: (CKKSWrappedAESSIVKey*) keyToUnwrap error: (NSError * __autoreleasing *) error {
364 return [self.keycore unwrapAESKey:keyToUnwrap error:error];
367 - (NSData*)encryptData: (NSData*) plaintext authenticatedData: (NSDictionary<NSString*, NSData*>*) ad error: (NSError * __autoreleasing *) error {
368 return [self.keycore encryptData:plaintext authenticatedData:ad error:error];
371 - (NSData*)decryptData: (NSData*) ciphertext authenticatedData: (NSDictionary<NSString*, NSData*>*) ad error: (NSError * __autoreleasing *) error {
372 return [self.keycore decryptData:ciphertext authenticatedData:ad error:error];
375 /* Functions to load and save keys from the keychain (where we get to store actual key material!) */
376 - (BOOL)saveKeyMaterialToKeychain: (NSError * __autoreleasing *) error {
377 return [self.keycore saveKeyMaterialToKeychain:true error: error];
380 - (BOOL)saveKeyMaterialToKeychain: (bool)stashTLK error:(NSError * __autoreleasing *) error {
381 return [self.keycore saveKeyMaterialToKeychain:stashTLK error:error];
384 - (BOOL)loadKeyMaterialFromKeychain: (NSError * __autoreleasing *) error {
385 return [self.keycore loadKeyMaterialFromKeychain:error];
388 - (BOOL)deleteKeyMaterialFromKeychain: (NSError * __autoreleasing *) error {
389 return [self.keycore deleteKeyMaterialFromKeychain:error];
392 + (instancetype)keyFromKeychain: (NSString*) uuid
393 parentKeyUUID: (NSString*) parentKeyUUID
394 keyclass: (CKKSKeyClass*)keyclass
395 state: (CKKSProcessedState*) state
396 zoneID: (CKRecordZoneID*) zoneID
397 encodedCKRecord: (NSData*) encodedrecord
398 currentkey: (NSInteger) currentkey
399 error: (NSError * __autoreleasing *) error {
400 CKKSKey* key = [[CKKSKey alloc] initWithWrappedAESKey:nil
402 parentKeyUUID:parentKeyUUID
406 encodedCKRecord:encodedrecord
407 currentkey:currentkey];
409 if(![key loadKeyMaterialFromKeychain:error]) {
416 + (NSString* _Nullable)isItemKeyForKeychainView:(SecDbItemRef)item {
418 NSString* accessgroup = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrAccessGroup);
419 NSString* description = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrDescription);
420 NSString* server = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrServer);
422 if(accessgroup && description && server &&
423 ![accessgroup isEqual:[NSNull null]] &&
424 ![description isEqual:[NSNull null]] &&
425 ![server isEqual:[NSNull null]] &&
427 [accessgroup isEqualToString:@"com.apple.security.ckks"] &&
428 ([description isEqualToString: SecCKKSKeyClassTLK] ||
429 [description isEqualToString: [NSString stringWithFormat:@"%@-nonsync", SecCKKSKeyClassTLK]] ||
430 [description isEqualToString: [NSString stringWithFormat:@"%@-piggy", SecCKKSKeyClassTLK]] ||
431 [description isEqualToString: SecCKKSKeyClassA] ||
432 [description isEqualToString: SecCKKSKeyClassC])) {
434 // Certainly looks like us! Return the view name.
438 // Never heard of this item.
443 /* Database functions only return keys marked 'local', unless otherwise specified. */
445 + (instancetype) fromDatabase: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
446 return [self fromDatabaseWhere: @{@"UUID": uuid, @"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error: error];
449 + (instancetype) fromDatabaseAnyState: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
450 return [self fromDatabaseWhere: @{@"UUID": uuid, @"ckzone":zoneID.zoneName} error: error];
453 + (instancetype) tryFromDatabase: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
454 return [self tryFromDatabaseWhere: @{@"UUID": uuid, @"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error: error];
457 + (instancetype) tryFromDatabaseAnyState: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
458 return [self tryFromDatabaseWhere: @{@"UUID": uuid, @"ckzone":zoneID.zoneName} error: error];
461 + (NSArray<CKKSKey*>*)selfWrappedKeys:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
462 return [self allWhere: @{@"UUID": [CKKSSQLWhereObject op:@"=" string:@"parentKeyUUID"], @"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error:error];
465 + (instancetype _Nullable)currentKeyForClass:(CKKSKeyClass*)keyclass
466 zoneID:(CKRecordZoneID*)zoneID
467 error:(NSError *__autoreleasing*)error
469 // Load the CurrentKey record, and find the key for it
470 CKKSCurrentKeyPointer* ckp = [CKKSCurrentKeyPointer fromDatabase:keyclass zoneID:zoneID error:error];
474 return [self fromDatabase:ckp.currentKeyUUID zoneID:zoneID error:error];
477 + (NSArray<CKKSKey*>*) currentKeysForClass: (CKKSKeyClass*) keyclass state:(NSString*) state zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
478 return [self allWhere: @{@"keyclass": keyclass, @"currentkey": @"1", @"state": state ? state : SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error:error];
481 /* Returns all keys for a zone */
482 + (NSArray<CKKSKey*>*)allKeys: (CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
483 return [self allWhere: @{@"ckzone":zoneID.zoneName} error:error];
486 /* Returns all keys marked 'remote', i.e., downloaded from CloudKit */
487 + (NSArray<CKKSKey*>*)remoteKeys: (CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
488 return [self allWhere: @{@"state": SecCKKSProcessedStateRemote, @"ckzone":zoneID.zoneName} error:error];
491 /* Returns all keys marked 'local', i.e., processed in the past */
492 + (NSArray<CKKSKey*>*)localKeys: (CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
493 return [self allWhere: @{@"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error:error];
496 - (bool)saveToDatabaseAsOnlyCurrentKeyForClassAndState: (NSError * __autoreleasing *) error {
497 self.currentkey = true;
499 // Find other keys for our key class
500 NSArray<CKKSKey*>* keys = [CKKSKey currentKeysForClass: self.keyclass state: self.state zoneID:self.zoneID error:error];
505 for(CKKSKey* key in keys) {
506 key.currentkey = false;
507 if(![key saveToDatabase: error]) {
511 if(![self saveToDatabase: error]) {
518 #pragma mark - CKRecord handling
520 - (NSString*)CKRecordName
522 return self.keycore.uuid;
525 - (void) setFromCKRecord: (CKRecord*) record {
526 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
528 exceptionWithName:@"WrongCKRecordTypeException"
529 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordIntermediateKeyType]
533 [self setStoredCKRecord: record];
535 NSString* uuid = record.recordID.recordName;
536 NSString* parentKeyUUID = nil;
538 if(record[SecCKRecordParentKeyRefKey] != nil) {
539 parentKeyUUID = [record[SecCKRecordParentKeyRefKey] recordID].recordName;
542 parentKeyUUID = uuid;
545 NSString* keyclass = record[SecCKRecordKeyClassKey];
546 CKKSWrappedAESSIVKey* wrappedkey =
547 [[CKKSWrappedAESSIVKey alloc] initWithBase64:record[SecCKRecordWrappedKeyKey]];
549 self.keycore = [[CKKSKeychainBackedKey alloc] initWithWrappedAESKey:wrappedkey
551 parentKeyUUID:parentKeyUUID
552 keyclass:(CKKSKeyClass *)keyclass
553 zoneID:record.recordID.zoneID];
555 self.keyclass = record[SecCKRecordKeyClassKey];
556 self.wrappedkey = [[CKKSWrappedAESSIVKey alloc] initWithBase64: record[SecCKRecordWrappedKeyKey]];
558 self.state = SecCKKSProcessedStateRemote;
561 - (CKRecord*) updateCKRecord: (CKRecord*) record zoneID: (CKRecordZoneID*) zoneID {
562 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
564 exceptionWithName:@"WrongCKRecordTypeException"
565 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordIntermediateKeyType]
569 // The parent key must exist in CloudKit, or this record save will fail.
570 if([self.parentKeyUUID isEqual: self.uuid]) {
571 // We wrap ourself. No parent.
572 record[SecCKRecordParentKeyRefKey] = nil;
574 record[SecCKRecordParentKeyRefKey] = [[CKReference alloc] initWithRecordID: [[CKRecordID alloc] initWithRecordName: self.parentKeyUUID zoneID: zoneID] action: CKReferenceActionValidate];
577 [CKKSItem setOSVersionInRecord: record];
579 record[SecCKRecordKeyClassKey] = self.keyclass;
580 record[SecCKRecordWrappedKeyKey] = [self.wrappedkey base64WrappedKey];
585 - (bool)matchesCKRecord:(CKRecord*)record {
586 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
590 if(![record.recordID.recordName isEqualToString: self.uuid]) {
591 secinfo("ckkskey", "UUID does not match");
595 // For the parent key ref, ensure that if it's nil, we wrap ourself
596 if(record[SecCKRecordParentKeyRefKey] == nil) {
597 if(![self wrapsSelf]) {
598 secinfo("ckkskey", "wrapping key reference (self-wrapped) does not match");
603 if(![[[record[SecCKRecordParentKeyRefKey] recordID] recordName] isEqualToString: self.parentKeyUUID]) {
604 secinfo("ckkskey", "wrapping key reference (non-self-wrapped) does not match");
609 if(![record[SecCKRecordKeyClassKey] isEqual: self.keyclass]) {
610 secinfo("ckkskey", "key class does not match");
614 if(![record[SecCKRecordWrappedKeyKey] isEqual: [self.wrappedkey base64WrappedKey]]) {
615 secinfo("ckkskey", "wrapped key does not match");
623 #pragma mark - Utility
625 - (NSString*)description {
626 return [NSString stringWithFormat: @"<%@(%@): %@ (%@,%@:%d)>",
627 NSStringFromClass([self class]),
628 self.zoneID.zoneName,
635 #pragma mark - CKKSSQLDatabaseObject methods
637 + (NSString*) sqlTable {
641 + (NSArray<NSString*>*) sqlColumns {
642 return @[@"UUID", @"parentKeyUUID", @"ckzone", @"ckrecord", @"keyclass", @"state", @"currentkey", @"wrappedkey"];
645 - (NSDictionary<NSString*,NSString*>*) whereClauseToFindSelf {
646 return @{@"UUID": self.uuid, @"state": self.state, @"ckzone":self.zoneID.zoneName};
649 - (NSDictionary<NSString*,NSString*>*) sqlValues {
650 return @{@"UUID": self.uuid,
651 @"parentKeyUUID": self.parentKeyUUID ? self.parentKeyUUID : self.uuid, // if we don't have a parent, we wrap ourself.
652 @"ckzone": CKKSNilToNSNull(self.zoneID.zoneName),
653 @"ckrecord": CKKSNilToNSNull([self.encodedCKRecord base64EncodedStringWithOptions:0]),
654 @"keyclass": CKKSNilToNSNull(self.keyclass),
655 @"state": CKKSNilToNSNull(self.state),
656 @"wrappedkey": CKKSNilToNSNull([self.wrappedkey base64WrappedKey]),
657 @"currentkey": self.currentkey ? @"1" : @"0"};
660 + (instancetype)fromDatabaseRow:(NSDictionary<NSString*, CKKSSQLResult*>*)row {
661 return [[CKKSKey alloc] initWithWrappedAESKey:row[@"wrappedkey"].asString ? [[CKKSWrappedAESSIVKey alloc] initWithBase64: row[@"wrappedkey"].asString] : nil
662 uuid:row[@"UUID"].asString
663 parentKeyUUID:row[@"parentKeyUUID"].asString
664 keyclass:(CKKSKeyClass*)row[@"keyclass"].asString
665 state:(CKKSProcessedState*)row[@"state"].asString
666 zoneID:[[CKRecordZoneID alloc] initWithZoneName:row[@"ckzone"].asString ownerName:CKCurrentUserDefaultName]
667 encodedCKRecord:row[@"ckrecord"].asBase64DecodedData
668 currentkey:row[@"currentkey"].asNSInteger];
672 + (NSDictionary<NSString*,NSNumber*>*)countsByClass:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
673 NSMutableDictionary* results = [[NSMutableDictionary alloc] init];
675 [CKKSSQLDatabaseObject queryDatabaseTable: [[self class] sqlTable]
676 where: @{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)}
677 columns: @[@"keyclass", @"state", @"count(rowid)"]
678 groupBy: @[@"keyclass", @"state"]
681 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
682 results[[NSString stringWithFormat: @"%@-%@", row[@"state"].asString, row[@"keyclass"].asString]] =
683 row[@"count(rowid)"].asNSNumberInteger;
689 - (instancetype)copyWithZone:(NSZone *)zone {
690 CKKSKey *keyCopy = [super copyWithZone:zone];
691 keyCopy->_keycore = [_keycore copyWithZone:zone];
693 keyCopy->_state = _state;
694 keyCopy->_currentkey = _currentkey;
698 - (NSData*)serializeAsProtobuf: (NSError * __autoreleasing *) error {
699 if(![self ensureKeyLoaded:error]) {
702 CKKSSerializedKey* proto = [[CKKSSerializedKey alloc] init];
704 proto.uuid = self.uuid;
705 proto.zoneName = self.zoneID.zoneName;
706 proto.keyclass = self.keyclass;
707 proto.key = [NSData _newZeroingDataWithBytes:self.aessivkey->key length:self.aessivkey->size];
712 + (CKKSKey*)loadFromProtobuf:(NSData*)data error:(NSError* __autoreleasing *)error {
713 CKKSSerializedKey* key = [[CKKSSerializedKey alloc] initWithData: data];
714 if(key && key.uuid && key.zoneName && key.keyclass && key.key) {
715 return [[CKKSKey alloc] initSelfWrappedWithAESKey:[[CKKSAESSIVKey alloc] initWithBytes:(uint8_t*)key.key.bytes len:key.key.length]
717 keyclass:(CKKSKeyClass*)key.keyclass // TODO sanitize
718 state:SecCKKSProcessedStateRemote
719 zoneID:[[CKRecordZoneID alloc] initWithZoneName:key.zoneName
720 ownerName:CKCurrentUserDefaultName]
726 *error = [NSError errorWithDomain:CKKSErrorDomain code:CKKSProtobufFailure description:@"Data failed to parse as a CKKSSerializedKey"];