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/ckks/CloudKitCategories.h"
31 #include <securityd/SecItemSchema.h>
32 #include <Security/SecItem.h>
33 #include <Security/SecItemPriv.h>
35 #include <CloudKit/CloudKit.h>
36 #include <CloudKit/CloudKit_Private.h>
38 @implementation CKKSKey
40 - (instancetype)init {
45 - (instancetype) initSelfWrappedWithAESKey: (CKKSAESSIVKey*) aeskey
46 uuid: (NSString*) uuid
47 keyclass: (CKKSKeyClass*)keyclass
48 state: (CKKSProcessedState*) state
49 zoneID: (CKRecordZoneID*) zoneID
50 encodedCKRecord: (NSData*) encodedrecord
51 currentkey: (NSInteger) currentkey
53 if(self = [super initWithUUID: uuid
56 encodedCKRecord: encodedrecord
60 encver: currentCKKSItemEncryptionVersion]) {
62 _currentkey = !!currentkey;
66 self.ckRecordType = SecCKRecordIntermediateKeyType;
68 // Wrap the key with the key. Not particularly useful, but there you go.
70 [self wrapUnder: self error:&error];
72 secerror("CKKSKey: Couldn't self-wrap key: %@", error);
79 - (instancetype) initWrappedBy: (CKKSKey*) wrappingKey
80 AESKey: (CKKSAESSIVKey*) aeskey
81 uuid: (NSString*) uuid
82 keyclass: (CKKSKeyClass*)keyclass
83 state: (CKKSProcessedState*) state
84 zoneID: (CKRecordZoneID*) zoneID
85 encodedCKRecord: (NSData*) encodedrecord
86 currentkey: (NSInteger) currentkey
88 if(self = [super initWithUUID: uuid
89 parentKeyUUID: wrappingKey.uuid
91 encodedCKRecord: encodedrecord
96 currentCKKSItemEncryptionVersion]) {
98 _currentkey = !!currentkey;
102 self.ckRecordType = SecCKRecordIntermediateKeyType;
104 NSError* error = nil;
105 [self wrapUnder: wrappingKey error:&error];
107 secerror("CKKSKey: Couldn't wrap key with key: %@", error);
114 - (instancetype) initWithWrappedAESKey: (CKKSWrappedAESSIVKey*) wrappedaeskey
115 uuid: (NSString*) uuid
116 parentKeyUUID: (NSString*) parentKeyUUID
117 keyclass: (CKKSKeyClass*)keyclass
118 state: (CKKSProcessedState*) state
119 zoneID: (CKRecordZoneID*) zoneID
120 encodedCKRecord: (NSData*) encodedrecord
121 currentkey: (NSInteger) currentkey
123 if(self = [super initWithUUID:uuid
124 parentKeyUUID:parentKeyUUID
126 encodedCKRecord:encodedrecord
128 wrappedkey:wrappedaeskey
130 encver:currentCKKSItemEncryptionVersion]) {
131 _keyclass = keyclass;
132 _currentkey = !!currentkey;
136 self.ckRecordType = SecCKRecordIntermediateKeyType;
146 [self.aessivkey zeroKey];
150 return [self.uuid isEqual: self.parentKeyUUID];
153 - (bool)wrapUnder: (CKKSKey*) wrappingKey error: (NSError * __autoreleasing *) error {
154 self.wrappedkey = [wrappingKey wrapAESKey: self.aessivkey error:error];
155 if(self.wrappedkey == nil) {
156 secerror("CKKSKey: couldn't wrap key: %@", error ? *error : @"unknown error");
158 self.parentKeyUUID = wrappingKey.uuid;
160 return (self.wrappedkey != nil);
163 - (bool)unwrapSelfWithAESKey: (CKKSAESSIVKey*) unwrappingKey error: (NSError * __autoreleasing *) error {
164 _aessivkey = [unwrappingKey unwrapAESKey:self.wrappedkey error:error];
165 return (_aessivkey != nil);
168 + (instancetype) loadKeyWithUUID: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
169 CKKSKey* key = [CKKSKey fromDatabase: uuid zoneID:zoneID error:error];
171 // failed unwrapping means we can't return a key.
172 if(![key ensureKeyLoaded:error]) {
178 + (CKKSKey*) randomKeyWrappedByParent: (CKKSKey*) parentKey error: (NSError * __autoreleasing *) error {
179 return [self randomKeyWrappedByParent: parentKey keyclass:parentKey.keyclass error:error];
182 + (CKKSKey*) randomKeyWrappedByParent: (CKKSKey*) parentKey keyclass:(CKKSKeyClass*)keyclass error: (NSError * __autoreleasing *) error {
183 CKKSAESSIVKey* aessivkey = [CKKSAESSIVKey randomKey];
185 CKKSKey* key = [[CKKSKey alloc] initWrappedBy: parentKey
187 uuid:[[NSUUID UUID] UUIDString]
189 state:SecCKKSProcessedStateLocal
190 zoneID: parentKey.zoneID
196 + (instancetype)randomKeyWrappedBySelf: (CKRecordZoneID*) zoneID error: (NSError * __autoreleasing *) error {
197 CKKSAESSIVKey* aessivkey = [CKKSAESSIVKey randomKey];
198 NSString* uuid = [[NSUUID UUID] UUIDString];
200 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: aessivkey
202 keyclass:SecCKKSKeyClassTLK
203 state:SecCKKSProcessedStateLocal
211 - (CKKSKey*)topKeyInAnyState: (NSError * __autoreleasing *) error {
212 // Recursively find the top-level key in the hierarchy, preferring 'remote' keys.
213 if([self wrapsSelf]) {
217 CKKSKey* remoteParent = [CKKSKey tryFromDatabaseWhere: @{@"UUID": self.parentKeyUUID, @"state": SecCKKSProcessedStateRemote} error: error];
219 return [remoteParent topKeyInAnyState: error];
222 // No remote parent. Fall back to anything.
223 CKKSKey* parent = [CKKSKey fromDatabaseWhere: @{@"UUID": self.parentKeyUUID} error: error];
225 return [parent topKeyInAnyState: error];
228 // No good. Error is already filled.
232 - (CKKSAESSIVKey*)ensureKeyLoaded: (NSError * __autoreleasing *) error {
234 return self.aessivkey;
237 // Attempt to load this key from the keychain
238 if([self loadKeyMaterialFromKeychain:error]) {
239 return self.aessivkey;
246 - (CKKSAESSIVKey*)unwrapViaKeyHierarchy: (NSError * __autoreleasing *) error {
248 return self.aessivkey;
251 NSError* localerror = nil;
253 // Attempt to load this key from the keychain
254 if([self loadKeyMaterialFromKeychain:&localerror]) {
256 return self.aessivkey;
259 // First, check if we're a TLK.
260 if([self.keyclass isEqual: SecCKKSKeyClassTLK]) {
261 // 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.
262 if(!self.parentKeyUUID || [self.parentKeyUUID isEqualToString: self.uuid]) {
270 // Recursively unwrap our parent.
271 CKKSKey* parent = [CKKSKey fromDatabaseAnyState:self.parentKeyUUID zoneID:self.zoneID error:error];
273 // TODO: do we need loop detection here?
274 if(![parent unwrapViaKeyHierarchy: error]) {
278 _aessivkey = [parent unwrapAESKey:self.wrappedkey error:error];
279 return self.aessivkey;
282 - (bool)trySelfWrappedKeyCandidate:(CKKSAESSIVKey*)candidate error:(NSError * __autoreleasing *) error {
283 if(![self wrapsSelf]) {
285 *error = [NSError errorWithDomain:CKKSErrorDomain code:CKKSKeyNotSelfWrapped userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat: @"%@ is not self-wrapped", self]}];
290 CKKSAESSIVKey* unwrapped = [candidate unwrapAESKey:self.wrappedkey error:error];
291 if(unwrapped && [unwrapped isEqual: candidate]) {
292 _aessivkey = unwrapped;
299 - (CKKSWrappedAESSIVKey*)wrapAESKey: (CKKSAESSIVKey*) keyToWrap error: (NSError * __autoreleasing *) error {
300 CKKSAESSIVKey* key = [self ensureKeyLoaded: error];
301 CKKSWrappedAESSIVKey* wrappedkey = [key wrapAESKey: keyToWrap error:error];
305 - (CKKSAESSIVKey*)unwrapAESKey: (CKKSWrappedAESSIVKey*) keyToUnwrap error: (NSError * __autoreleasing *) error {
306 CKKSAESSIVKey* key = [self ensureKeyLoaded: error];
307 CKKSAESSIVKey* unwrappedkey = [key unwrapAESKey: keyToUnwrap error:error];
311 - (NSData*)encryptData: (NSData*) plaintext authenticatedData: (NSDictionary<NSString*, NSData*>*) ad error: (NSError * __autoreleasing *) error {
312 CKKSAESSIVKey* key = [self ensureKeyLoaded: error];
313 NSData* data = [key encryptData: plaintext authenticatedData:ad error:error];
317 - (NSData*)decryptData: (NSData*) ciphertext authenticatedData: (NSDictionary<NSString*, NSData*>*) ad error: (NSError * __autoreleasing *) error {
318 CKKSAESSIVKey* key = [self ensureKeyLoaded: error];
319 NSData* data = [key decryptData: ciphertext authenticatedData:ad error:error];
323 /* Functions to load and save keys from the keychain (where we get to store actual key material!) */
324 - (bool)saveKeyMaterialToKeychain: (NSError * __autoreleasing *) error {
325 return [self saveKeyMaterialToKeychain: true error: error];
328 - (bool)saveKeyMaterialToKeychain: (bool)stashTLK error:(NSError * __autoreleasing *) error {
329 return [CKKSKey saveKeyMaterialToKeychain:self stashTLK:stashTLK error:error];
332 +(bool)saveKeyMaterialToKeychain:(CKKSKey*)key stashTLK:(bool)stashTLK error:(NSError * __autoreleasing *) error {
334 // Note that we only store the key class, view, UUID, parentKeyUUID, and key material in the keychain
335 // Any other metadata must be stored elsewhere and filled in at load time.
337 if(![key ensureKeyLoaded:error]) {
338 // No key material, nothing to save to keychain.
342 // iOS keychains can't store symmetric keys, so we're reduced to storing this key as a password
343 NSData* keydata = [[[NSData alloc] initWithBytes:key.aessivkey->key length:key.aessivkey->size] base64EncodedDataWithOptions:0];
344 NSMutableDictionary* query = [@{
345 (id)kSecClass : (id)kSecClassInternetPassword,
346 (id)kSecAttrAccessible: (id)kSecAttrAccessibleWhenUnlocked,
347 (id)kSecAttrNoLegacy : @YES,
348 (id)kSecAttrAccessGroup: @"com.apple.security.ckks",
349 (id)kSecAttrDescription: key.keyclass,
350 (id)kSecAttrServer: key.zoneID.zoneName,
351 (id)kSecAttrAccount: key.uuid,
352 (id)kSecAttrPath: key.parentKeyUUID,
353 (id)kSecAttrIsInvisible: @YES,
354 (id)kSecValueData : keydata,
357 // Only TLKs are synchronizable. Other keyclasses must synchronize via key hierarchy.
358 if([key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
359 // Use PCS-MasterKey view so they'll be initial-synced under SOS.
360 query[(id)kSecAttrSyncViewHint] = (id)kSecAttrViewHintPCSMasterKey;
361 query[(id)kSecAttrSynchronizable] = (id)kCFBooleanTrue;
364 // Class C keys are accessible after first unlock; TLKs and Class A keys are accessible only when unlocked
365 if([key.keyclass isEqualToString: SecCKKSKeyClassC]) {
366 query[(id)kSecAttrAccessible] = (id)kSecAttrAccessibleAfterFirstUnlock;
368 query[(id)kSecAttrAccessible] = (id)kSecAttrAccessibleWhenUnlocked;
371 OSStatus status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
373 if(status == errSecDuplicateItem) {
374 // Sure, okay, fine, we'll update.
376 NSMutableDictionary* update = [@{
377 (id)kSecValueData: keydata,
378 (id)kSecAttrPath: key.parentKeyUUID,
380 query[(id)kSecValueData] = nil;
381 query[(id)kSecAttrPath] = nil;
383 // Udpate the view-hint, too
384 if([key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
385 update[(id)kSecAttrSyncViewHint] = (id)kSecAttrViewHintPCSMasterKey;
386 query[(id)kSecAttrSyncViewHint] = nil;
389 status = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
392 if(status && error) {
393 *error = [NSError errorWithDomain:@"securityd"
395 userInfo:@{NSLocalizedDescriptionKey:
396 [NSString stringWithFormat:@"Couldn't save %@ to keychain: %d", self, (int)status]}];
399 // TLKs are synchronizable. Stash them nonsyncably nearby.
400 // Don't report errors here.
401 if(stashTLK && [key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
403 (id)kSecClass : (id)kSecClassInternetPassword,
404 (id)kSecAttrAccessible: (id)kSecAttrAccessibleWhenUnlocked,
405 (id)kSecAttrNoLegacy : @YES,
406 (id)kSecAttrAccessGroup: @"com.apple.security.ckks",
407 (id)kSecAttrDescription: [key.keyclass stringByAppendingString: @"-nonsync"],
408 (id)kSecAttrServer: key.zoneID.zoneName,
409 (id)kSecAttrAccount: key.uuid,
410 (id)kSecAttrPath: key.parentKeyUUID,
411 (id)kSecAttrIsInvisible: @YES,
412 (id)kSecValueData : keydata,
414 query[(id)kSecAttrSynchronizable] = (id)kCFBooleanFalse;
416 OSStatus stashstatus = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
417 if(stashstatus != errSecSuccess) {
418 if(stashstatus == errSecDuplicateItem) {
419 // Sure, okay, fine, we'll update.
421 NSDictionary* update = @{
422 (id)kSecValueData: keydata,
423 (id)kSecAttrPath: key.parentKeyUUID,
425 query[(id)kSecValueData] = nil;
426 query[(id)kSecAttrPath] = nil;
428 stashstatus = SecItemUpdate((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef)update);
431 if(stashstatus != errSecSuccess) {
432 secerror("ckkskey: Couldn't stash %@ to keychain: %d", self, (int)stashstatus);
440 + (NSData*)loadKeyMaterialFromKeychain:(CKKSKey*)key resave:(bool*)resavePtr error:(NSError* __autoreleasing *)error {
441 NSMutableDictionary* query = [@{
442 (id)kSecClass : (id)kSecClassInternetPassword,
443 (id)kSecAttrNoLegacy : @YES,
444 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
445 (id)kSecAttrDescription: key.keyclass,
446 (id)kSecAttrAccount: key.uuid,
447 (id)kSecAttrServer: key.zoneID.zoneName,
448 (id)kSecReturnAttributes: @YES,
449 (id)kSecReturnData: @YES,
452 // Synchronizable items are only found if you request synchronizable items. Only TLKs are synchronizable.
453 if([key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
454 query[(id)kSecAttrSynchronizable] = (id)kCFBooleanTrue;
457 CFTypeRef result = NULL;
458 OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, &result);
460 if(status == errSecItemNotFound) {
461 CFReleaseNull(result);
462 //didn't find a regular tlk? how about a piggy?
463 if([key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
465 (id)kSecClass : (id)kSecClassInternetPassword,
466 (id)kSecAttrNoLegacy : @YES,
467 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
468 (id)kSecAttrDescription: @"tlk-piggy",
469 (id)kSecAttrSynchronizable : (id)kSecAttrSynchronizableAny,
470 (id)kSecAttrAccount: [NSString stringWithFormat: @"%@-piggy", key.uuid],
471 (id)kSecAttrServer: key.zoneID.zoneName,
472 (id)kSecReturnAttributes: @YES,
473 (id)kSecReturnData: @YES,
474 (id)kSecMatchLimit: (id)kSecMatchLimitOne,
476 status = SecItemCopyMatching((__bridge CFDictionaryRef) query, &result);
477 if(status == errSecSuccess){
478 secnotice("ckkskey", "loaded a piggy TLK (%@)", key.uuid);
486 if(status == errSecItemNotFound && [key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
487 CFReleaseNull(result);
489 // Try to look for the non-syncable stashed tlk and resurrect it.
491 (id)kSecClass : (id)kSecClassInternetPassword,
492 (id)kSecAttrNoLegacy : @YES,
493 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
494 (id)kSecAttrDescription: [key.keyclass stringByAppendingString: @"-nonsync"],
495 (id)kSecAttrServer: key.zoneID.zoneName,
496 (id)kSecAttrAccount: key.uuid,
497 (id)kSecReturnAttributes: @YES,
498 (id)kSecReturnData: @YES,
499 (id)kSecAttrSynchronizable: @NO,
502 status = SecItemCopyMatching((__bridge CFDictionaryRef) query, &result);
503 if(status == errSecSuccess) {
504 secnotice("ckkskey", "loaded a stashed TLK (%@)", key.uuid);
512 if(status){ //still can't find it!
514 *error = [NSError errorWithDomain:@"securityd"
516 userInfo:@{NSLocalizedDescriptionKey:
517 [NSString stringWithFormat:@"Couldn't load %@ from keychain: %d", self, (int)status]}];
522 // Determine if we should fix up any attributes on this item...
523 NSDictionary* resultDict = CFBridgingRelease(result);
525 // We created some TLKs with no ViewHint. Fix it.
526 if([key.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
527 NSString* viewHint = resultDict[(id)kSecAttrSyncViewHint];
529 ckksnotice("ckkskey", key.zoneID, "Fixing up non-viewhinted TLK %@", self);
530 query[(id)kSecReturnAttributes] = nil;
531 query[(id)kSecReturnData] = nil;
533 NSDictionary* update = @{(id)kSecAttrSyncViewHint: (id)kSecAttrViewHintPCSMasterKey};
535 status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)update);
537 // Don't report error upwards; this is an optimization fixup.
538 secerror("ckkskey: Couldn't update viewhint on existing TLK %@", self);
543 // Okay, back to the real purpose of this function: extract the CFData currently in the results dictionary
544 NSData* b64keymaterial = resultDict[(id)kSecValueData];
545 NSData* keymaterial = [[NSData alloc] initWithBase64EncodedData:b64keymaterial options:0];
549 - (bool)loadKeyMaterialFromKeychain: (NSError * __autoreleasing *) error {
551 NSData* keymaterial = [CKKSKey loadKeyMaterialFromKeychain:self resave:&resave error:error];
556 CKKSAESSIVKey* key = [[CKKSAESSIVKey alloc] initWithBytes: (uint8_t*) keymaterial.bytes len:keymaterial.length];
560 secnotice("ckkskey", "Resaving %@ as per request", self);
561 NSError* resaveError = nil;
562 [self saveKeyMaterialToKeychain:&resaveError];
564 secnotice("ckkskey", "Resaving %@ failed: %@", self, resaveError);
568 return !!(self.aessivkey);
571 - (bool)deleteKeyMaterialFromKeychain: (NSError * __autoreleasing *) error {
573 NSMutableDictionary* query = [@{
574 (id)kSecClass : (id)kSecClassInternetPassword,
575 (id)kSecAttrNoLegacy : @YES,
576 (id)kSecAttrAccessGroup : @"com.apple.security.ckks",
577 (id)kSecAttrDescription: self.keyclass,
578 (id)kSecAttrAccount: self.uuid,
579 (id)kSecAttrServer: self.zoneID.zoneName,
580 (id)kSecReturnData: @YES,
583 // Synchronizable items are only found if you request synchronizable items. Only TLKs are synchronizable.
584 if([self.keyclass isEqualToString: SecCKKSKeyClassTLK]) {
585 query[(id)kSecAttrSynchronizable] = (id)kCFBooleanTrue;
588 OSStatus status = SecItemDelete((__bridge CFDictionaryRef) query);
592 *error = [NSError errorWithDomain:@"securityd"
594 userInfo:@{NSLocalizedDescriptionKey:
595 [NSString stringWithFormat:@"Couldn't delete %@ from keychain: %d", self, (int)status]}];
602 + (instancetype)keyFromKeychain: (NSString*) uuid
603 parentKeyUUID: (NSString*) parentKeyUUID
604 keyclass: (CKKSKeyClass*)keyclass
605 state: (CKKSProcessedState*) state
606 zoneID: (CKRecordZoneID*) zoneID
607 encodedCKRecord: (NSData*) encodedrecord
608 currentkey: (NSInteger) currentkey
609 error: (NSError * __autoreleasing *) error {
610 CKKSKey* key = [[CKKSKey alloc] initWithWrappedAESKey:nil
612 parentKeyUUID:parentKeyUUID
616 encodedCKRecord:encodedrecord
617 currentkey:currentkey];
619 if(![key loadKeyMaterialFromKeychain:error]) {
626 + (NSString*)isItemKeyForKeychainView: (SecDbItemRef) item {
628 NSString* accessgroup = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrAccessGroup);
629 NSString* description = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrDescription);
630 NSString* server = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrServer);
632 if(accessgroup && description && server &&
633 ![accessgroup isEqual:[NSNull null]] &&
634 ![description isEqual:[NSNull null]] &&
635 ![server isEqual:[NSNull null]] &&
637 [accessgroup isEqualToString:@"com.apple.security.ckks"] &&
638 ([description isEqualToString: SecCKKSKeyClassTLK] ||
639 [description isEqualToString: [NSString stringWithFormat:@"%@-nonsync", SecCKKSKeyClassTLK]] ||
640 [description isEqualToString: [NSString stringWithFormat:@"%@-piggy", SecCKKSKeyClassTLK]] ||
641 [description isEqualToString: SecCKKSKeyClassA] ||
642 [description isEqualToString: SecCKKSKeyClassC])) {
644 // Certainly looks like us! Return the view name.
648 // Never heard of this item.
653 /* Database functions only return keys marked 'local', unless otherwise specified. */
655 + (instancetype) fromDatabase: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
656 return [self fromDatabaseWhere: @{@"UUID": uuid, @"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error: error];
659 + (instancetype) fromDatabaseAnyState: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
660 return [self fromDatabaseWhere: @{@"UUID": uuid, @"ckzone":zoneID.zoneName} error: error];
663 + (instancetype) tryFromDatabase: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
664 return [self tryFromDatabaseWhere: @{@"UUID": uuid, @"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error: error];
667 + (instancetype) tryFromDatabaseAnyState: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
668 return [self tryFromDatabaseWhere: @{@"UUID": uuid, @"ckzone":zoneID.zoneName} error: error];
671 + (NSArray<CKKSKey*>*)selfWrappedKeys:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
672 return [self allWhere: @{@"UUID": [CKKSSQLWhereObject op:@"=" string:@"parentKeyUUID"], @"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error:error];
675 + (instancetype) currentKeyForClass: (CKKSKeyClass*) keyclass zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
676 // Load the CurrentKey record, and find the key for it
677 CKKSCurrentKeyPointer* ckp = [CKKSCurrentKeyPointer fromDatabase:keyclass zoneID:zoneID error:error];
681 return [self fromDatabase:ckp.currentKeyUUID zoneID:zoneID error:error];
684 + (NSArray<CKKSKey*>*) currentKeysForClass: (CKKSKeyClass*) keyclass state:(NSString*) state zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
685 return [self allWhere: @{@"keyclass": keyclass, @"currentkey": @"1", @"state": state ? state : SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error:error];
688 /* Returns all keys for a zone */
689 + (NSArray<CKKSKey*>*)allKeys: (CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
690 return [self allWhere: @{@"ckzone":zoneID.zoneName} error:error];
693 /* Returns all keys marked 'remote', i.e., downloaded from CloudKit */
694 + (NSArray<CKKSKey*>*)remoteKeys: (CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
695 return [self allWhere: @{@"state": SecCKKSProcessedStateRemote, @"ckzone":zoneID.zoneName} error:error];
698 /* Returns all keys marked 'local', i.e., processed in the past */
699 + (NSArray<CKKSKey*>*)localKeys: (CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
700 return [self allWhere: @{@"state": SecCKKSProcessedStateLocal, @"ckzone":zoneID.zoneName} error:error];
703 - (bool)saveToDatabaseAsOnlyCurrentKeyForClassAndState: (NSError * __autoreleasing *) error {
704 self.currentkey = true;
706 // Find other keys for our key class
707 NSArray<CKKSKey*>* keys = [CKKSKey currentKeysForClass: self.keyclass state: self.state zoneID:self.zoneID error:error];
712 for(CKKSKey* key in keys) {
713 key.currentkey = false;
714 if(![key saveToDatabase: error]) {
718 if(![self saveToDatabase: error]) {
725 #pragma mark - CKRecord handling
727 - (void) setFromCKRecord: (CKRecord*) record {
728 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
730 exceptionWithName:@"WrongCKRecordTypeException"
731 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordIntermediateKeyType]
735 [self setStoredCKRecord: record];
737 self.uuid = [[record recordID] recordName];
738 if(record[SecCKRecordParentKeyRefKey] != nil) {
739 self.parentKeyUUID = [record[SecCKRecordParentKeyRefKey] recordID].recordName;
742 self.parentKeyUUID = self.uuid;
745 self.keyclass = record[SecCKRecordKeyClassKey];
746 self.wrappedkey = [[CKKSWrappedAESSIVKey alloc] initWithBase64: record[SecCKRecordWrappedKeyKey]];
749 - (CKRecord*) updateCKRecord: (CKRecord*) record zoneID: (CKRecordZoneID*) zoneID {
750 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
752 exceptionWithName:@"WrongCKRecordTypeException"
753 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordIntermediateKeyType]
757 // The parent key must exist in CloudKit, or this record save will fail.
758 if([self.parentKeyUUID isEqual: self.uuid]) {
759 // We wrap ourself. No parent.
760 record[SecCKRecordParentKeyRefKey] = nil;
762 record[SecCKRecordParentKeyRefKey] = [[CKReference alloc] initWithRecordID: [[CKRecordID alloc] initWithRecordName: self.parentKeyUUID zoneID: zoneID] action: CKReferenceActionValidate];
765 [CKKSItem setOSVersionInRecord: record];
767 record[SecCKRecordKeyClassKey] = self.keyclass;
768 record[SecCKRecordWrappedKeyKey] = [self.wrappedkey base64WrappedKey];
773 #pragma mark - Utility
775 - (NSString*)description {
776 return [NSString stringWithFormat: @"<%@(%@): %@ (%@,%@:%d)>",
777 NSStringFromClass([self class]),
778 self.zoneID.zoneName,
785 #pragma mark - CKKSSQLDatabaseObject methods
787 + (NSString*) sqlTable {
791 + (NSArray<NSString*>*) sqlColumns {
792 return @[@"UUID", @"parentKeyUUID", @"ckzone", @"ckrecord", @"keyclass", @"state", @"currentkey", @"wrappedkey"];
795 - (NSDictionary<NSString*,NSString*>*) whereClauseToFindSelf {
796 return @{@"UUID": self.uuid, @"state": self.state, @"ckzone":self.zoneID.zoneName};
799 - (NSDictionary<NSString*,NSString*>*) sqlValues {
800 return @{@"UUID": self.uuid,
801 @"parentKeyUUID": self.parentKeyUUID ? self.parentKeyUUID : self.uuid, // if we don't have a parent, we wrap ourself.
802 @"ckzone": CKKSNilToNSNull(self.zoneID.zoneName),
803 @"ckrecord": CKKSNilToNSNull([self.encodedCKRecord base64EncodedStringWithOptions:0]),
804 @"keyclass": CKKSNilToNSNull(self.keyclass),
805 @"state": CKKSNilToNSNull(self.state),
806 @"wrappedkey": CKKSNilToNSNull([self.wrappedkey base64WrappedKey]),
807 @"currentkey": self.currentkey ? @"1" : @"0"};
810 + (instancetype) fromDatabaseRow: (NSDictionary*) row {
811 return [[CKKSKey alloc] initWithWrappedAESKey: row[@"wrappedkey"] ? [[CKKSWrappedAESSIVKey alloc] initWithBase64: row[@"wrappedkey"]] : nil
813 parentKeyUUID: row[@"parentKeyUUID"]
814 keyclass: row[@"keyclass"]
816 zoneID: [[CKRecordZoneID alloc] initWithZoneName: row[@"ckzone"] ownerName:CKCurrentUserDefaultName]
817 encodedCKRecord: [[NSData alloc] initWithBase64EncodedString: row[@"ckrecord"] options:0]
818 currentkey: [row[@"currentkey"] integerValue]];
822 + (NSDictionary<NSString*,NSNumber*>*)countsByClass:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
823 NSMutableDictionary* results = [[NSMutableDictionary alloc] init];
825 [CKKSSQLDatabaseObject queryDatabaseTable: [[self class] sqlTable]
826 where: @{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)}
827 columns: @[@"keyclass", @"state", @"count(rowid)"]
828 groupBy: @[@"keyclass", @"state"]
831 processRow: ^(NSDictionary* row) {
832 results[[NSString stringWithFormat: @"%@-%@", row[@"state"], row[@"keyclass"]]] =
833 [NSNumber numberWithInteger: [row[@"count(rowid)"] integerValue]];
839 - (instancetype)copyWithZone:(NSZone *)zone {
840 CKKSKey *keyCopy = [super copyWithZone:zone];
841 keyCopy->_aessivkey = _aessivkey;
842 keyCopy->_state = _state;
843 keyCopy->_keyclass = _keyclass;
844 keyCopy->_currentkey = _currentkey;
848 - (NSData*)serializeAsProtobuf: (NSError * __autoreleasing *) error {
849 if(![self ensureKeyLoaded:error]) {
852 CKKSSerializedKey* proto = [[CKKSSerializedKey alloc] init];
854 proto.uuid = self.uuid;
855 proto.zoneName = self.zoneID.zoneName;
856 proto.keyclass = self.keyclass;
857 proto.key = [[NSData alloc] initWithBytes:self.aessivkey->key length:self.aessivkey->size];
862 + (CKKSKey*)loadFromProtobuf:(NSData*)data error:(NSError* __autoreleasing *)error {
863 CKKSSerializedKey* key = [[CKKSSerializedKey alloc] initWithData: data];
864 if(key && key.uuid && key.zoneName && key.keyclass && key.key) {
865 return [[CKKSKey alloc] initSelfWrappedWithAESKey:[[CKKSAESSIVKey alloc] initWithBytes:(uint8_t*)key.key.bytes len:key.key.length]
867 keyclass:(CKKSKeyClass*)key.keyclass // TODO sanitize
868 state:SecCKKSProcessedStateRemote
869 zoneID:[[CKRecordZoneID alloc] initWithZoneName:key.zoneName
870 ownerName:CKCurrentUserDefaultName]
876 *error = [NSError errorWithDomain:CKKSErrorDomain code:CKKSProtobufFailure description:@"Data failed to parse as a CKKSSerializedKey"];