]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/tests/CKKSAESSIVEncryptionTests.m
Security-59306.41.2.tar.gz
[apple/security.git] / keychain / ckks / tests / CKKSAESSIVEncryptionTests.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 #import <XCTest/XCTest.h>
27 #import "CloudKitMockXCTest.h"
28
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"
35
36 #include "keychain/securityd/SecItemServer.h"
37 #include <Security/SecItemPriv.h>
38 #include "OSX/sec/Security/SecItemShim.h"
39
40 @interface CloudKitKeychainAESSIVEncryptionTests : CloudKitMockXCTest
41 @end
42
43 @implementation CloudKitKeychainAESSIVEncryptionTests
44
45 + (void)setUp {
46 // We don't really want to spin up the whole machinery for the encryption tests
47 SecCKKSDisable();
48
49 [super setUp];
50 }
51
52 - (void)setUp {
53 [super setUp];
54 }
55
56 - (void)tearDown {
57 [super tearDown];
58 }
59
60 + (void)tearDown {
61 [super tearDown];
62 SecCKKSResetSyncing();
63 }
64
65 - (void)testKeyGeneration {
66 NSError* error = nil;
67 CKKSAESSIVKey* key1 = [CKKSAESSIVKey randomKey:&error];
68 XCTAssertNil(error, "Should be no error creating random key");
69 CKKSAESSIVKey* key2 = [CKKSAESSIVKey randomKey:&error];
70 XCTAssertNil(error, "Should be no error creating random key");
71
72 CKKSAESSIVKey* fixedkey1 = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
73 XCTAssertNotNil(fixedkey1, "fixedkey1 generated from base64");
74 CKKSAESSIVKey* fixedkey2 = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
75 XCTAssertNotNil(fixedkey2, "fixedkey2 generated from base64");
76
77 XCTAssertEqualObjects(fixedkey1, fixedkey2, "matching fixed keys match");
78 XCTAssertNotEqualObjects(fixedkey1, key1, "fixed key and random key do not match");
79 XCTAssertNotEqualObjects(key1, key2, "two random keys do not match");
80
81 XCTAssertNil([[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA------AAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="], "Invalid base64 does not generate a key");
82 }
83
84 - (void)testBasicAESSIVEncryption {
85 NSString* plaintext = @"plaintext is plain";
86 NSData* plaintextData = [plaintext dataUsingEncoding: NSUTF8StringEncoding];
87
88 NSError* error = nil;
89
90 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="]
91 uuid:@"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"
92 keyclass:SecCKKSKeyClassC
93 state: SecCKKSProcessedStateLocal
94 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
95 encodedCKRecord: nil
96 currentkey: true];
97
98 NSData* ciphertext = [key encryptData: plaintextData authenticatedData: nil error: &error];
99 XCTAssertNil(error, "No error encrypting plaintext");
100 XCTAssertNotNil(ciphertext, "Received a ciphertext");
101 NSData* roundtrip = [key decryptData: ciphertext authenticatedData: nil error: &error];
102 XCTAssertNil(error, "No error decrypting roundtrip");
103 XCTAssertNotNil(roundtrip, "Received a plaintext");
104 XCTAssertEqualObjects(plaintextData, roundtrip, "roundtripped data matches input");
105
106 NSData* shortDecrypt = [key decryptData: [@"asdf" dataUsingEncoding:NSUTF8StringEncoding] authenticatedData:nil error:&error];
107 XCTAssertNotNil(error, "Decrypting a short plaintext returned an error");
108 XCTAssertNil(shortDecrypt, "Decrypting a short plaintext returned nil");
109 error = nil;
110
111 // Check that we're adding enough entropy
112 NSData* ciphertextAgain = [key encryptData: plaintextData authenticatedData: nil error: &error];
113 XCTAssertNil(error, "No error encrypting plaintext");
114 XCTAssertNotNil(ciphertextAgain, "Received a ciphertext");
115 NSData* roundtripAgain = [key decryptData: ciphertextAgain authenticatedData: nil error: &error];
116 XCTAssertNil(error, "No error decrypting roundtrip");
117 XCTAssertNotNil(roundtripAgain, "Received a plaintext");
118 XCTAssertEqualObjects(plaintextData, roundtripAgain, "roundtripped data matches input");
119
120 XCTAssertNotEqualObjects(ciphertext, ciphertextAgain, "two encryptions of same input produce different outputs");
121
122 // Do it all again
123 CKKSKey* key2 = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
124 uuid:@"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6"
125 keyclass:SecCKKSKeyClassC
126 state: SecCKKSProcessedStateLocal
127 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
128 encodedCKRecord: nil
129 currentkey: true];
130
131 NSData* ciphertext2 = [key2 encryptData: plaintextData authenticatedData: nil error: &error];
132 XCTAssertNil(error, "No error encrypting plaintext");
133 XCTAssertNotNil(ciphertext2, "Received a ciphertext");
134 NSData* roundtrip2 = [key decryptData: ciphertext authenticatedData: nil error: &error];
135 XCTAssertNil(error, "No error decrypting roundtrip");
136 XCTAssertNotNil(roundtrip2, "Received a plaintext");
137 XCTAssertEqualObjects(plaintextData, roundtrip2, "roundtripped data matches input");
138
139 XCTAssertNotEqualObjects(ciphertext, ciphertext2, "ciphertexts with distinct keys are distinct");
140 }
141
142 - (void)testAuthEncryption {
143 NSString* plaintext = @"plaintext is plain";
144 NSData* plaintextData = [plaintext dataUsingEncoding: NSUTF8StringEncoding];
145
146 NSError* error = nil;
147
148 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="]
149 uuid:@"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7"
150 keyclass:SecCKKSKeyClassC
151 state:SecCKKSProcessedStateLocal
152 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
153 encodedCKRecord:nil
154 currentkey:true];
155 NSDictionary<NSString*, NSData*>* ad = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding] };
156
157 NSData* ciphertext = [key encryptData: plaintextData authenticatedData: ad error: &error];
158 XCTAssertNil(error, "No error encrypting plaintext");
159 XCTAssertNotNil(ciphertext, "Received a ciphertext");
160 NSData* roundtrip = [key decryptData: ciphertext authenticatedData: ad error: &error];
161 XCTAssertNil(error, "No error decrypting roundtrip");
162 XCTAssertNotNil(roundtrip, "Received a plaintext");
163 XCTAssertEqualObjects(plaintextData, roundtrip, "roundtripped data matches input");
164
165 // Without AD, decryption should fail
166 roundtrip = [key decryptData: ciphertext authenticatedData: nil error: &error];
167 XCTAssertNotNil(error, "Not passing in the authenticated data causes break");
168 XCTAssertNil(roundtrip, "on error, don't receive plaintext");
169 error = nil;
170
171 roundtrip = [key decryptData: ciphertext authenticatedData: @{ @"test": [@"wrongdata" dataUsingEncoding: NSUTF8StringEncoding] } error: &error];
172 XCTAssertNotNil(error, "Wrong authenticated data causes break");
173 XCTAssertNil(roundtrip, "on error, don't receive plaintext");
174 error = nil;
175 }
176
177 - (void)testDictionaryEncryption {
178 NSDictionary<NSString*, NSData*>* plaintext = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
179 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
180 NSDictionary<NSString*, NSData*>* roundtrip;
181
182 NSError* error = nil;
183
184 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
185 uuid:@"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6"
186 keyclass:SecCKKSKeyClassC
187 state: SecCKKSProcessedStateLocal
188 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
189 encodedCKRecord: nil
190 currentkey: true];
191
192 NSData* ciphertext = [CKKSItemEncrypter encryptDictionary: plaintext key: key.aessivkey authenticatedData: nil error: &error];
193 XCTAssertNil(error, "No error encrypting plaintext");
194 XCTAssertNotNil(ciphertext, "Received a ciphertext");
195 roundtrip = [CKKSItemEncrypter decryptDictionary: ciphertext key: key.aessivkey authenticatedData: nil error: &error];
196 XCTAssertNil(error, "No error decrypting roundtrip");
197 XCTAssertNotNil(roundtrip, "Received a plaintext");
198 XCTAssertEqualObjects(plaintext, roundtrip, "roundtripped dictionary matches input");
199
200 NSDictionary* authenticatedData = @{@"data": [@"auth" dataUsingEncoding: NSUTF8StringEncoding], @"moredata": [@"unauth" dataUsingEncoding: NSUTF8StringEncoding]};
201 NSDictionary* unauthenticatedData = @{@"data": [@"notequal" dataUsingEncoding: NSUTF8StringEncoding], @"moredata": [@"unauth" dataUsingEncoding: NSUTF8StringEncoding]};
202
203 NSData* authciphertext = [CKKSItemEncrypter encryptDictionary: plaintext key: key.aessivkey authenticatedData: authenticatedData error: &error];
204 XCTAssertNil(error, "No error encrypting plaintext with authenticated data");
205 XCTAssertNotNil(authciphertext, "Received a ciphertext");
206 roundtrip = [CKKSItemEncrypter decryptDictionary: authciphertext key: key.aessivkey authenticatedData: authenticatedData error: &error];
207 XCTAssertNil(error, "No error decrypting roundtrip with authenticated data");
208 XCTAssertNotNil(roundtrip, "Received a plaintext");
209 XCTAssertEqualObjects(plaintext, roundtrip, "roundtripped dictionary matches input");
210
211 roundtrip = [CKKSItemEncrypter decryptDictionary: authciphertext key: key.aessivkey authenticatedData: unauthenticatedData error: &error];
212 XCTAssertNotNil(error, "Error decrypting roundtrip with bad authenticated data");
213 XCTAssertNil(roundtrip, "Did not receive a plaintext when authenticated data is wrong");
214 }
215
216 - (void)testKeyWrapping {
217 CKKSAESSIVKey* key = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
218
219 CKKSAESSIVKey* keyToWrap = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
220
221 NSError* error = nil;
222
223 CKKSWrappedAESSIVKey* wrappedKey = [key wrapAESKey: keyToWrap error:&error];
224 XCTAssertNil(error, "no error wrapping key");
225 XCTAssertNotNil(wrappedKey, "wrapped key was returned");
226
227 XCTAssert(0 != memcmp(keyToWrap->key, (wrappedKey->key)+(CKKSWrappedKeySize - CKKSKeySize), CKKSKeySize), "wrapped key is different from original key");
228
229 CKKSAESSIVKey* unwrappedKey = [key unwrapAESKey: wrappedKey error:&error];
230 XCTAssertNil(error, "no error unwrapping key");
231 XCTAssertNotNil(unwrappedKey, "unwrapped key was returned");
232
233 XCTAssert(0 == memcmp(keyToWrap->key, unwrappedKey->key, CKKSKeySize), "unwrapped key matches original key");
234 XCTAssertEqualObjects(keyToWrap, unwrappedKey, "unwrapped key matches original key");
235 }
236
237 - (void)testKeyWrappingFailure {
238 CKKSAESSIVKey* key = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
239
240 CKKSAESSIVKey* keyToWrap = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
241
242 NSError* error = nil;
243
244 CKKSWrappedAESSIVKey* wrappedKey = [key wrapAESKey: keyToWrap error:&error];
245 XCTAssertNil(error, "no error wrapping key");
246 XCTAssertNotNil(wrappedKey, "wrapped key was returned");
247
248 XCTAssert(0 != memcmp(keyToWrap->key, (wrappedKey->key)+(CKKSWrappedKeySize - CKKSKeySize), CKKSKeySize), "wrapped key is different from original key");
249 wrappedKey->key[0] ^= 0x1;
250
251 CKKSAESSIVKey* unwrappedKey = [key unwrapAESKey: wrappedKey error:&error];
252 XCTAssertNotNil(error, "error unwrapping key");
253 XCTAssertNil(unwrappedKey, "unwrapped key was not returned in error case");
254 }
255
256 - (void)testKeyKeychainSaving {
257 NSError* error = nil;
258 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
259
260 XCTAssertTrue([tlk saveKeyMaterialToKeychain:false error:&error], "should be able to save key material to keychain (without stashing)");
261 XCTAssertNil(error, "tlk should save to database without error");
262 XCTAssertTrue([tlk loadKeyMaterialFromKeychain:&error], "Should be able to reload key material");
263 XCTAssertNil(error, "should be no error loading the tlk from the keychain");
264
265 XCTAssertTrue([tlk saveKeyMaterialToKeychain:false error:&error], "should be able to save key material to keychain (without stashing)");
266 XCTAssertNil(error, "tlk should save again to database without error");
267 XCTAssertTrue([tlk loadKeyMaterialFromKeychain:&error], "Should be able to reload key material");
268 XCTAssertNil(error, "should be no error loading the tlk from the keychain");
269
270 [tlk deleteKeyMaterialFromKeychain:&error];
271 XCTAssertNil(error, "tlk should be able to delete itself without error");
272
273 XCTAssertFalse([tlk loadKeyMaterialFromKeychain:&error], "Should not able to reload key material");
274 XCTAssertNotNil(error, "should be error loading the tlk from the keychain");
275 error = nil;
276
277 NSData* keydata = [@"asdf" dataUsingEncoding:NSUTF8StringEncoding];
278
279 // Add an item using no viewhint that will conflict with itself upon a SecItemUpdate (internal builds only)
280 NSMutableDictionary* query = [@{
281 (id)kSecClass : (id)kSecClassInternetPassword,
282 (id)kSecAttrAccessible: (id)kSecAttrAccessibleWhenUnlocked,
283 (id)kSecUseDataProtectionKeychain : @YES,
284 (id)kSecAttrAccessGroup: @"com.apple.security.ckks",
285 (id)kSecAttrDescription: tlk.keyclass,
286 (id)kSecAttrServer: tlk.zoneID.zoneName,
287 (id)kSecAttrAccount: tlk.uuid,
288 (id)kSecAttrPath: tlk.parentKeyUUID,
289 (id)kSecAttrIsInvisible: @YES,
290 (id)kSecValueData : keydata,
291 (id)kSecAttrSynchronizable : (id)kCFBooleanTrue,
292 } mutableCopy];
293 XCTAssertEqual(errSecSuccess, SecItemAdd((__bridge CFDictionaryRef)query, NULL), "Should be able to add a conflicting item");
294
295 XCTAssertTrue([tlk saveKeyMaterialToKeychain:false error:&error], "should be able to save key material to keychain (without stashing)");
296 XCTAssertNil(error, "tlk should save to database without error");
297 XCTAssertTrue([tlk loadKeyMaterialFromKeychain:&error], "Should be able to reload key material");
298 XCTAssertNil(error, "should be no error loading the tlk from the keychain");
299
300 XCTAssertTrue([tlk saveKeyMaterialToKeychain:false error:&error], "should be able to save key material to keychain (without stashing)");
301 XCTAssertNil(error, "tlk should save again to database without error");
302 XCTAssertTrue([tlk loadKeyMaterialFromKeychain:&error], "Should be able to reload key material");
303 XCTAssertNil(error, "should be no error loading the tlk from the keychain");
304 }
305
306 - (void)testKeyHierarchy {
307 NSError* error = nil;
308 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
309 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
310
311 [tlk saveToDatabase:&error];
312 [tlk saveKeyMaterialToKeychain:&error];
313 XCTAssertNil(error, "tlk saved to database without error");
314
315 CKKSKey* level1 = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassA error:&error];
316 level1.encodedCKRecord = testCKRecord;
317 XCTAssertNotNil(level1, "level 1 key created");
318 XCTAssertNil(error, "level 1 key created");
319
320 [level1 saveToDatabase:&error];
321 XCTAssertNil(error, "level 1 key saved to database without error");
322
323 CKKSKey* level2 = [CKKSKey randomKeyWrappedByParent: level1 error:&error];
324 level2.encodedCKRecord = testCKRecord;
325 XCTAssertNotNil(level2, "level 2 key created");
326 XCTAssertNil(error, "no error creating level 2 key");
327 [level2 saveToDatabase:&error];
328 XCTAssertNil(error, "level 2 key saved to database without error");
329
330 NSString* level2UUID = level2.uuid;
331
332 // Fetch the level2 key from the database.
333 CKKSKey* extractedkey = [CKKSKey fromDatabase:level2UUID zoneID:self.testZoneID error:&error];
334 [extractedkey unwrapViaKeyHierarchy: &error];
335 XCTAssertNotNil(extractedkey, "could fetch key again");
336 XCTAssertNil(error, "no error fetching key from database");
337
338 CKKSAESSIVKey* extracedaeskey = [extractedkey ensureKeyLoaded:&error];
339 XCTAssertNotNil(extractedkey, "fetched key could unwrap");
340 XCTAssertNil(error, "no error forcing unwrap on fetched key");
341
342 XCTAssertEqualObjects(level2.aessivkey, extracedaeskey, @"fetched aes key is equal to saved key");
343 }
344
345 - (void)ensureKeychainSaveLoad: (CKKSKey*) key {
346 NSError* error = nil;
347 [key saveToDatabase:&error];
348 XCTAssertNil(error, "no error saving to database");
349 [key saveKeyMaterialToKeychain:&error];
350 XCTAssertNil(error, "no error saving to keychain");
351
352 CKKSKey* loadedKey = [CKKSKey fromDatabase:key.uuid zoneID:self.testZoneID error:&error];
353 XCTAssertNil(error, "no error loading from database");
354 XCTAssertNotNil(loadedKey, "Received an item back from the database");
355
356 XCTAssert([loadedKey loadKeyMaterialFromKeychain:&error], "could load key material back from keychain");
357 XCTAssertNil(error, "no error loading key from keychain");
358
359 XCTAssertEqualObjects(loadedKey.aessivkey, key.aessivkey, "Loaded key is identical after save/load");
360 }
361
362 - (void)testKeychainSave {
363 NSError* error = nil;
364 NSData* testCKRecord = [@"nonsense" dataUsingEncoding:NSUTF8StringEncoding];
365 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
366 [self ensureKeychainSaveLoad: tlk];
367
368 // Ensure that Class A and Class C can do the same thing
369 CKKSKey* classA = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassA error:&error];
370 classA.encodedCKRecord = testCKRecord;
371 XCTAssertNil(error, "No error creating random class A key");
372 [self ensureKeychainSaveLoad: classA];
373 CKKSKey* classC = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassC error:&error];
374 classC.encodedCKRecord = testCKRecord;
375 XCTAssertNil(error, "No error creating random class C key");
376 [self ensureKeychainSaveLoad: classC];
377 }
378
379 - (void)testCKKSKeyProtobuf {
380 NSError* error = nil;
381 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
382
383 NSData* tlkPersisted = [tlk serializeAsProtobuf:&error];
384 XCTAssertNil(error, "Shouldn't have been an error serializing to protobuf");
385 XCTAssertNotNil(tlkPersisted, "Should have gotten some protobuf data back");
386
387 CKKSKey* otherKey = [CKKSKey loadFromProtobuf:tlkPersisted error:&error];
388 XCTAssertNil(error, "Shouldn't have been an error serializing from protobuf");
389 XCTAssertNotNil(otherKey, "Should have gotten some protobuf data back");
390
391 XCTAssertEqualObjects(tlk.uuid, otherKey.uuid, "Should have gotten the same UUID");
392 XCTAssertEqualObjects(tlk.keyclass, otherKey.keyclass, "Should have gotten the same key class");
393 XCTAssertEqualObjects(tlk.zoneID, otherKey.zoneID, "Should have gotten the same zoneID");
394 XCTAssertEqualObjects(tlk.aessivkey, otherKey.aessivkey, "Should have gotten the same underlying key back");
395 XCTAssertEqualObjects(tlk, otherKey, "Should have gotten the same key");
396 }
397
398 - (BOOL)tryDecryptWithProperAuthData:(CKKSItem*)ciphertext plaintext:(NSDictionary<NSString*, NSData*>*)plaintext {
399 NSDictionary<NSString*, NSData*>* roundtrip;
400 NSError *error = nil;
401 roundtrip = [CKKSItemEncrypter decryptItemToDictionary: (CKKSItem*) ciphertext error: &error];
402 XCTAssertNil(error, "No error decrypting roundtrip");
403 XCTAssertNotNil(roundtrip, "Received a plaintext");
404 XCTAssertEqualObjects(plaintext, roundtrip, "roundtripped dictionary matches input");
405 return error == nil && roundtrip != nil && [plaintext isEqualToDictionary:roundtrip];
406 }
407
408 - (BOOL)tryDecryptWithBrokenAuthData:(CKKSItem *)ciphertext {
409 NSDictionary<NSString*, NSData*>* brokenAuthentication;
410 NSError *error = nil;
411 brokenAuthentication = [CKKSItemEncrypter decryptItemToDictionary: (CKKSItem*) ciphertext error: &error];
412 XCTAssertNotNil(error, "Error exists decrypting ciphertext with bad authenticated data: %@", error);
413 XCTAssertNil(brokenAuthentication, "Did not receive a plaintext if authenticated data was mucked with");
414 return error != nil && brokenAuthentication == nil;
415 }
416
417 - (void)testItemDictionaryEncryption {
418 NSDictionary<NSString*, NSData*>* plaintext = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
419 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
420 NSError* error = nil;
421 NSString *uuid = @"8b2aeb7f-4af3-43e9-b6e6-70d5c728ebf7";
422
423 CKKSKey* key = [self fakeTLK:self.testZoneID];
424 [key saveToDatabase: &error];
425 [key saveKeyMaterialToKeychain:&error];
426 XCTAssertNil(error, @"could save the fake TLK to the database");
427
428 CKKSItem* ciphertext = [CKKSItemEncrypter encryptCKKSItem: [[CKKSItem alloc] initWithUUID:uuid
429 parentKeyUUID:key.uuid
430 zoneID:self.testZoneID]
431 dataDictionary:plaintext
432 updatingCKKSItem:nil
433 parentkey:key
434 error:&error];
435 XCTAssertNil(error, "No error encrypting plaintext");
436 XCTAssertNotNil(ciphertext, "Received a ciphertext");
437 XCTAssertEqual(ciphertext.encver, currentCKKSItemEncryptionVersion, "Encryption sets the current protocol version");
438
439 [self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext];
440
441 // Make sure these fields are authenticated and that authentication works.
442 // Messing with them should make the item not decrypt.
443 ciphertext.generationCount = 100;
444 XCTAssertTrue([self tryDecryptWithBrokenAuthData:ciphertext], "Decryption with broken authentication data fails");
445 ciphertext.generationCount = 0;
446 XCTAssertTrue([self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext], "Decryption with authentication data succeeds");
447
448 ciphertext.encver += 1;
449 XCTAssertTrue([self tryDecryptWithBrokenAuthData:ciphertext], "Decryption with broken authentication data fails");
450 ciphertext.encver -= 1;
451 XCTAssertTrue([self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext], "Decryption with authentication data succeeds");
452
453 ciphertext.uuid = @"x";
454 XCTAssertTrue([self tryDecryptWithBrokenAuthData:ciphertext], "Decryption with broken authentication data fails");
455 ciphertext.uuid = uuid;
456 XCTAssertTrue([self tryDecryptWithProperAuthData:ciphertext plaintext:plaintext], "Decryption with authentication data succeeds");
457 }
458
459 - (void)testEncryptionVersions {
460 NSDictionary<NSString*, NSData*>* plaintext = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
461 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
462 NSDictionary<NSString*, NSData*>* output;
463 NSError *error = nil;
464 NSData* data = [NSPropertyListSerialization dataWithPropertyList:plaintext
465 format:NSPropertyListBinaryFormat_v1_0
466 options:0
467 error:&error];
468 XCTAssertNil(error);
469 CKKSKey* key = [self fakeTLK:self.testZoneID];
470 [key saveToDatabase: &error];
471 [key saveKeyMaterialToKeychain:&error];
472 XCTAssertNil(error, @"could save the fake TLK to the database");
473
474 CKKSAESSIVKey* keyToWrap = [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="];
475 CKKSWrappedAESSIVKey* wrappedKey = [key wrapAESKey: keyToWrap error:&error];
476 XCTAssertNil(error, "no error wrapping key");
477 XCTAssertNotNil(wrappedKey, "wrapped key was returned");
478 CKKSItem* baseitem = [[CKKSItem alloc] initWithUUID:@"abc"
479 parentKeyUUID:key.uuid
480 zoneID:self.testZoneID
481 encItem:data
482 wrappedkey:wrappedKey
483 generationCount:0
484 encver:CKKSItemEncryptionVersionNone];
485 XCTAssertNotNil(baseitem, "Constructed CKKSItem");
486
487 // First try versionNone. Should fail, we don't support unencrypted data
488 output = [CKKSItemEncrypter decryptItemToDictionary:baseitem error:&error];
489 XCTAssert(error, "Did not failed to decrypt v0 item");
490 XCTAssertNil(output, "Did not failed to decrypt v0 item");
491 error = nil;
492 output = nil;
493
494 // Then try version1. Should take actual decryption path and fail because there's no properly encrypted data.
495 baseitem.encver = CKKSItemEncryptionVersion1;
496 output = [CKKSItemEncrypter decryptItemToDictionary:baseitem error:&error];
497 XCTAssertNotNil(error, "Taking v1 codepath without encrypted item fails");
498 XCTAssertEqualObjects(error.localizedDescription, @"could not ccsiv_crypt", "Error specifically failure to ccsiv_crypt");
499 XCTAssertNil(output, "Did not receive output from failed decryption call");
500 error = nil;
501 output = nil;
502
503 // Finally, some unknown version should fail immediately
504 baseitem.encver = 100;
505 output = [CKKSItemEncrypter decryptItemToDictionary:baseitem error:&error];
506 XCTAssertNotNil(error);
507 NSString *errstr = [NSString stringWithFormat:@"%@", error.localizedDescription];
508 NSString *expected = @"Unrecognized encryption version: 100";
509 XCTAssertEqualObjects(expected, errstr, "Error is specific to unrecognized version failure");
510 XCTAssertNil(output);
511 }
512
513 - (void)testKeychainPersistence {
514
515 NSString* plaintext = @"plaintext is plain";
516 NSData* plaintextData = [plaintext dataUsingEncoding: NSUTF8StringEncoding];
517
518 NSError* error = nil;
519
520 NSString* uuid = @"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6";
521
522 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
523 uuid:uuid
524 keyclass:SecCKKSKeyClassA
525 state:SecCKKSProcessedStateLocal
526 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
527 encodedCKRecord: nil
528 currentkey: true];
529
530 NSData* ciphertext = [key encryptData: plaintextData authenticatedData: nil error: &error];
531 XCTAssertNil(error, "No error encrypting plaintext");
532 XCTAssertNotNil(ciphertext, "Received a ciphertext");
533 NSData* roundtrip = [key decryptData: ciphertext authenticatedData: nil error: &error];
534 XCTAssertNil(error, "No error decrypting roundtrip");
535 XCTAssertNotNil(roundtrip, "Received a plaintext");
536 XCTAssertEqualObjects(plaintextData, roundtrip, "roundtripped data matches input");
537
538 // Check that there is no key material in the keychain
539 CKKSKey* reloadedKey = [CKKSKey keyFromKeychain:uuid
540 parentKeyUUID:uuid
541 keyclass:SecCKKSKeyClassA
542 state:SecCKKSProcessedStateLocal
543 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
544 encodedCKRecord:nil
545 currentkey:true
546 error:&error];
547
548 XCTAssertNotNil(error, "error exists when there's nothing in the keychain");
549 XCTAssertNil(reloadedKey, "no key object when there's nothing in the keychain");
550 error = nil;
551
552 [key saveKeyMaterialToKeychain:&error];
553 XCTAssertNil(error, "Could save key material to keychain");
554
555 // Reload the key material and check that it works
556 reloadedKey = [CKKSKey keyFromKeychain:uuid
557 parentKeyUUID:uuid
558 keyclass:SecCKKSKeyClassA
559 state:SecCKKSProcessedStateLocal
560 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
561 encodedCKRecord:nil
562 currentkey:true
563 error:&error];
564
565 XCTAssertNil(error, "No error loading key from keychain");
566 XCTAssertNotNil(reloadedKey, "Could load key from keychain");
567
568 NSData* ciphertext2 = [reloadedKey encryptData: plaintextData authenticatedData: nil error: &error];
569 XCTAssertNil(error, "No error encrypting plaintext");
570 XCTAssertNotNil(ciphertext2, "Received a ciphertext");
571 NSData* roundtrip2 = [reloadedKey decryptData: ciphertext2 authenticatedData: nil error: &error];
572 XCTAssertNil(error, "No error decrypting roundtrip");
573 XCTAssertNotNil(roundtrip2, "Received a plaintext");
574 XCTAssertEqualObjects(plaintextData, roundtrip2, "roundtripped data matches input");
575
576 XCTAssertEqualObjects(key.aessivkey, reloadedKey.aessivkey, "reloaded AES key is equal to generated key");
577
578 [key deleteKeyMaterialFromKeychain: &error];
579 XCTAssertNil(error, "could delete key material from keychain");
580
581 // Check that there is no key material in the keychain
582 // Note that TLKs will be stashed (and deleteKeyMaterial won't delete the stash), and so this test would fail for a TLK
583
584 reloadedKey = [CKKSKey keyFromKeychain:uuid
585 parentKeyUUID:uuid
586 keyclass:SecCKKSKeyClassA
587 state:SecCKKSProcessedStateLocal
588 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
589 encodedCKRecord:nil
590 currentkey:true
591 error:&error];
592
593 XCTAssertNotNil(error, "error exists when there's nothing in the keychain");
594 XCTAssertNil(reloadedKey, "no key object when there's nothing in the keychain");
595 error = nil;
596 }
597
598 - (void)testCKKSKeyTrialSelfWrapped {
599 NSError* error = nil;
600 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
601 XCTAssertTrue([tlk wrapsSelf], "TLKs should wrap themselves");
602
603 CKRecord* record = [tlk CKRecordWithZoneID:self.testZoneID];
604 XCTAssertNotNil(record, "TLKs should know how to turn themselves into CKRecords");
605 CKKSKey* receivedTLK = [[CKKSKey alloc] initWithCKRecord:record];
606 XCTAssertNotNil(receivedTLK, "Keys should know how to recover themselves from CKRecords");
607
608 XCTAssertTrue([receivedTLK wrapsSelf], "TLKs should wrap themselves, even when received from CloudKit");
609
610 XCTAssertFalse([receivedTLK ensureKeyLoaded:&error], "Received keys can't load themselves when there's no key data");
611 XCTAssertNotNil(error, "Error should exist when a key fails to load itself");
612 error = nil;
613
614 XCTAssertTrue([receivedTLK trySelfWrappedKeyCandidate:tlk.aessivkey error:&error], "Shouldn't be an error when we give a CKKSKey its key");
615 XCTAssertNil(error, "Shouldn't be an error giving a CKKSKey its key material");
616
617 XCTAssertTrue([receivedTLK ensureKeyLoaded:&error], "Once a CKKSKey has its key material, it doesn't need to load it again");
618 XCTAssertNil(error, "Shouldn't be an error loading a loaded CKKSKey");
619 }
620
621 - (void)testCKKSKeyTrialSelfWrappedFailure {
622 NSError* error = nil;
623 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
624 XCTAssertTrue([tlk wrapsSelf], "TLKs should wrap themselves");
625
626 CKRecord* record = [tlk CKRecordWithZoneID:self.testZoneID];
627 XCTAssertNotNil(record, "TLKs should know how to turn themselves into CKRecords");
628 CKKSKey* receivedTLK = [[CKKSKey alloc] initWithCKRecord:record];
629 XCTAssertNotNil(receivedTLK, "Keys should know how to recover themselves from CKRecords");
630
631 XCTAssertTrue([receivedTLK wrapsSelf], "TLKs should wrap themselves, even when received from CloudKit");
632
633 XCTAssertFalse([receivedTLK ensureKeyLoaded:&error], "Received keys can't load themselves when there's no key data");
634 XCTAssertNotNil(error, "Error should exist when a key fails to load itself");
635 error = nil;
636
637 XCTAssertFalse([receivedTLK trySelfWrappedKeyCandidate:[[CKKSAESSIVKey alloc] initWithBase64: @"aaaaaZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="] error:&error], "Should be an error when we give a CKKSKey the wrong key");
638 XCTAssertNotNil(error, "Should be an error giving a CKKSKey the wrong key material");
639
640 XCTAssertFalse([receivedTLK ensureKeyLoaded:&error], "Received keys can't load themselves when there's no key data");
641 XCTAssertNotNil(error, "Error should exist when a key fails to load itself");
642 error = nil;
643 }
644
645 - (void)testCKKSKeyTrialNotSelfWrappedFailure {
646 NSError* error = nil;
647 CKKSKey* tlk = [self fakeTLK:self.testZoneID];
648 XCTAssertTrue([tlk wrapsSelf], "TLKs should wrap themselves");
649
650 CKKSKey* classC = [CKKSKey randomKeyWrappedByParent: tlk keyclass:SecCKKSKeyClassC error:&error];
651 XCTAssertFalse([classC wrapsSelf], "Wrapped keys should not wrap themselves");
652
653 XCTAssertTrue([classC ensureKeyLoaded:&error], "Once a CKKSKey has its key material, it doesn't need to load it again");
654 XCTAssertNil(error, "Shouldn't be an error loading a loaded CKKSKey");
655
656 XCTAssertFalse([classC trySelfWrappedKeyCandidate:classC.aessivkey error:&error], "Should be an error when we attempt to trial a key on a non-self-wrapped key");
657 XCTAssertNotNil(error, "Should be an error giving a CKKSKey the wrong key material");
658 XCTAssertEqual(error.code, CKKSKeyNotSelfWrapped, "Should have gotten CKKSKeyNotSelfWrapped as an error");
659 error = nil;
660
661 // But, since we didn't throw away its key, it's still loaded
662 XCTAssertTrue([classC ensureKeyLoaded:&error], "Once a CKKSKey has its key material, it doesn't need to load it again");
663 XCTAssertNil(error, "Shouldn't be an error loading a loaded CKKSKey");
664 }
665
666 - (BOOL)padAndUnpadDataWithLength:(NSUInteger)dataLength blockSize:(NSUInteger)blockSize extra:(BOOL)extra {
667 // Test it works
668 NSMutableData *data = [NSMutableData dataWithLength:dataLength];
669 memset((unsigned char *)[data mutableBytes], 0x55, dataLength);
670 NSMutableData *orig = [data mutableCopy];
671 NSData *padded = [CKKSItemEncrypter padData:data blockSize:blockSize additionalBlock:extra];
672 XCTAssertNotNil(padded, "Padding never returns nil");
673 XCTAssertEqualObjects(data, orig, "Input object unmodified");
674 XCTAssertTrue(padded.length % blockSize == 0, "Padded data aligns on %lu-byte blocksize", (unsigned long)blockSize);
675 XCTAssertTrue(padded.length > data.length, "At least one byte of padding has been added");
676 NSData *unpadded = [CKKSItemEncrypter removePaddingFromData:padded];
677 XCTAssertNotNil(unpadded, "Successfully removed padding again");
678
679 // Test it fails by poking some byte in the padding
680 NSMutableData *glitch = [NSMutableData dataWithData:padded];
681 NSUInteger offsetFromTop = glitch.length - arc4random_uniform((unsigned)(glitch.length - data.length)) - 1;
682 uint8_t poke = ((uint8_t)arc4random_uniform(0xFF) & 0x7E) + 1; // This gets most of the values while excluding 0 and 0x80
683 unsigned char *bytes = [glitch mutableBytes];
684 bytes[offsetFromTop] = poke;
685 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);
686
687 return padded && unpadded && [unpadded isEqual:data];
688 }
689
690 - (void)testPadding {
691 [self runPaddingTest:NO];
692 [self runPaddingTest:YES];
693
694 NSData *data = nil;
695 XCTAssertNil([CKKSItemEncrypter removePaddingFromData:[NSData data]], "zero data valid ?");
696
697 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80" length:1]];
698 XCTAssert(data && data.length == 0, "data wrong size");
699
700 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x00" length:2]];
701 XCTAssert(data && data.length == 0, "data wrong size");
702 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x00\x00" length:3]];
703 XCTAssert(data && data.length == 0, "data wrong size");
704 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x80\x80" length:3]];
705 XCTAssert(data && data.length == 2, "data wrong size");
706 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x80\x80\x00" length:3]];
707 XCTAssert(data && data.length == 1, "data wrong size");
708 data = [CKKSItemEncrypter removePaddingFromData:[NSData dataWithBytes:"\x00\x80\x00" length:3]];
709 XCTAssert(data && data.length == 1, "data wrong size");
710
711 }
712
713 - (void)runPaddingTest:(BOOL)extra {
714
715 // Aligned, arbitrary lengths
716 for (int idx = 1; idx <= 128; ++idx) {
717 XCTAssertTrue([self padAndUnpadDataWithLength:idx blockSize:idx extra:extra], "Padding aligned data succeeds");
718 }
719
720 // Off-by-one, arbitrary lengths
721 for (int idx = 1; idx <= 128; ++idx) {
722 XCTAssertTrue([self padAndUnpadDataWithLength:idx - 1 blockSize:idx extra:extra], "Padding aligned data succeeds");
723 XCTAssertTrue([self padAndUnpadDataWithLength:idx + 1 blockSize:idx extra:extra], "Padding aligned data succeeds");
724 }
725
726 // Misaligned, arbitrary lengths
727 for (int idx = 1; idx <= 1000; ++idx) {
728 NSUInteger dataSize = arc4random_uniform(128) + 1;
729 NSUInteger blockSize = arc4random_uniform(128) + 1;
730 XCTAssertTrue([self padAndUnpadDataWithLength:dataSize blockSize:blockSize extra:extra], "Padding data lenght %lu to blockSize %lu succeeds", (unsigned long)dataSize, (unsigned long)blockSize);
731 }
732
733 // Special case: blocksize 0 results in 1 byte of padding always
734 NSMutableData *data = [NSMutableData dataWithLength:23];
735 memset((unsigned char *)[data mutableBytes], 0x55, 23);
736 NSData *padded = [CKKSItemEncrypter padData:data blockSize:0 additionalBlock:extra];
737 XCTAssertNotNil(padded, "Padding never returns nil");
738 XCTAssertTrue(padded.length == data.length + extra ? 2 : 1, "One byte of padding has been added, 2 if extra padding");
739 NSData *unpadded = [CKKSItemEncrypter removePaddingFromData:padded];
740 XCTAssertNotNil(unpadded, "Successfully removed padding again");
741 XCTAssertEqualObjects(data, unpadded, "Data effectively unmodified through padding-unpadding trip");
742
743 // Nonpadded data
744 unpadded = [CKKSItemEncrypter removePaddingFromData:data];
745 XCTAssertNil(unpadded, "Cannot remove padding where none exists");
746
747 // Feeding nil
748 #pragma clang diagnostic push
749 #pragma clang diagnostic ignored "-Wnonnull"
750 padded = [CKKSItemEncrypter padData:nil blockSize:0 additionalBlock:extra];
751 XCTAssertNotNil(padded, "padData always returns a data object");
752 XCTAssertEqual(padded.length, extra ? 2ul : 1ul, "Length of padded nil object is padding byte only--two if extra");
753 unpadded = [CKKSItemEncrypter removePaddingFromData:nil];
754 XCTAssertNil(unpadded, "Removing padding from nil is senseless");
755 #pragma clang diagnostic pop
756 }
757
758 - (BOOL)encryptAndDecryptDictionary:(NSDictionary<NSString*, NSData*>*)data key:(CKKSKey *)key {
759 NSDictionary<NSString*, NSData*>* roundtrip;
760 NSError *error = nil;
761 NSData* ciphertext = [CKKSItemEncrypter encryptDictionary: data key: key.aessivkey authenticatedData: nil error: &error];
762 XCTAssertNil(error, "No error encrypting plaintext");
763 XCTAssertNotNil(ciphertext, "Received a ciphertext");
764 // AES-SIV adds 32 bytes, need to subtract them
765 XCTAssertTrue((ciphertext.length - 32) % SecCKKSItemPaddingBlockSize == 0, "Ciphertext aligned on %lu-byte boundary", (unsigned long)SecCKKSItemPaddingBlockSize);
766 roundtrip = [CKKSItemEncrypter decryptDictionary: ciphertext key: key.aessivkey authenticatedData: nil error: &error];
767 XCTAssertNil(error, "No error decrypting roundtrip");
768 XCTAssertNotNil(roundtrip, "Received a plaintext");
769 XCTAssertEqualObjects(data, roundtrip, "roundtripped dictionary matches input");
770 return (ciphertext.length - 32) % SecCKKSItemPaddingBlockSize == 0 && roundtrip && error == nil && [data isEqualToDictionary:roundtrip];
771 }
772
773 - (void)testDictionaryPadding {
774 // Pad a bunch of bytes to nearest boundary
775 NSDictionary<NSString*, NSData*>* unaligned_74 = @{ @"test": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
776 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
777 // Pad precisely one byte
778 NSDictionary<NSString*, NSData*>* unaligned_79 = @{ @"test12345": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
779 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
780 // Already on boundary, pad until next boundary
781 NSDictionary<NSString*, NSData*>* aligned_80 = @{ @"test123456": [@"data" dataUsingEncoding: NSUTF8StringEncoding],
782 @"more": [@"testdata" dataUsingEncoding: NSUTF8StringEncoding] };
783 CKKSKey* key = [[CKKSKey alloc] initSelfWrappedWithAESKey: [[CKKSAESSIVKey alloc] initWithBase64: @"uImdbZ7Zg+6WJXScTnRBfNmoU1UiMkSYxWc+d1Vuq3IFn2RmTRkTdWTe3HmeWo1pAomqy+upK8KHg2PGiRGhqg=="]
784 uuid:@"f5e7f20f-0885-48f9-b75d-9f0cfd2171b6"
785 keyclass:SecCKKSKeyClassC
786 state:SecCKKSProcessedStateLocal
787 zoneID:[[CKRecordZoneID alloc] initWithZoneName:@"testzone" ownerName:CKCurrentUserDefaultName]
788 encodedCKRecord:nil
789 currentkey:true];
790
791 XCTAssertTrue([self encryptAndDecryptDictionary:unaligned_74 key:key], "Roundtrip with unaligned data succeeds");
792 XCTAssertTrue([self encryptAndDecryptDictionary:unaligned_79 key:key], "Roundtrip with unaligned data succeeds");
793 XCTAssertTrue([self encryptAndDecryptDictionary:aligned_80 key:key], "Roundtrip with aligned data succeeds");
794 }
795
796 - (void)testCKKSKeychainBackedKeySerialization {
797 NSError* error = nil;
798 CKKSKeychainBackedKey* tlk = [self fakeTLK:self.testZoneID].keycore;
799 CKKSKeychainBackedKey* classC = [CKKSKeychainBackedKey randomKeyWrappedByParent:tlk keyclass:SecCKKSKeyClassC error:&error];
800 XCTAssertNil(error, "Should be no error creating classC key");
801
802 XCTAssertTrue([tlk saveKeyMaterialToKeychain:&error], "Should be able to save tlk key material to keychain");
803 XCTAssertNil(error, "Should be no error saving key material");
804
805 XCTAssertTrue([classC saveKeyMaterialToKeychain:&error], "Should be able to save classC key material to keychain");
806 XCTAssertNil(error, "Should be no error saving key material");
807
808 NSKeyedArchiver* encoder = [[NSKeyedArchiver alloc] initRequiringSecureCoding:YES];
809 [encoder encodeObject:tlk forKey:@"tlk"];
810 [encoder encodeObject:classC forKey:@"classC"];
811 NSData* data = encoder.encodedData;
812 XCTAssertNotNil(data, "encoding should have produced some data");
813
814 NSKeyedUnarchiver* decoder = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:nil];
815 CKKSKeychainBackedKey* decodedTLK = [decoder decodeObjectOfClass: [CKKSKeychainBackedKey class] forKey:@"tlk"];
816 CKKSKeychainBackedKey* decodedClassC = [decoder decodeObjectOfClass: [CKKSKeychainBackedKey class] forKey:@"classC"];
817
818 XCTAssertEqualObjects(tlk, decodedTLK, "TLKs should transit NSSecureCoding without changes");
819 XCTAssertEqualObjects(classC, decodedClassC, "Class C keys should transit NSSecureCoding without changes");
820
821 // Now, check that they can load the key material
822
823 XCTAssertTrue([decodedTLK loadKeyMaterialFromKeychain:&error], "Should be able to load tlk key material from keychain");
824 XCTAssertNil(error, "Should be no error from loading key material");
825
826 XCTAssertTrue([decodedClassC loadKeyMaterialFromKeychain:&error], "Should be able to load classC key material from keychain");
827 XCTAssertNil(error, "Should be no error from loading key material");
828 }
829
830 @end
831
832 #endif // OCTAGON