2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 #import <XCTest/XCTest.h>
27 #import "CloudKitMockXCTest.h"
29 #import "keychain/ckks/CKKS.h"
30 #import "keychain/ckks/CKKSKey.h"
31 #import "keychain/ckks/CKKSItem.h"
32 #import "keychain/ckks/CKKSOutgoingQueueEntry.h"
33 #import "keychain/ckks/CKKSIncomingQueueEntry.h"
34 #import "keychain/ckks/CKKSItemEncrypter.h"
36 #include <securityd/SecItemServer.h>
37 #include <Security/SecItemPriv.h>
39 @interface CloudKitKeychainEncryptionTests : CloudKitMockXCTest
42 @implementation CloudKitKeychainEncryptionTests
45 // We don't really want to spin up the whole machinery for the encryption tests
61 SecCKKSResetSyncing();
64 - (void)testKeyGeneration {
65 CKKSAESSIVKey* key1 = [CKKSAESSIVKey randomKey];
66 CKKSAESSIVKey* key2 = [CKKSAESSIVKey randomKey];
67 CKKSAESSIVKey* fixedkey1 = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
68 XCTAssertNotNil(fixedkey1, "fixedkey1 generated from base64");
69 CKKSAESSIVKey* fixedkey2 = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
70 XCTAssertNotNil(fixedkey2, "fixedkey2 generated from base64");
72 XCTAssertEqualObjects(fixedkey1, fixedkey2, "matching fixed keys match");
73 XCTAssertNotEqualObjects(fixedkey1, key1, "fixed key and random key do not match");
74 XCTAssertNotEqualObjects(key1, key2, "two random keys do not match");
76 XCTAssertNil([[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA------AAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="], "Invalid base64 does not generate a key");
79 - (void)testBasicEncryption {
80 NSString* plaintext = @"plaintext is plain";
81 NSData* plaintextData = [plaintext dataUsingEncoding: NSUTF8StringEncoding];
85 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="]
86 uuid:@"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"
87 keyclass:SecCKKSKeyClassC
88 state: SecCKKSProcessedStateLocal
89 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
93 NSData* ciphertext = [key encryptData: plaintextData authenticatedData: nil error: &error];
94 XCTAssertNil(error, "No error encrypting plaintext");
95 XCTAssertNotNil(ciphertext, "Received a ciphertext");
96 NSData* roundtrip = [key decryptData: ciphertext authenticatedData: nil error: &error];
97 XCTAssertNil(error, "No error decrypting roundtrip");
98 XCTAssertNotNil(roundtrip, "Received a plaintext");
99 XCTAssertEqualObjects(plaintextData, roundtrip, "roundtripped data matches input");
101 NSData* shortDecrypt = [key decryptData: [@"asdf" dataUsingEncoding:NSUTF8StringEncoding] authenticatedData:nil error:&error];
102 XCTAssertNotNil(error, "Decrypting a short plaintext returned an error");
103 XCTAssertNil(shortDecrypt, "Decrypting a short plaintext returned nil");
106 // Check that we're adding enough entropy
107 NSData* ciphertextAgain = [key encryptData: plaintextData authenticatedData: nil error: &error];
108 XCTAssertNil(error, "No error encrypting plaintext");
109 XCTAssertNotNil(ciphertextAgain, "Received a ciphertext");
110 NSData* roundtripAgain = [key decryptData: ciphertextAgain authenticatedData: nil error: &error];
111 XCTAssertNil(error, "No error decrypting roundtrip");
112 XCTAssertNotNil(roundtripAgain, "Received a plaintext");
113 XCTAssertEqualObjects(plaintextData, roundtripAgain, "roundtripped data matches input");
115 XCTAssertNotEqualObjects(ciphertext, ciphertextAgain, "two encryptions of same input produce different outputs");
118 CKKSKey* key2 = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
119 uuid:@"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6"
120 keyclass:SecCKKSKeyClassC
121 state: SecCKKSProcessedStateLocal
122 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
126 NSData* ciphertext2 = [key2 encryptData: plaintextData authenticatedData: nil error: &error];
127 XCTAssertNil(error, "No error encrypting plaintext");
128 XCTAssertNotNil(ciphertext2, "Received a ciphertext");
129 NSData* roundtrip2 = [key decryptData: ciphertext authenticatedData: nil error: &error];
130 XCTAssertNil(error, "No error decrypting roundtrip");
131 XCTAssertNotNil(roundtrip2, "Received a plaintext");
132 XCTAssertEqualObjects(plaintextData, roundtrip2, "roundtripped data matches input");
134 XCTAssertNotEqualObjects(ciphertext, ciphertext2, "ciphertexts with distinct keys are distinct");
137 - (void)testAuthEncryption {
138 NSString* plaintext = @"plaintext is plain";
139 NSData* plaintextData = [plaintext dataUsingEncoding: NSUTF8StringEncoding];
141 NSError* error = nil;
143 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="]
144 uuid:@"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"
145 keyclass:SecCKKSKeyClassC
146 state:SecCKKSProcessedStateLocal
147 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
150 NSDictionary<NSString*, NSData*>* ad = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding] };
152 NSData* ciphertext = [key encryptData: plaintextData authenticatedData: ad error: &error];
153 XCTAssertNil(error, "No error encrypting plaintext");
154 XCTAssertNotNil(ciphertext, "Received a ciphertext");
155 NSData* roundtrip = [key decryptData: ciphertext authenticatedData: ad error: &error];
156 XCTAssertNil(error, "No error decrypting roundtrip");
157 XCTAssertNotNil(roundtrip, "Received a plaintext");
158 XCTAssertEqualObjects(plaintextData, roundtrip, "roundtripped data matches input");
160 // Without AD, decryption should fail
161 roundtrip = [key decryptData: ciphertext authenticatedData: nil error: &error];
162 XCTAssertNotNil(error, "Not passing in the authenticated data causes break");
163 XCTAssertNil(roundtrip, "on error, don't receive plaintext");
166 roundtrip = [key decryptData: ciphertext authenticatedData: @{ @"test": [@"wrongdata" dataUsingEncoding: NSUTF8StringEncoding] } error: &error];
167 XCTAssertNotNil(error, "Wrong authenticated data causes break");
168 XCTAssertNil(roundtrip, "on error, don't receive plaintext");
172 - (void)testDictionaryEncryption {
173 NSDictionary<NSString*, NSData*>* plaintext = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
174 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
175 NSDictionary<NSString*, NSData*>* roundtrip;
177 NSError* error = nil;
179 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
180 uuid:@"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6"
181 keyclass:SecCKKSKeyClassC
182 state: SecCKKSProcessedStateLocal
183 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
187 NSData* ciphertext = [CKKSItemEncrypter encryptDictionary: plaintext key: key.aessivkey authenticatedData: nil error: &error];
188 XCTAssertNil(error, "No error encrypting plaintext");
189 XCTAssertNotNil(ciphertext, "Received a ciphertext");
190 roundtrip = [CKKSItemEncrypter decryptDictionary: ciphertext key: key.aessivkey authenticatedData: nil error: &error];
191 XCTAssertNil(error, "No error decrypting roundtrip");
192 XCTAssertNotNil(roundtrip, "Received a plaintext");
193 XCTAssertEqualObjects(plaintext, roundtrip, "roundtripped dictionary matches input");
195 NSDictionary* authenticatedData = @{@"data": [@"auth" dataUsingEncoding: NSUTF8StringEncoding], @"moredata": [@"unauth" dataUsingEncoding: NSUTF8StringEncoding]};
196 NSDictionary* unauthenticatedData = @{@"data": [@"notequal" dataUsingEncoding: NSUTF8StringEncoding], @"moredata": [@"unauth" dataUsingEncoding: NSUTF8StringEncoding]};
198 NSData* authciphertext = [CKKSItemEncrypter encryptDictionary: plaintext key: key.aessivkey authenticatedData: authenticatedData error: &error];
199 XCTAssertNil(error, "No error encrypting plaintext with authenticated data");
200 XCTAssertNotNil(authciphertext, "Received a ciphertext");
201 roundtrip = [CKKSItemEncrypter decryptDictionary: authciphertext key: key.aessivkey authenticatedData: authenticatedData error: &error];
202 XCTAssertNil(error, "No error decrypting roundtrip with authenticated data");
203 XCTAssertNotNil(roundtrip, "Received a plaintext");
204 XCTAssertEqualObjects(plaintext, roundtrip, "roundtripped dictionary matches input");
206 roundtrip = [CKKSItemEncrypter decryptDictionary: authciphertext key: key.aessivkey authenticatedData: unauthenticatedData error: &error];
207 XCTAssertNotNil(error, "Error decrypting roundtrip with bad authenticated data");
208 XCTAssertNil(roundtrip, "Did not receive a plaintext when authenticated data is wrong");
211 - (void)testKeyWrapping {
212 CKKSAESSIVKey* key = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
214 CKKSAESSIVKey* keyToWrap = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
216 NSError* error = nil;
218 CKKSWrappedAESSIVKey* wrappedKey = [key wrapAESKey: keyToWrap error:&error];
219 XCTAssertNil(error, "no error wrapping key");
220 XCTAssertNotNil(wrappedKey, "wrapped key was returned");
222 XCTAssert(0 != memcmp(keyToWrap->key, (wrappedKey->key)+(CKKSWrappedKeySize - CKKSKeySize), CKKSKeySize), "wrapped key is different from original key");
224 CKKSAESSIVKey* unwrappedKey = [key unwrapAESKey: wrappedKey error:&error];
225 XCTAssertNil(error, "no error unwrapping key");
226 XCTAssertNotNil(unwrappedKey, "unwrapped key was returned");
228 XCTAssert(0 == memcmp(keyToWrap->key, unwrappedKey->key, CKKSKeySize), "unwrapped key matches original key");
229 XCTAssertEqualObjects(keyToWrap, unwrappedKey, "unwrapped key matches original key");
232 - (void)testKeyWrappingFailure {
233 CKKSAESSIVKey* key = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
235 CKKSAESSIVKey* keyToWrap = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
237 NSError* error = nil;
239 CKKSWrappedAESSIVKey* wrappedKey = [key wrapAESKey: keyToWrap error:&error];
240 XCTAssertNil(error, "no error wrapping key");
241 XCTAssertNotNil(wrappedKey, "wrapped key was returned");
243 XCTAssert(0 != memcmp(keyToWrap->key, (wrappedKey->key)+(CKKSWrappedKeySize - CKKSKeySize), CKKSKeySize), "wrapped key is different from original key");
244 wrappedKey->key[0] ^= 0x1;
246 CKKSAESSIVKey* unwrappedKey = [key unwrapAESKey: wrappedKey error:&error];
247 XCTAssertNotNil(error, "error unwrapping key");
248 XCTAssertNil(unwrappedKey, "unwrapped key was not returned in error case");
251 - (void)testKeyHierarchy {
252 NSError* error = nil;
253 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
254 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
256 [tlk saveToDatabase:&error];
257 [tlk saveKeyMaterialToKeychain:&error];
258 XCTAssertNil(error, "tlk saved to database without error");
260 CKKSKey* level1 = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassA error:&error];
261 level1.encodedCKRecord = testCKRecord;
262 XCTAssertNotNil(level1, "level 1 key created");
263 XCTAssertNil(error, "level 1 key created");
265 [level1 saveToDatabase:&error];
266 XCTAssertNil(error, "level 1 key saved to database without error");
268 CKKSKey* level2 = [CKKSKey randomKeyWrappedByParent: level1 error:&error];
269 level2.encodedCKRecord = testCKRecord;
270 XCTAssertNotNil(level2, "level 2 key created");
271 XCTAssertNil(error, "no error creating level 2 key");
272 [level2 saveToDatabase:&error];
273 XCTAssertNil(error, "level 2 key saved to database without error");
275 NSString* level2UUID = level2.uuid;
277 // Fetch the level2 key from the database.
278 CKKSKey* extractedkey = [CKKSKey fromDatabase:level2UUID zoneID:self.testZoneID error:&error];
279 [extractedkey unwrapViaKeyHierarchy: &error];
280 XCTAssertNotNil(extractedkey, "could fetch key again");
281 XCTAssertNil(error, "no error fetching key from database");
283 CKKSAESSIVKey* extracedaeskey = [extractedkey ensureKeyLoaded:&error];
284 XCTAssertNotNil(extractedkey, "fetched key could unwrap");
285 XCTAssertNil(error, "no error forcing unwrap on fetched key");
287 XCTAssertEqualObjects(level2.aessivkey, extracedaeskey, @"fetched aes key is equal to saved key");
290 - (void)ensureKeychainSaveLoad: (CKKSKey*) key {
291 NSError* error = nil;
292 [key saveToDatabase:&error];
293 XCTAssertNil(error, "no error saving to database");
294 [key saveKeyMaterialToKeychain:&error];
295 XCTAssertNil(error, "no error saving to keychain");
297 CKKSKey* loadedKey = [CKKSKey fromDatabase:key.uuid zoneID:self.testZoneID error:&error];
298 XCTAssertNil(error, "no error loading from database");
299 XCTAssertNotNil(loadedKey, "Received an item back from the database");
301 XCTAssert([loadedKey loadKeyMaterialFromKeychain:&error], "could load key material back from keychain");
302 XCTAssertNil(error, "no error loading key from keychain");
304 XCTAssertEqualObjects(loadedKey.aessivkey, key.aessivkey, "Loaded key is identical after save/load");
307 - (void)testKeychainSave {
308 NSError* error = nil;
309 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
310 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
311 [self ensureKeychainSaveLoad: tlk];
313 // Ensure that Class A and Class C can do the same thing
314 CKKSKey* classA = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassA error:&error];
315 classA.encodedCKRecord = testCKRecord;
316 XCTAssertNil(error, "No error creating random class A key");
317 [self ensureKeychainSaveLoad: classA];
318 CKKSKey* classC = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassC error:&error];
319 classC.encodedCKRecord = testCKRecord;
320 XCTAssertNil(error, "No error creating random class C key");
321 [self ensureKeychainSaveLoad: classC];
324 - (BOOL)tryDecryptWithProperAuthData:(CKKSItem*)ciphertext plaintext:(NSDictionary<NSString*, NSData*>*)plaintext {
325 NSDictionary<NSString*, NSData*>* roundtrip;
326 NSError *error = nil;
327 roundtrip = [CKKSItemEncrypter decryptItemToDictionary: (CKKSItem*) ciphertext error: &error];
328 XCTAssertNil(error, "No error decrypting roundtrip");
329 XCTAssertNotNil(roundtrip, "Received a plaintext");
330 XCTAssertEqualObjects(plaintext, roundtrip, "roundtripped dictionary matches input");
331 return error == nil && roundtrip != nil && [plaintext isEqualToDictionary:roundtrip];
334 - (BOOL)tryDecryptWithBrokenAuthData:(CKKSItem *)ciphertext {
335 NSDictionary<NSString*, NSData*>* brokenAuthentication;
336 NSError *error = nil;
337 brokenAuthentication = [CKKSItemEncrypter decryptItemToDictionary: (CKKSItem*) ciphertext error: &error];
338 XCTAssertNotNil(error, "Error exists decrypting ciphertext with bad authenticated data: %@", error);
339 XCTAssertNil(brokenAuthentication, "Did not receive a plaintext if authenticated data was mucked with");
340 return error != nil && brokenAuthentication == nil;
343 - (void)testItemDictionaryEncryption {
344 NSDictionary<NSString*, NSData*>* plaintext = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
345 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
346 NSError* error = nil;
347 NSString *uuid = @"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7";
349 CKKSKey* key = [self fakeTLK:self.testZoneID];
350 [key saveToDatabase: &error];
351 [key saveKeyMaterialToKeychain:&error];
352 XCTAssertNil(error, @"could save the fake TLK to the database");
354 CKKSItem* ciphertext = [CKKSItemEncrypter encryptCKKSItem: [[CKKSItem alloc] initWithUUID:uuid
355 parentKeyUUID:key.uuid
356 zoneID:self.testZoneID]
357 dataDictionary:plaintext
361 XCTAssertNil(error, "No error encrypting plaintext");
362 XCTAssertNotNil(ciphertext, "Received a ciphertext");
363 XCTAssertEqual(ciphertext.encver, currentCKKSItemEncryptionVersion, "Encryption sets the current protocol version");
365 [self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext];
367 // Make sure these fields are authenticated and that authentication works.
368 // Messing with them should make the item not decrypt.
369 ciphertext.generationCount = 100;
370 XCTAssertTrue([self tryDecryptWithBrokenAuthData:ciphertext], "Decryption with broken authentication data fails");
371 ciphertext.generationCount = 0;
372 XCTAssertTrue([self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext], "Decryption with authentication data succeeds");
374 ciphertext.encver += 1;
375 XCTAssertTrue([self tryDecryptWithBrokenAuthData:ciphertext], "Decryption with broken authentication data fails");
376 ciphertext.encver -= 1;
377 XCTAssertTrue([self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext], "Decryption with authentication data succeeds");
379 ciphertext.uuid = @"x";
380 XCTAssertTrue([self tryDecryptWithBrokenAuthData:ciphertext], "Decryption with broken authentication data fails");
381 ciphertext.uuid = uuid;
382 XCTAssertTrue([self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext], "Decryption with authentication data succeeds");
385 - (void)testEncryptionVersions {
386 NSDictionary<NSString*, NSData*>* plaintext = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
387 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
388 NSDictionary<NSString*, NSData*>* output;
389 NSError *error = nil;
390 NSData* data = [NSPropertyListSerialization dataWithPropertyList:plaintext
391 format:NSPropertyListBinaryFormat_v1_0
395 CKKSKey* key = [self fakeTLK:self.testZoneID];
396 [key saveToDatabase: &error];
397 [key saveKeyMaterialToKeychain:&error];
398 XCTAssertNil(error, @"could save the fake TLK to the database");
400 CKKSAESSIVKey* keyToWrap = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
401 CKKSWrappedAESSIVKey* wrappedKey = [key wrapAESKey: keyToWrap error:&error];
402 XCTAssertNil(error, "no error wrapping key");
403 XCTAssertNotNil(wrappedKey, "wrapped key was returned");
404 CKKSItem* baseitem = [[CKKSItem alloc] initWithUUID:@"abc"
405 parentKeyUUID:key.uuid
406 zoneID:self.testZoneID
408 wrappedkey:wrappedKey
410 encver:CKKSItemEncryptionVersionNone];
411 XCTAssertNotNil(baseitem, "Constructed CKKSItem");
413 // First try versionNone. Should fail, we don't support unencrypted data
414 output = [CKKSItemEncrypter decryptItemToDictionary:baseitem error:&error];
415 XCTAssert(error, "Did not failed to decrypt v0 item");
416 XCTAssertNil(output, "Did not failed to decrypt v0 item");
420 // Then try version1. Should take actual decryption path and fail because there's no properly encrypted data.
421 baseitem.encver = CKKSItemEncryptionVersion1;
422 output = [CKKSItemEncrypter decryptItemToDictionary:baseitem error:&error];
423 XCTAssertNotNil(error, "Taking v1 codepath without encrypted item fails");
424 XCTAssertEqualObjects(error.localizedDescription, @"could not ccsiv_crypt", "Error specifically failure to ccsiv_crypt");
425 XCTAssertNil(output, "Did not receive output from failed decryption call");
429 // Finally, some unknown version should fail immediately
430 baseitem.encver = 100;
431 output = [CKKSItemEncrypter decryptItemToDictionary:baseitem error:&error];
432 XCTAssertNotNil(error);
433 NSString *errstr = [NSString stringWithFormat:@"%@", error.localizedDescription];
434 NSString *expected = @"Unrecognized encryption version: 100";
435 XCTAssertEqualObjects(expected, errstr, "Error is specific to unrecognized version failure");
436 XCTAssertNil(output);
439 - (void)testKeychainPersistence {
441 NSString* plaintext = @"plaintext is plain";
442 NSData* plaintextData = [plaintext dataUsingEncoding: NSUTF8StringEncoding];
444 NSError* error = nil;
446 NSString* uuid = @"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6";
448 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
450 keyclass:SecCKKSKeyClassA
451 state:SecCKKSProcessedStateLocal
452 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
456 NSData* ciphertext = [key encryptData: plaintextData authenticatedData: nil error: &error];
457 XCTAssertNil(error, "No error encrypting plaintext");
458 XCTAssertNotNil(ciphertext, "Received a ciphertext");
459 NSData* roundtrip = [key decryptData: ciphertext authenticatedData: nil error: &error];
460 XCTAssertNil(error, "No error decrypting roundtrip");
461 XCTAssertNotNil(roundtrip, "Received a plaintext");
462 XCTAssertEqualObjects(plaintextData, roundtrip, "roundtripped data matches input");
464 // Check that there is no key material in the keychain
465 CKKSKey* reloadedKey = [CKKSKey keyFromKeychain:uuid
467 keyclass:SecCKKSKeyClassA
468 state:SecCKKSProcessedStateLocal
469 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
474 XCTAssertNotNil(error, "error exists when there's nothing in the keychain");
475 XCTAssertNil(reloadedKey, "no key object when there's nothing in the keychain");
478 [key saveKeyMaterialToKeychain:&error];
479 XCTAssertNil(error, "Could save key material to keychain");
481 // Reload the key material and check that it works
482 reloadedKey = [CKKSKey keyFromKeychain:uuid
484 keyclass:SecCKKSKeyClassA
485 state:SecCKKSProcessedStateLocal
486 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
491 XCTAssertNil(error, "No error loading key from keychain");
492 XCTAssertNotNil(reloadedKey, "Could load key from keychain");
494 NSData* ciphertext2 = [reloadedKey encryptData: plaintextData authenticatedData: nil error: &error];
495 XCTAssertNil(error, "No error encrypting plaintext");
496 XCTAssertNotNil(ciphertext2, "Received a ciphertext");
497 NSData* roundtrip2 = [reloadedKey decryptData: ciphertext2 authenticatedData: nil error: &error];
498 XCTAssertNil(error, "No error decrypting roundtrip");
499 XCTAssertNotNil(roundtrip2, "Received a plaintext");
500 XCTAssertEqualObjects(plaintextData, roundtrip2, "roundtripped data matches input");
502 XCTAssertEqualObjects(key.aessivkey, reloadedKey.aessivkey, "reloaded AES key is equal to generated key");
504 [key deleteKeyMaterialFromKeychain: &error];
505 XCTAssertNil(error, "could delete key material from keychain");
507 // Check that there is no key material in the keychain
508 // Note that TLKs will be stashed (and deleteKeyMaterial won't delete the stash), and so this test would fail for a TLK
510 reloadedKey = [CKKSKey keyFromKeychain:uuid
512 keyclass:SecCKKSKeyClassA
513 state:SecCKKSProcessedStateLocal
514 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
519 XCTAssertNotNil(error, "error exists when there's nothing in the keychain");
520 XCTAssertNil(reloadedKey, "no key object when there's nothing in the keychain");
524 - (BOOL)padAndUnpadDataWithLength:(NSUInteger)dataLength blockSize:(NSUInteger)blockSize extra:(BOOL)extra {
526 NSMutableData *data = [NSMutableData dataWithLength:dataLength];
527 memset((unsigned char *)[data mutableBytes], 0x55, dataLength);
528 NSMutableData *orig = [data mutableCopy];
529 NSData *padded = [CKKSItemEncrypter padData:data blockSize:blockSize additionalBlock:extra];
530 XCTAssertNotNil(padded, "Padding never returns nil");
531 XCTAssertEqualObjects(data, orig, "Input object unmodified");
532 XCTAssertTrue(padded.length % blockSize == 0, "Padded data aligns on %lu-byte blocksize", (unsigned long)blockSize);
533 XCTAssertTrue(padded.length > data.length, "At least one byte of padding has been added");
534 NSData *unpadded = [CKKSItemEncrypter removePaddingFromData:padded];
535 XCTAssertNotNil(unpadded, "Successfully removed padding again");
537 // Test it fails by poking some byte in the padding
538 NSMutableData *glitch = [NSMutableData dataWithData:padded];
539 NSUInteger offsetFromTop = glitch.length - arc4random_uniform((unsigned)(glitch.length - data.length)) - 1;
540 uint8_t poke = ((uint8_t)arc4random_uniform(0xFF) & 0x7E) + 1; // This gets most of the values while excluding 0 and 0x80
541 unsigned char *bytes = [glitch mutableBytes];
542 bytes[offsetFromTop] = poke;
543 XCTAssertNil([CKKSItemEncrypter removePaddingFromData:glitch], "Cannot remove broken padding (len %lu, dlen %lu, plen %lu glitchidx %lu, glitchval 0x%x)", (unsigned long)glitch.length, (unsigned long)data.length, (unsigned long)glitch.length - data.length, (unsigned long)offsetFromTop, poke);
545 return padded && unpadded && [unpadded isEqual:data];
548 - (void)testPadding {
549 [self runPaddingTest:NO];
550 [self runPaddingTest:YES];
553 XCTAssertNil([CKKSItemEncrypter removePaddingFromData:[NSData data]], "zero data valid ?");
555 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80" length:1]];
556 XCTAssert(data && data.length == 0, "data wrong size");
558 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x00" length:2]];
559 XCTAssert(data && data.length == 0, "data wrong size");
560 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x00\x00" length:3]];
561 XCTAssert(data && data.length == 0, "data wrong size");
562 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x80\x80" length:3]];
563 XCTAssert(data && data.length == 2, "data wrong size");
564 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x80\x00" length:3]];
565 XCTAssert(data && data.length == 1, "data wrong size");
566 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x00\x80\x00" length:3]];
567 XCTAssert(data && data.length == 1, "data wrong size");
571 - (void)runPaddingTest:(BOOL)extra {
573 // Aligned, arbitrary lengths
574 for (int idx = 1; idx <= 128; ++idx) {
575 XCTAssertTrue([self padAndUnpadDataWithLength:idx blockSize:idx extra:extra], "Padding aligned data succeeds");
578 // Off-by-one, arbitrary lengths
579 for (int idx = 1; idx <= 128; ++idx) {
580 XCTAssertTrue([self padAndUnpadDataWithLength:idx - 1 blockSize:idx extra:extra], "Padding aligned data succeeds");
581 XCTAssertTrue([self padAndUnpadDataWithLength:idx + 1 blockSize:idx extra:extra], "Padding aligned data succeeds");
584 // Misaligned, arbitrary lengths
585 for (int idx = 1; idx <= 1000; ++idx) {
586 NSUInteger dataSize = arc4random_uniform(128) + 1;
587 NSUInteger blockSize = arc4random_uniform(128) + 1;
588 XCTAssertTrue([self padAndUnpadDataWithLength:dataSize blockSize:blockSize extra:extra], "Padding data lenght %lu to blockSize %lu succeeds", (unsigned long)dataSize, (unsigned long)blockSize);
591 // Special case: blocksize 0 results in 1 byte of padding always
592 NSMutableData *data = [NSMutableData dataWithLength:23];
593 memset((unsigned char *)[data mutableBytes], 0x55, 23);
594 NSData *padded = [CKKSItemEncrypter padData:data blockSize:0 additionalBlock:extra];
595 XCTAssertNotNil(padded, "Padding never returns nil");
596 XCTAssertTrue(padded.length == data.length + extra ? 2 : 1, "One byte of padding has been added, 2 if extra padding");
597 NSData *unpadded = [CKKSItemEncrypter removePaddingFromData:padded];
598 XCTAssertNotNil(unpadded, "Successfully removed padding again");
599 XCTAssertEqualObjects(data, unpadded, "Data effectively unmodified through padding-unpadding trip");
602 unpadded = [CKKSItemEncrypter removePaddingFromData:data];
603 XCTAssertNil(unpadded, "Cannot remove padding where none exists");
606 padded = [CKKSItemEncrypter padData:nil blockSize:0 additionalBlock:extra];
607 XCTAssertNotNil(padded, "padData always returns a data object");
608 XCTAssertEqual(padded.length, extra ? 2ul : 1ul, "Length of padded nil object is padding byte only--two if extra");
609 unpadded = [CKKSItemEncrypter removePaddingFromData:nil];
610 XCTAssertNil(unpadded, "Removing padding from nil is senseless");
613 - (BOOL)encryptAndDecryptDictionary:(NSDictionary<NSString*, NSData*>*)data key:(CKKSKey *)key {
614 NSDictionary<NSString*, NSData*>* roundtrip;
615 NSError *error = nil;
616 NSData* ciphertext = [CKKSItemEncrypter encryptDictionary: data key: key.aessivkey authenticatedData: nil error: &error];
617 XCTAssertNil(error, "No error encrypting plaintext");
618 XCTAssertNotNil(ciphertext, "Received a ciphertext");
619 // AES-SIV adds 32 bytes, need to subtract them
620 XCTAssertTrue((ciphertext.length - 32) % SecCKKSItemPaddingBlockSize == 0, "Ciphertext aligned on %lu-byte boundary", (unsigned long)SecCKKSItemPaddingBlockSize);
621 roundtrip = [CKKSItemEncrypter decryptDictionary: ciphertext key: key.aessivkey authenticatedData: nil error: &error];
622 XCTAssertNil(error, "No error decrypting roundtrip");
623 XCTAssertNotNil(roundtrip, "Received a plaintext");
624 XCTAssertEqualObjects(data, roundtrip, "roundtripped dictionary matches input");
625 return (ciphertext.length - 32) % SecCKKSItemPaddingBlockSize == 0 && roundtrip && error == nil && [data isEqualToDictionary:roundtrip];
628 - (void)testDictionaryPadding {
629 // Pad a bunch of bytes to nearest boundary
630 NSDictionary<NSString*, NSData*>* unaligned_74 = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
631 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
632 // Pad precisely one byte
633 NSDictionary<NSString*, NSData*>* unaligned_79 = @{ @"test12345": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
634 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
635 // Already on boundary, pad until next boundary
636 NSDictionary<NSString*, NSData*>* aligned_80 = @{ @"test123456": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
637 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
638 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
639 uuid:@"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6"
640 keyclass:SecCKKSKeyClassC
641 state:SecCKKSProcessedStateLocal
646 XCTAssertTrue([self encryptAndDecryptDictionary:unaligned_74 key:key], "Roundtrip with unaligned data succeeds");
647 XCTAssertTrue([self encryptAndDecryptDictionary:unaligned_79 key:key], "Roundtrip with unaligned data succeeds");
648 XCTAssertTrue([self encryptAndDecryptDictionary:aligned_80 key:key], "Roundtrip with aligned data succeeds");