]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSKey.m
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / ckks / CKKSKey.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 "CKKSViewManager.h"
27 #import "CKKSKeychainView.h"
28 #import "CKKSCurrentKeyPointer.h"
29 #import "CKKSKey.h"
30 #import "keychain/categories/NSError+UsefulConstructors.h"
31 #include <securityd/SecItemSchema.h>
32 #include <Security/SecItem.h>
33 #include <Security/SecItemPriv.h>
34 #include "OSX/sec/Security/SecItemShim.h"
35
36 #include <CloudKit/CloudKit.h>
37 #include <CloudKit/CloudKit_Private.h>
38
39 #import <Foundation/NSData_Private.h>
40
41 @implementation CKKSKey
42
43 - (instancetype)init {
44 self = [super init];
45 return self;
46 }
47
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
55 {
56 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
57 encodedCKRecord:encodedrecord
58 zoneID:zoneID])) {
59
60 _keycore = [[CKKSKeychainBackedKey alloc] initSelfWrappedWithAESKey:aeskey
61 uuid:uuid
62 keyclass:keyclass
63 zoneID:zoneID];
64 if(!_keycore) {
65 return nil;
66 }
67
68 _currentkey = !!currentkey;
69 _state = state;
70 }
71 return self;
72 }
73
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
82 {
83 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
84 encodedCKRecord:encodedrecord
85 zoneID:zoneID])) {
86 _keycore = [[CKKSKeychainBackedKey alloc] initWrappedBy:wrappingKey.keycore
87 AESKey:aeskey
88 uuid:uuid
89 keyclass:keyclass
90 zoneID:zoneID];
91 if(!_keycore) {
92 return nil;
93 }
94
95 _currentkey = !!currentkey;
96 _state = state;
97 }
98 return self;
99 }
100
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
109 {
110 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
111 encodedCKRecord:encodedrecord
112 zoneID:zoneID])) {
113
114 _keycore = [[CKKSKeychainBackedKey alloc] initWithWrappedAESKey:wrappedaeskey
115 uuid:uuid
116 parentKeyUUID:parentKeyUUID
117 keyclass:keyclass
118 zoneID:zoneID];
119
120 _currentkey = !!currentkey;
121 _state = state;
122 }
123 return self;
124 }
125
126 - (instancetype)initWithKeyCore:(CKKSKeychainBackedKey*)core
127 {
128 if((self = [super initWithCKRecordType:SecCKRecordIntermediateKeyType
129 encodedCKRecord:nil
130 zoneID:core.zoneID])) {
131 _keycore = core;
132 _currentkey = false;
133 _state = SecCKKSProcessedStateRemote;
134 }
135 return self;
136 }
137
138 - (void)dealloc {
139 }
140
141 - (BOOL)isEqual:(id)object {
142 if(![object isKindOfClass:[CKKSKey class]]) {
143 return NO;
144 }
145
146 CKKSKey* obj = (CKKSKey*)object;
147
148 // Equality ignores state, currentkey, and CK record differences. Be careful...
149 return [self.keycore isEqual:obj.keycore] ? YES : NO;
150 }
151
152 // These used to be properties on CKKSKey, but are now properties on the actual key inside
153 - (NSString*)uuid
154 {
155 return self.keycore.uuid;
156 }
157
158 - (void)setUuid:(NSString *)uuid
159 {
160 self.keycore.uuid = uuid;
161 }
162
163 - (NSString*)parentKeyUUID
164 {
165 return self.keycore.parentKeyUUID;
166 }
167
168 - (void)setParentKeyUUID:(NSString *)parentKeyUUID
169 {
170 self.keycore.parentKeyUUID = parentKeyUUID;
171 }
172
173 - (CKKSKeyClass*)keyclass
174 {
175 return self.keycore.keyclass;
176 }
177
178 - (void)setKeyclass:(CKKSKeyClass*)keyclass
179 {
180 self.keycore.keyclass = keyclass;
181 }
182
183 - (CKKSWrappedAESSIVKey*)wrappedkey
184 {
185 return self.keycore.wrappedkey;
186 }
187
188 - (void)setWrappedkey:(CKKSWrappedAESSIVKey*)wrappedkey
189 {
190 self.keycore.wrappedkey = wrappedkey;
191 }
192
193 - (CKKSAESSIVKey*)aessivkey
194 {
195 return self.keycore.aessivkey;
196 }
197
198 - (bool)wrapsSelf {
199 return [self.keycore wrapsSelf];
200 }
201
202 - (bool)wrapUnder: (CKKSKey*) wrappingKey error: (NSError * __autoreleasing *) error {
203 return [self.keycore wrapUnder:wrappingKey.keycore error:error];
204 }
205
206 + (instancetype) loadKeyWithUUID: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
207 CKKSKey* key = [CKKSKey fromDatabase: uuid zoneID:zoneID error:error];
208
209 // failed unwrapping means we can't return a key.
210 if(![key ensureKeyLoaded:error]) {
211 return nil;
212 }
213 return key;
214 }
215
216 + (CKKSKey*) randomKeyWrappedByParent: (CKKSKey*) parentKey error: (NSError * __autoreleasing *) error {
217 return [self randomKeyWrappedByParent: parentKey keyclass:parentKey.keyclass error:error];
218 }
219
220 + (CKKSKey*) randomKeyWrappedByParent: (CKKSKey*) parentKey keyclass:(CKKSKeyClass*)keyclass error: (NSError * __autoreleasing *) error {
221 CKKSAESSIVKey* aessivkey = [CKKSAESSIVKey randomKey:error];
222 if(aessivkey == nil) {
223 return nil;
224 }
225
226 CKKSKey* key = [[CKKSKey alloc] initWrappedBy: parentKey
227 AESKey: aessivkey
228 uuid:[[NSUUID UUID] UUIDString]
229 keyclass:keyclass
230 state:SecCKKSProcessedStateLocal
231 zoneID: parentKey.zoneID
232 encodedCKRecord: nil
233 currentkey: false];
234 return key;
235 }
236
237 + (instancetype)randomKeyWrappedBySelf: (CKRecordZoneID*) zoneID error: (NSError * __autoreleasing *) error {
238 CKKSAESSIVKey* aessivkey = [CKKSAESSIVKey randomKey:error];
239 if(aessivkey == nil) {
240 return nil;
241 }
242
243 NSString* uuid = [[NSUUID UUID] UUIDString];
244
245 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: aessivkey
246 uuid:uuid
247 keyclass:SecCKKSKeyClassTLK
248 state:SecCKKSProcessedStateLocal
249 zoneID: zoneID
250 encodedCKRecord: nil
251 currentkey: false];
252 return key;
253
254 }
255
256 - (CKKSKey*)topKeyInAnyState: (NSError * __autoreleasing *) error {
257 NSMutableSet<NSString*>* seenUUID = [[NSMutableSet alloc] init];
258 CKKSKey* key = self;
259
260 // Find the top-level key in the hierarchy.
261 while (key) {
262 if([key wrapsSelf]) {
263 return key;
264 }
265
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"];
271 return nil;
272 }
273
274 [seenUUID addObject:key.uuid];
275
276 // Prefer 'remote' parents.
277 CKKSKey* parent = [CKKSKey tryFromDatabaseWhere: @{@"UUID": key.parentKeyUUID, @"state": SecCKKSProcessedStateRemote} error: error];
278
279 // No remote parent. Fall back to anything.
280 if(parent == nil) {
281 parent = [CKKSKey fromDatabaseWhere: @{@"UUID": key.parentKeyUUID} error: error];
282 }
283
284 key = parent;
285 }
286
287 // Couldn't get the parent. Error is already filled.
288 return nil;
289 }
290
291 - (CKKSAESSIVKey*)ensureKeyLoaded: (NSError * __autoreleasing *) error {
292 NSError* keychainError = nil;
293
294 CKKSAESSIVKey* sivkey = [self.keycore ensureKeyLoaded:&keychainError];
295 if(sivkey) {
296 return sivkey;
297 }
298
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);
306 }
307
308 return self.aessivkey;
309 }
310
311 // Pick an error to report
312 if(error) {
313 *error = keyHierarchyError ? keyHierarchyError : keychainError;
314 }
315
316 return nil;
317 }
318
319 - (CKKSAESSIVKey*)unwrapViaKeyHierarchy: (NSError * __autoreleasing *) error {
320 if(self.aessivkey) {
321 return self.aessivkey;
322 }
323
324 NSError* localerror = nil;
325
326 // Attempt to load this key from the keychain
327 if([self.keycore loadKeyMaterialFromKeychain:&localerror]) {
328 // Rad. Success!
329 return self.aessivkey;
330 }
331
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]) {
336 if(error) {
337 *error = localerror;
338 }
339 return nil;
340 }
341 }
342
343 // Recursively unwrap our parent.
344 CKKSKey* parent = [CKKSKey fromDatabaseAnyState:self.parentKeyUUID zoneID:self.zoneID error:error];
345
346 // TODO: do we need loop detection here?
347 if(![parent unwrapViaKeyHierarchy: error]) {
348 return nil;
349 }
350
351 self.keycore.aessivkey = [parent unwrapAESKey:self.wrappedkey error:error];
352 return self.aessivkey;
353 }
354
355 - (bool)trySelfWrappedKeyCandidate:(CKKSAESSIVKey*)candidate error:(NSError * __autoreleasing *) error {
356 return [self.keycore trySelfWrappedKeyCandidate:candidate error:error];
357 }
358
359 - (CKKSWrappedAESSIVKey*)wrapAESKey: (CKKSAESSIVKey*) keyToWrap error: (NSError * __autoreleasing *) error {
360 return [self.keycore wrapAESKey:keyToWrap error:error];
361 }
362
363 - (CKKSAESSIVKey*)unwrapAESKey: (CKKSWrappedAESSIVKey*) keyToUnwrap error: (NSError * __autoreleasing *) error {
364 return [self.keycore unwrapAESKey:keyToUnwrap error:error];
365 }
366
367 - (NSData*)encryptData: (NSData*) plaintext authenticatedData: (NSDictionary<NSString*, NSData*>*) ad error: (NSError * __autoreleasing *) error {
368 return [self.keycore encryptData:plaintext authenticatedData:ad error:error];
369 }
370
371 - (NSData*)decryptData: (NSData*) ciphertext authenticatedData: (NSDictionary<NSString*, NSData*>*) ad error: (NSError * __autoreleasing *) error {
372 return [self.keycore decryptData:ciphertext authenticatedData:ad error:error];
373 }
374
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];
378 }
379
380 - (BOOL)saveKeyMaterialToKeychain: (bool)stashTLK error:(NSError * __autoreleasing *) error {
381 return [self.keycore saveKeyMaterialToKeychain:stashTLK error:error];
382 }
383
384 - (BOOL)loadKeyMaterialFromKeychain: (NSError * __autoreleasing *) error {
385 return [self.keycore loadKeyMaterialFromKeychain:error];
386 }
387
388 - (BOOL)deleteKeyMaterialFromKeychain: (NSError * __autoreleasing *) error {
389 return [self.keycore deleteKeyMaterialFromKeychain:error];
390 }
391
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
401 uuid:uuid
402 parentKeyUUID:parentKeyUUID
403 keyclass:keyclass
404 state:state
405 zoneID:zoneID
406 encodedCKRecord:encodedrecord
407 currentkey:currentkey];
408
409 if(![key loadKeyMaterialFromKeychain:error]) {
410 return nil;
411 }
412
413 return key;
414 }
415
416 + (NSString* _Nullable)isItemKeyForKeychainView:(SecDbItemRef)item {
417
418 NSString* accessgroup = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrAccessGroup);
419 NSString* description = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrDescription);
420 NSString* server = (__bridge NSString*) SecDbItemGetCachedValueWithName(item, kSecAttrServer);
421
422 if(accessgroup && description && server &&
423 ![accessgroup isEqual:[NSNull null]] &&
424 ![description isEqual:[NSNull null]] &&
425 ![server isEqual:[NSNull null]] &&
426
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])) {
433
434 // Certainly looks like us! Return the view name.
435 return server;
436 }
437
438 // Never heard of this item.
439 return nil;
440 }
441
442
443 /* Database functions only return keys marked 'local', unless otherwise specified. */
444
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];
447 }
448
449 + (instancetype) fromDatabaseAnyState: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
450 return [self fromDatabaseWhere: @{@"UUID": uuid, @"ckzone":zoneID.zoneName} error: error];
451 }
452
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];
455 }
456
457 + (instancetype) tryFromDatabaseAnyState: (NSString*) uuid zoneID:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
458 return [self tryFromDatabaseWhere: @{@"UUID": uuid, @"ckzone":zoneID.zoneName} error: error];
459 }
460
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];
463 }
464
465 + (instancetype _Nullable)currentKeyForClass:(CKKSKeyClass*)keyclass
466 zoneID:(CKRecordZoneID*)zoneID
467 error:(NSError *__autoreleasing*)error
468 {
469 // Load the CurrentKey record, and find the key for it
470 CKKSCurrentKeyPointer* ckp = [CKKSCurrentKeyPointer fromDatabase:keyclass zoneID:zoneID error:error];
471 if(!ckp) {
472 return nil;
473 }
474 return [self fromDatabase:ckp.currentKeyUUID zoneID:zoneID error:error];
475 }
476
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];
479 }
480
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];
484 }
485
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];
489 }
490
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];
494 }
495
496 - (bool)saveToDatabaseAsOnlyCurrentKeyForClassAndState: (NSError * __autoreleasing *) error {
497 self.currentkey = true;
498
499 // Find other keys for our key class
500 NSArray<CKKSKey*>* keys = [CKKSKey currentKeysForClass: self.keyclass state: self.state zoneID:self.zoneID error:error];
501 if(!keys) {
502 return false;
503 }
504
505 for(CKKSKey* key in keys) {
506 key.currentkey = false;
507 if(![key saveToDatabase: error]) {
508 return false;
509 }
510 }
511 if(![self saveToDatabase: error]) {
512 return false;
513 }
514
515 return true;
516 }
517
518 #pragma mark - CKRecord handling
519
520 - (NSString*)CKRecordName
521 {
522 return self.keycore.uuid;
523 }
524
525 - (void) setFromCKRecord: (CKRecord*) record {
526 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
527 @throw [NSException
528 exceptionWithName:@"WrongCKRecordTypeException"
529 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordIntermediateKeyType]
530 userInfo:nil];
531 }
532
533 [self setStoredCKRecord: record];
534
535 NSString* uuid = record.recordID.recordName;
536 NSString* parentKeyUUID = nil;
537
538 if(record[SecCKRecordParentKeyRefKey] != nil) {
539 parentKeyUUID = [record[SecCKRecordParentKeyRefKey] recordID].recordName;
540 } else {
541 // We wrap ourself.
542 parentKeyUUID = uuid;
543 }
544
545 NSString* keyclass = record[SecCKRecordKeyClassKey];
546 CKKSWrappedAESSIVKey* wrappedkey =
547 [[CKKSWrappedAESSIVKey alloc] initWithBase64:record[SecCKRecordWrappedKeyKey]];
548
549 self.keycore = [[CKKSKeychainBackedKey alloc] initWithWrappedAESKey:wrappedkey
550 uuid:uuid
551 parentKeyUUID:parentKeyUUID
552 keyclass:(CKKSKeyClass *)keyclass
553 zoneID:record.recordID.zoneID];
554
555 self.keyclass = record[SecCKRecordKeyClassKey];
556 self.wrappedkey = [[CKKSWrappedAESSIVKey alloc] initWithBase64: record[SecCKRecordWrappedKeyKey]];
557
558 self.state = SecCKKSProcessedStateRemote;
559 }
560
561 - (CKRecord*) updateCKRecord: (CKRecord*) record zoneID: (CKRecordZoneID*) zoneID {
562 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
563 @throw [NSException
564 exceptionWithName:@"WrongCKRecordTypeException"
565 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordIntermediateKeyType]
566 userInfo:nil];
567 }
568
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;
573 } else {
574 record[SecCKRecordParentKeyRefKey] = [[CKReference alloc] initWithRecordID: [[CKRecordID alloc] initWithRecordName: self.parentKeyUUID zoneID: zoneID] action: CKReferenceActionValidate];
575 }
576
577 [CKKSItem setOSVersionInRecord: record];
578
579 record[SecCKRecordKeyClassKey] = self.keyclass;
580 record[SecCKRecordWrappedKeyKey] = [self.wrappedkey base64WrappedKey];
581
582 return record;
583 }
584
585 - (bool)matchesCKRecord:(CKRecord*)record {
586 if(![record.recordType isEqual: SecCKRecordIntermediateKeyType]) {
587 return false;
588 }
589
590 if(![record.recordID.recordName isEqualToString: self.uuid]) {
591 secinfo("ckkskey", "UUID does not match");
592 return false;
593 }
594
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");
599 return false;
600 }
601
602 } else {
603 if(![[[record[SecCKRecordParentKeyRefKey] recordID] recordName] isEqualToString: self.parentKeyUUID]) {
604 secinfo("ckkskey", "wrapping key reference (non-self-wrapped) does not match");
605 return false;
606 }
607 }
608
609 if(![record[SecCKRecordKeyClassKey] isEqual: self.keyclass]) {
610 secinfo("ckkskey", "key class does not match");
611 return false;
612 }
613
614 if(![record[SecCKRecordWrappedKeyKey] isEqual: [self.wrappedkey base64WrappedKey]]) {
615 secinfo("ckkskey", "wrapped key does not match");
616 return false;
617 }
618
619 return true;
620 }
621
622
623 #pragma mark - Utility
624
625 - (NSString*)description {
626 return [NSString stringWithFormat: @"<%@(%@): %@ (%@,%@:%d)>",
627 NSStringFromClass([self class]),
628 self.zoneID.zoneName,
629 self.uuid,
630 self.keyclass,
631 self.state,
632 self.currentkey];
633 }
634
635 #pragma mark - CKKSSQLDatabaseObject methods
636
637 + (NSString*) sqlTable {
638 return @"synckeys";
639 }
640
641 + (NSArray<NSString*>*) sqlColumns {
642 return @[@"UUID", @"parentKeyUUID", @"ckzone", @"ckrecord", @"keyclass", @"state", @"currentkey", @"wrappedkey"];
643 }
644
645 - (NSDictionary<NSString*,NSString*>*) whereClauseToFindSelf {
646 return @{@"UUID": self.uuid, @"state": self.state, @"ckzone":self.zoneID.zoneName};
647 }
648
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"};
658 }
659
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];
669
670 }
671
672 + (NSDictionary<NSString*,NSNumber*>*)countsByClass:(CKRecordZoneID*)zoneID error: (NSError * __autoreleasing *) error {
673 NSMutableDictionary* results = [[NSMutableDictionary alloc] init];
674
675 [CKKSSQLDatabaseObject queryDatabaseTable: [[self class] sqlTable]
676 where: @{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)}
677 columns: @[@"keyclass", @"state", @"count(rowid)"]
678 groupBy: @[@"keyclass", @"state"]
679 orderBy:nil
680 limit: -1
681 processRow: ^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
682 results[[NSString stringWithFormat: @"%@-%@", row[@"state"].asString, row[@"keyclass"].asString]] =
683 row[@"count(rowid)"].asNSNumberInteger;
684 }
685 error: error];
686 return results;
687 }
688
689 - (instancetype)copyWithZone:(NSZone *)zone {
690 CKKSKey *keyCopy = [super copyWithZone:zone];
691 keyCopy->_keycore = [_keycore copyWithZone:zone];
692
693 keyCopy->_state = _state;
694 keyCopy->_currentkey = _currentkey;
695 return keyCopy;
696 }
697
698 - (NSData*)serializeAsProtobuf: (NSError * __autoreleasing *) error {
699 if(![self ensureKeyLoaded:error]) {
700 return nil;
701 }
702 CKKSSerializedKey* proto = [[CKKSSerializedKey alloc] init];
703
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];
708
709 return proto.data;
710 }
711
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]
716 uuid:key.uuid
717 keyclass:(CKKSKeyClass*)key.keyclass // TODO sanitize
718 state:SecCKKSProcessedStateRemote
719 zoneID:[[CKRecordZoneID alloc] initWithZoneName:key.zoneName
720 ownerName:CKCurrentUserDefaultName]
721 encodedCKRecord:nil
722 currentkey:false];
723 }
724
725 if(error) {
726 *error = [NSError errorWithDomain:CKKSErrorDomain code:CKKSProtobufFailure description:@"Data failed to parse as a CKKSSerializedKey"];
727 }
728 return nil;
729 }
730
731 @end
732
733 #endif // OCTAGON