]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSItem.m
Security-59306.41.2.tar.gz
[apple/security.git] / keychain / ckks / CKKSItem.m
1 /*
2 * Copyright (c) 2016 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 #include <AssertMacros.h>
27
28 #import <Foundation/Foundation.h>
29 #import "CKKSItem.h"
30 #import "CKKSSIV.h"
31
32 #include <utilities/SecDb.h>
33 #include "keychain/securityd/SecDbItem.h"
34 #include "keychain/securityd/SecItemSchema.h"
35
36 #import <CloudKit/CloudKit.h>
37 #import <CloudKit/CloudKit_Private.h>
38
39 @implementation CKKSItem
40
41 - (instancetype) initWithCKRecord: (CKRecord*) record {
42 if(self = [super initWithCKRecord: record]) {
43 }
44 return self;
45 }
46
47 - (instancetype) initCopyingCKKSItem: (CKKSItem*) item {
48 if(self = [super initWithCKRecordType: item.ckRecordType encodedCKRecord:item.encodedCKRecord zoneID:item.zoneID]) {
49 _uuid = item.uuid;
50 _parentKeyUUID = item.parentKeyUUID;
51 _generationCount = item.generationCount;
52 _encitem = item.encitem;
53 _wrappedkey = item.wrappedkey;
54 _encver = item.encver;
55
56 _plaintextPCSServiceIdentifier = item.plaintextPCSServiceIdentifier;
57 _plaintextPCSPublicKey = item.plaintextPCSPublicKey;
58 _plaintextPCSPublicIdentity = item.plaintextPCSPublicIdentity;
59 }
60 return self;
61 }
62
63 - (instancetype) initWithUUID: (NSString*) uuid
64 parentKeyUUID: (NSString*) parentKeyUUID
65 zoneID: (CKRecordZoneID*) zoneID
66 {
67 return [self initWithUUID:uuid
68 parentKeyUUID:parentKeyUUID
69 zoneID:zoneID
70 encodedCKRecord:nil
71 encItem:nil
72 wrappedkey:nil
73 generationCount:0
74 encver:CKKSItemEncryptionVersionNone];
75 }
76
77 - (instancetype) initWithUUID: (NSString*) uuid
78 parentKeyUUID: (NSString*) parentKeyUUID
79 zoneID: (CKRecordZoneID*) zoneID
80 encItem: (NSData*) encitem
81 wrappedkey: (CKKSWrappedAESSIVKey*) wrappedkey
82 generationCount: (NSUInteger) genCount
83 encver: (NSUInteger) encver
84 {
85 return [self initWithUUID:uuid
86 parentKeyUUID:parentKeyUUID
87 zoneID:zoneID
88 encodedCKRecord:nil
89 encItem:encitem
90 wrappedkey:wrappedkey
91 generationCount:genCount
92 encver:encver];
93 }
94
95 - (instancetype) initWithUUID: (NSString*) uuid
96 parentKeyUUID: (NSString*) parentKeyUUID
97 zoneID: (CKRecordZoneID*)zoneID
98 encodedCKRecord: (NSData*) encodedrecord
99 encItem: (NSData*) encitem
100 wrappedkey: (CKKSWrappedAESSIVKey*) wrappedkey
101 generationCount: (NSUInteger) genCount
102 encver: (NSUInteger) encver
103 {
104 return [self initWithUUID:uuid
105 parentKeyUUID:parentKeyUUID
106 zoneID:zoneID
107 encodedCKRecord:encodedrecord
108 encItem:encitem
109 wrappedkey:wrappedkey
110 generationCount:genCount
111 encver:encver
112 plaintextPCSServiceIdentifier:nil
113 plaintextPCSPublicKey:nil
114 plaintextPCSPublicIdentity:nil];
115 }
116
117 - (instancetype) initWithUUID: (NSString*) uuid
118 parentKeyUUID: (NSString*) parentKeyUUID
119 zoneID: (CKRecordZoneID*)zoneID
120 encodedCKRecord: (NSData*) encodedrecord
121 encItem: (NSData*) encitem
122 wrappedkey: (CKKSWrappedAESSIVKey*) wrappedkey
123 generationCount: (NSUInteger) genCount
124 encver: (NSUInteger) encver
125 plaintextPCSServiceIdentifier: (NSNumber*) pcsServiceIdentifier
126 plaintextPCSPublicKey: (NSData*) pcsPublicKey
127 plaintextPCSPublicIdentity: (NSData*) pcsPublicIdentity
128 {
129 if(self = [super initWithCKRecordType: SecCKRecordItemType encodedCKRecord:encodedrecord zoneID:zoneID]) {
130 _uuid = uuid;
131 _parentKeyUUID = parentKeyUUID;
132 _generationCount = genCount;
133 self.encitem = encitem;
134 _wrappedkey = wrappedkey;
135 _encver = encver;
136
137 _plaintextPCSServiceIdentifier = pcsServiceIdentifier;
138 _plaintextPCSPublicKey = pcsPublicKey;
139 _plaintextPCSPublicIdentity = pcsPublicIdentity;
140 }
141
142 return self;
143 }
144
145 - (BOOL)isEqual: (id) object {
146 if(![object isKindOfClass:[CKKSItem class]]) {
147 return NO;
148 }
149
150 CKKSItem* obj = (CKKSItem*) object;
151
152 return ([self.uuid isEqual: obj.uuid] &&
153 [self.parentKeyUUID isEqual: obj.parentKeyUUID] &&
154 [self.zoneID isEqual: obj.zoneID] &&
155 ((self.encitem == nil && obj.encitem == nil) || ([self.encitem isEqual: obj.encitem])) &&
156 [self.wrappedkey isEqual: obj.wrappedkey] &&
157 self.generationCount == obj.generationCount &&
158 self.encver == obj.encver &&
159 true) ? YES : NO;
160 }
161
162 #pragma mark - CKRecord handling
163
164 - (NSString*) CKRecordName {
165 return self.uuid;
166 }
167
168 - (void) setFromCKRecord: (CKRecord*) record {
169 if(![record.recordType isEqual: SecCKRecordItemType]) {
170 @throw [NSException
171 exceptionWithName:@"WrongCKRecordTypeException"
172 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordItemType]
173 userInfo:nil];
174 }
175
176 [self setStoredCKRecord:record];
177
178 _uuid = [[record recordID] recordName];
179 self.parentKeyUUID = [record[SecCKRecordParentKeyRefKey] recordID].recordName;
180 self.encitem = record[SecCKRecordDataKey];
181 self.wrappedkey = [[CKKSWrappedAESSIVKey alloc] initWithBase64: record[SecCKRecordWrappedKeyKey]];
182 self.generationCount = [record[SecCKRecordGenerationCountKey] unsignedIntegerValue];
183 self.encver = [record[SecCKRecordEncryptionVersionKey] unsignedIntegerValue];
184
185 self.plaintextPCSServiceIdentifier = record[SecCKRecordPCSServiceIdentifier];
186 self.plaintextPCSPublicKey = record[SecCKRecordPCSPublicKey];
187 self.plaintextPCSPublicIdentity = record[SecCKRecordPCSPublicIdentity];
188 }
189
190 + (void)setOSVersionInRecord: (CKRecord*) record {
191 record[SecCKRecordHostOSVersionKey] = SecCKKSHostOSVersion();
192 }
193
194 - (CKRecord*) updateCKRecord: (CKRecord*) record zoneID: (CKRecordZoneID*) zoneID {
195 if(![record.recordType isEqual: SecCKRecordItemType]) {
196 @throw [NSException
197 exceptionWithName:@"WrongCKRecordTypeException"
198 reason:[NSString stringWithFormat: @"CKRecordType (%@) was not %@", record.recordType, SecCKRecordItemType]
199 userInfo:nil];
200 }
201
202 // Items must have a wrapping key.
203 record[SecCKRecordParentKeyRefKey] = [[CKReference alloc] initWithRecordID: [[CKRecordID alloc] initWithRecordName: self.parentKeyUUID zoneID: zoneID] action: CKReferenceActionValidate];
204
205 [CKKSItem setOSVersionInRecord: record];
206
207 record[SecCKRecordDataKey] = self.encitem;
208 record[SecCKRecordWrappedKeyKey] = [self.wrappedkey base64WrappedKey];
209 record[SecCKRecordGenerationCountKey] = [NSNumber numberWithInteger:self.generationCount];
210 // TODO: if the record's generation count is already higher than ours, that's a problem.
211 record[SecCKRecordEncryptionVersionKey] = [NSNumber numberWithInteger:self.encver];
212
213 // Add unencrypted fields
214 record[SecCKRecordPCSServiceIdentifier] = self.plaintextPCSServiceIdentifier;
215 record[SecCKRecordPCSPublicKey] = self.plaintextPCSPublicKey;
216 record[SecCKRecordPCSPublicIdentity] = self.plaintextPCSPublicIdentity;
217
218 return record;
219 }
220
221
222 - (bool) matchesCKRecord: (CKRecord*) record {
223 if(![record.recordType isEqual: SecCKRecordItemType]) {
224 return false;
225 }
226
227 // We only really care about the data, the wrapped key, the generation count, and the parent key.
228 // Note that since all of those things are included as authenticated data into the AES-SIV ciphertext, we could just
229 // compare that. However, check 'em all.
230 if(![record.recordID.recordName isEqualToString: self.uuid]) {
231 secinfo("ckksitem", "UUID does not match");
232 return false;
233 }
234
235 if(![[record[SecCKRecordParentKeyRefKey] recordID].recordName isEqualToString: self.parentKeyUUID]) {
236 secinfo("ckksitem", "wrapping key reference does not match");
237 return false;
238 }
239
240 if(![record[SecCKRecordGenerationCountKey] isEqual: [NSNumber numberWithInteger:self.generationCount]]) {
241 secinfo("ckksitem", "SecCKRecordGenerationCountKey does not match");
242 return false;
243 }
244
245 if(![record[SecCKRecordWrappedKeyKey] isEqual: [self.wrappedkey base64WrappedKey]]) {
246 secinfo("ckksitem", "SecCKRecordWrappedKeyKey does not match");
247 return false;
248 }
249
250 if(![record[SecCKRecordDataKey] isEqual: self.encitem]) {
251 secinfo("ckksitem", "SecCKRecordDataKey does not match");
252 return false;
253 }
254
255 // Compare plaintext records, too
256 // Why is obj-c nullable equality so difficult?
257 if(!((record[SecCKRecordPCSServiceIdentifier] == nil && self.plaintextPCSServiceIdentifier == nil) ||
258 [record[SecCKRecordPCSServiceIdentifier] isEqual: self.plaintextPCSServiceIdentifier])) {
259 secinfo("ckksitem", "SecCKRecordPCSServiceIdentifier does not match");
260 return false;
261 }
262
263 if(!((record[SecCKRecordPCSPublicKey] == nil && self.plaintextPCSPublicKey == nil) ||
264 [record[SecCKRecordPCSPublicKey] isEqual: self.plaintextPCSPublicKey])) {
265 secinfo("ckksitem", "SecCKRecordPCSPublicKey does not match");
266 return false;
267 }
268
269 if(!((record[SecCKRecordPCSPublicIdentity] == nil && self.plaintextPCSPublicIdentity == nil) ||
270 [record[SecCKRecordPCSPublicIdentity] isEqual: self.plaintextPCSPublicIdentity])) {
271 secinfo("ckksitem", "SecCKRecordPCSPublicIdentity does not match");
272 return false;
273 }
274
275 return true;
276 }
277
278 // Generates the list of 'authenticated data' to go along with this item, and optionally adds in unknown, future fields received from CloudKit
279 - (NSDictionary<NSString*, NSData*>*)makeAuthenticatedDataDictionaryUpdatingCKKSItem:(CKKSItem*) olditem encryptionVersion:(SecCKKSItemEncryptionVersion)encversion {
280 switch(encversion) {
281 case CKKSItemEncryptionVersion1:
282 return [self makeAuthenticatedDataDictionaryUpdatingCKKSItemEncVer1];
283 case CKKSItemEncryptionVersion2:
284 return [self makeAuthenticatedDataDictionaryUpdatingCKKSItemEncVer2:olditem];
285 default:
286 @throw [NSException
287 exceptionWithName:@"WrongEncryptionVersionException"
288 reason:[NSString stringWithFormat: @"%d is not a known encryption version", (int)encversion]
289 userInfo:nil];
290 }
291 }
292
293 - (NSDictionary<NSString*, NSData*>*)makeAuthenticatedDataDictionaryUpdatingCKKSItemEncVer1 {
294 NSMutableDictionary<NSString*, NSData*>* authenticatedData = [[NSMutableDictionary alloc] init];
295
296 authenticatedData[@"UUID"] = [self.uuid dataUsingEncoding: NSUTF8StringEncoding];
297 authenticatedData[SecCKRecordWrappedKeyKey] = [self.parentKeyUUID dataUsingEncoding: NSUTF8StringEncoding];
298
299 uint64_t genCount64 = OSSwapHostToLittleConstInt64(self.generationCount);
300 authenticatedData[SecCKRecordGenerationCountKey] = [NSData dataWithBytes:&genCount64 length:sizeof(genCount64)];
301
302 uint64_t encver = OSSwapHostToLittleConstInt64((uint64_t)self.encver);
303 authenticatedData[SecCKRecordEncryptionVersionKey] = [NSData dataWithBytes:&encver length:sizeof(encver)];
304
305 // In v1, don't authenticate the plaintext PCS fields
306 authenticatedData[SecCKRecordPCSServiceIdentifier] = nil;
307 authenticatedData[SecCKRecordPCSPublicKey] = nil;
308 authenticatedData[SecCKRecordPCSPublicIdentity] = nil;
309
310 return authenticatedData;
311 }
312
313 - (NSDictionary<NSString*, NSData*>*)makeAuthenticatedDataDictionaryUpdatingCKKSItemEncVer2:(CKKSItem*) olditem {
314 NSMutableDictionary<NSString*, NSData*>* authenticatedData = [[NSMutableDictionary alloc] init];
315
316 authenticatedData[@"UUID"] = [self.uuid dataUsingEncoding: NSUTF8StringEncoding];
317 authenticatedData[SecCKRecordWrappedKeyKey] = [self.parentKeyUUID dataUsingEncoding: NSUTF8StringEncoding];
318
319 uint64_t genCount64 = OSSwapHostToLittleConstInt64(self.generationCount);
320 authenticatedData[SecCKRecordGenerationCountKey] = [NSData dataWithBytes:&genCount64 length:sizeof(genCount64)];
321
322 uint64_t encver = OSSwapHostToLittleConstInt64((uint64_t)self.encver);
323 authenticatedData[SecCKRecordEncryptionVersionKey] = [NSData dataWithBytes:&encver length:sizeof(encver)];
324
325 // v2 authenticates the PCS fields too
326 if(self.plaintextPCSServiceIdentifier) {
327 uint64_t pcsServiceIdentifier = OSSwapHostToLittleConstInt64([self.plaintextPCSServiceIdentifier unsignedLongValue]);
328 authenticatedData[SecCKRecordPCSServiceIdentifier] = [NSData dataWithBytes:&pcsServiceIdentifier length:sizeof(pcsServiceIdentifier)];
329 }
330 authenticatedData[SecCKRecordPCSPublicKey] = self.plaintextPCSPublicKey;
331 authenticatedData[SecCKRecordPCSPublicIdentity] = self.plaintextPCSPublicIdentity;
332
333 // Iterate through the fields in the old CKKSItem. If we don't recognize any of them, add them to the authenticated data.
334 if(olditem) {
335 CKRecord* record = olditem.storedCKRecord;
336 if(record) {
337 for(NSString* key in record.allKeys) {
338 if([key isEqualToString:@"UUID"] ||
339 [key isEqualToString:SecCKRecordHostOSVersionKey] ||
340 [key isEqualToString:SecCKRecordDataKey] ||
341 [key isEqualToString:SecCKRecordWrappedKeyKey] ||
342 [key isEqualToString:SecCKRecordGenerationCountKey] ||
343 [key isEqualToString:SecCKRecordEncryptionVersionKey] ||
344 [key isEqualToString:SecCKRecordPCSServiceIdentifier] ||
345 [key isEqualToString:SecCKRecordPCSPublicKey] ||
346 [key isEqualToString:SecCKRecordPCSPublicIdentity]) {
347 // This version of CKKS knows about this data field. Ignore them with prejudice.
348 continue;
349 }
350
351 if([key hasPrefix:@"server_"]) {
352 // Ignore all fields prefixed by "server_"
353 continue;
354 }
355
356 id obj = record[key];
357
358 // Skip CKReferences, NSArray, CLLocation, and CKAsset.
359 if([obj isKindOfClass: [NSString class]]) {
360 // Add an NSString.
361 authenticatedData[key] = [obj dataUsingEncoding: NSUTF8StringEncoding];
362 } else if([obj isKindOfClass: [NSData class]]) {
363 // Add an NSData
364 authenticatedData[key] = [obj copy];
365 } else if([obj isKindOfClass:[NSDate class]]) {
366 // Add an NSDate
367 NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
368 NSString* str = [formatter stringForObjectValue: obj];
369
370 authenticatedData[key] = [str dataUsingEncoding: NSUTF8StringEncoding];
371 } else if([obj isKindOfClass: [NSNumber class]]) {
372 // Add an NSNumber
373 uint64_t n64 = OSSwapHostToLittleConstInt64([obj unsignedLongLongValue]);
374 authenticatedData[key] = [NSData dataWithBytes:&n64 length:sizeof(n64)];
375 }
376 }
377
378 }
379 }
380
381 // TODO: add unauth'ed field name here
382
383 return authenticatedData;
384 }
385
386 #pragma mark - Utility
387
388 - (NSString*)description {
389 return [NSString stringWithFormat: @"<%@: %@>", NSStringFromClass([self class]), self.uuid];
390 }
391
392 - (NSString*)debugDescription {
393 return [NSString stringWithFormat: @"<%@: %@ %p>", NSStringFromClass([self class]), self.uuid, self];
394 }
395
396 - (instancetype)copyWithZone:(NSZone *)zone {
397 CKKSItem *itemCopy = [super copyWithZone:zone];
398 itemCopy->_uuid = _uuid;
399 itemCopy->_parentKeyUUID = _parentKeyUUID;
400 itemCopy->_encitem = _encitem;
401 itemCopy->_wrappedkey = _wrappedkey;
402 itemCopy->_generationCount = _generationCount;
403 itemCopy->_encver = _encver;
404 return itemCopy;
405 }
406
407 #pragma mark - Getters/Setters
408
409 - (NSString*) base64Item {
410 return [self.encitem base64EncodedStringWithOptions:0];
411 }
412
413 - (void) setBase64Item: (NSString*) base64Item {
414 _encitem = [[NSData alloc] initWithBase64EncodedString: base64Item options:0];
415 }
416
417 #pragma mark - CKKSSQLDatabaseObject helpers
418
419 // Note that CKKSItems are not intended to be saved directly, and so CKKSItem does not implement sqlTable.
420 // You must subclass CKKSItem to have this work correctly, although you can call back up into this class to use these if you like.
421
422 + (NSArray<NSString*>*)sqlColumns {
423 return @[@"UUID", @"parentKeyUUID", @"ckzone", @"encitem", @"wrappedkey", @"gencount", @"encver", @"ckrecord",
424 @"pcss", @"pcsk", @"pcsi"];
425 }
426
427 - (NSDictionary<NSString*,NSString*>*)whereClauseToFindSelf {
428 return @{@"UUID": self.uuid, @"ckzone":self.zoneID.zoneName};
429 }
430
431 - (NSDictionary<NSString*,NSString*>*)sqlValues {
432 return @{@"UUID": self.uuid,
433 @"parentKeyUUID": self.parentKeyUUID,
434 @"ckzone": CKKSNilToNSNull(self.zoneID.zoneName),
435 @"encitem": self.base64encitem,
436 @"wrappedkey": [self.wrappedkey base64WrappedKey],
437 @"gencount": [[NSNumber numberWithInteger:self.generationCount] stringValue],
438 @"encver": [[NSNumber numberWithInteger:self.encver] stringValue],
439 @"ckrecord": CKKSNilToNSNull([self.encodedCKRecord base64EncodedStringWithOptions:0]),
440 @"pcss": CKKSNilToNSNull(self.plaintextPCSServiceIdentifier),
441 @"pcsk": CKKSNilToNSNull([self.plaintextPCSPublicKey base64EncodedStringWithOptions:0]),
442 @"pcsi": CKKSNilToNSNull([self.plaintextPCSPublicIdentity base64EncodedStringWithOptions:0])};
443 }
444
445 + (instancetype)fromDatabaseRow:(NSDictionary<NSString*, CKKSSQLResult*>*)row {
446 return [[CKKSItem alloc] initWithUUID:row[@"UUID"].asString
447 parentKeyUUID:row[@"parentKeyUUID"].asString
448 zoneID:[[CKRecordZoneID alloc] initWithZoneName: row[@"ckzone"].asString ownerName:CKCurrentUserDefaultName]
449 encodedCKRecord:row[@"ckrecord"].asBase64DecodedData
450 encItem:row[@"encitem"].asBase64DecodedData
451 wrappedkey:row[@"wrappedkey"].asString == nil ? nil : [[CKKSWrappedAESSIVKey alloc] initWithBase64:row[@"wrappedkey"].asString]
452 generationCount:row[@"gencount"].asNSInteger
453 encver:row[@"encver"].asNSInteger
454 plaintextPCSServiceIdentifier:row[@"pcss"].asNSNumberInteger
455 plaintextPCSPublicKey:row[@"pcsk"].asBase64DecodedData
456 plaintextPCSPublicIdentity:row[@"pcsi"].asBase64DecodedData
457 ];
458 }
459
460 @end
461
462 #pragma mark - CK-Aware Database Helpers
463
464 @implementation CKKSSQLDatabaseObject (CKKSZoneExtras)
465
466 + (NSArray<NSString*>*)allUUIDs:(CKRecordZoneID*)zoneID error:(NSError * __autoreleasing *)error {
467 __block NSMutableArray<NSString*>* uuids = [[NSMutableArray alloc] init];
468
469 [CKKSSQLDatabaseObject queryDatabaseTable: [self sqlTable]
470 where:@{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)}
471 columns: @[@"UUID"]
472 groupBy: nil
473 orderBy:nil
474 limit: -1
475 processRow:^(NSDictionary<NSString*, CKKSSQLResult*>* row) {
476 [uuids addObject: row[@"UUID"].asString];
477 }
478 error: error];
479 return uuids;
480 }
481
482 + (NSArray*) all:(CKRecordZoneID*) zoneID error: (NSError * __autoreleasing *) error {
483 return [self allWhere: @{@"ckzone": CKKSNilToNSNull(zoneID.zoneName)} error:error];
484 }
485
486 + (bool) deleteAll:(CKRecordZoneID*) zoneID error: (NSError * __autoreleasing *) error {
487 bool ok = [CKKSSQLDatabaseObject deleteFromTable:[self sqlTable] where: @{@"ckzone":CKKSNilToNSNull(zoneID.zoneName)} connection:nil error: error];
488
489 if(ok) {
490 secdebug("ckksitem", "Deleted all %@", self);
491 } else {
492 secdebug("ckksitem", "Couldn't delete all %@: %@", self, error ? *error : @"unknown");
493 }
494 return ok;
495 }
496
497 @end
498
499 #endif