1 /*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <algorithm>
18 #include <utility>
19
20 #include <gtest/gtest.h>
21
22 #include <openssl/engine.h>
23 #include <openssl/rand.h>
24
25 #include <android-base/logging.h>
26
27 #include <keymaster/android_keymaster_utils.h>
28 #include <keymaster/authorization_set.h>
29 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
30 #include <keymaster/key_blob_utils/integrity_assured_key_blob.h>
31 #include <keymaster/keymaster_tags.h>
32 #include <keymaster/km_openssl/software_random_source.h>
33
34 #include "android_keymaster_test_utils.h"
35
36 namespace keymaster::test {
37
38 namespace {
39
40 const uint8_t master_key_data[16] = {};
41 const uint8_t key_data[5] = {21, 22, 23, 24, 25};
42
43 } // namespace
44
45 class KeyBlobTest : public ::testing::TestWithParam<AuthEncryptedBlobFormat>,
46 public SoftwareRandomSource {
47 protected:
KeyBlobTest()48 KeyBlobTest()
49 : key_material_(key_data, array_length(key_data)),
50 master_key_(master_key_data, array_length(master_key_data)),
51 secure_deletion_data_(SecureDeletionData()) {
52 hw_enforced_.push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
53 hw_enforced_.push_back(TAG_KEY_SIZE, 256);
54 hw_enforced_.push_back(TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE);
55 hw_enforced_.push_back(TAG_MIN_SECONDS_BETWEEN_OPS, 10);
56 hw_enforced_.push_back(TAG_ALL_USERS);
57 hw_enforced_.push_back(TAG_NO_AUTH_REQUIRED);
58 hw_enforced_.push_back(TAG_ORIGIN, KM_ORIGIN_GENERATED);
59
60 sw_enforced_.push_back(TAG_ACTIVE_DATETIME, 10);
61 sw_enforced_.push_back(TAG_ORIGINATION_EXPIRE_DATETIME, 100);
62 sw_enforced_.push_back(TAG_CREATION_DATETIME, 10);
63
64 secure_deletion_data_.factory_reset_secret.Reinitialize("Factory reset secret",
65 sizeof("Factory reset secret"));
66 secure_deletion_data_.secure_deletion_secret.Reinitialize("Secure deletion secret",
67 sizeof("Secure deletion secret"));
68
69 hidden_.push_back(TAG_ROOT_OF_TRUST, "foo", 3);
70 hidden_.push_back(TAG_APPLICATION_ID, "my_app", 6);
71 }
72
Encrypt(AuthEncryptedBlobFormat format)73 keymaster_error_t Encrypt(AuthEncryptedBlobFormat format) {
74 auto result = EncryptKey(key_material_, format, hw_enforced_, sw_enforced_, hidden_,
75 secure_deletion_data_, master_key_, *this);
76 if (!result) return result.error();
77 encrypted_key_ = std::move(*result);
78 return KM_ERROR_OK;
79 }
80
Decrypt()81 keymaster_error_t Decrypt() {
82 auto result =
83 DecryptKey(std::move(deserialized_key_), hidden_, secure_deletion_data_, master_key_);
84 if (!result) return result.error();
85 decrypted_plaintext_ = std::move(*result);
86 return KM_ERROR_OK;
87 }
88
Serialize(uint32_t secure_deletion_key_slot=0)89 keymaster_error_t Serialize(uint32_t secure_deletion_key_slot = 0) {
90 auto result = SerializeAuthEncryptedBlob(encrypted_key_, hw_enforced_, sw_enforced_,
91 secure_deletion_key_slot);
92 if (!result) return result.error();
93 serialized_blob_ = std::move(*result);
94 return KM_ERROR_OK;
95 }
96
Deserialize()97 keymaster_error_t Deserialize() {
98 auto result = DeserializeAuthEncryptedBlob(serialized_blob_);
99 if (!result) return result.error();
100 deserialized_key_ = std::move(*result);
101 return KM_ERROR_OK;
102 }
103
104 // Encryption inputs
105 AuthorizationSet hw_enforced_;
106 AuthorizationSet sw_enforced_;
107 AuthorizationSet hidden_;
108 KeymasterKeyBlob key_material_;
109 KeymasterKeyBlob master_key_;
110 SecureDeletionData secure_deletion_data_;
111
112 // Encryption output
113 EncryptedKey encrypted_key_;
114
115 // Serialization output
116 KeymasterKeyBlob serialized_blob_;
117
118 // Deserialization output
119 DeserializedKey deserialized_key_;
120
121 // Decryption output.
122 KeymasterKeyBlob decrypted_plaintext_;
123 };
124
TEST_P(KeyBlobTest,EncryptDecrypt)125 TEST_P(KeyBlobTest, EncryptDecrypt) {
126 uint32_t key_slot = static_cast<uint32_t>(rand());
127
128 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
129 ASSERT_EQ(KM_ERROR_OK, Serialize(key_slot));
130
131 // key_data shouldn't be anywhere in the blob, ciphertext should.
132 EXPECT_EQ(serialized_blob_.end(), std::search(serialized_blob_.begin(), serialized_blob_.end(),
133 key_material_.begin(), key_material_.end()));
134 EXPECT_NE(serialized_blob_.end(),
135 std::search(serialized_blob_.begin(), serialized_blob_.end(),
136 encrypted_key_.ciphertext.begin(), encrypted_key_.ciphertext.end()));
137
138 KmErrorOr<DeserializedKey> deserialized = DeserializeAuthEncryptedBlob(serialized_blob_);
139 ASSERT_TRUE(deserialized.isOk());
140 EXPECT_EQ(hw_enforced_, deserialized->hw_enforced);
141 EXPECT_EQ(sw_enforced_, deserialized->sw_enforced);
142 if (GetParam() == AES_GCM_WITH_SECURE_DELETION ||
143 GetParam() == AES_GCM_WITH_SECURE_DELETION_VERSIONED) {
144 EXPECT_EQ(key_slot, deserialized->key_slot);
145 } else {
146 EXPECT_EQ(0U, deserialized->key_slot);
147 }
148
149 KmErrorOr<KeymasterKeyBlob> plaintext =
150 DecryptKey(*deserialized, hidden_, secure_deletion_data_, master_key_);
151 ASSERT_TRUE(plaintext.isOk());
152 EXPECT_TRUE(std::equal(key_material_.begin(), key_material_.end(), //
153 plaintext->begin(), plaintext->end()));
154 }
155
TEST_P(KeyBlobTest,WrongKeyLength)156 TEST_P(KeyBlobTest, WrongKeyLength) {
157 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
158 ASSERT_EQ(KM_ERROR_OK, Serialize());
159
160 // Modify the key length, shouldn't be able to parse.
161 serialized_blob_.writable_data()[1 /* version */ + 4 /* nonce len */ + 12 /* nonce */ + 3]++;
162
163 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, Deserialize());
164 }
165
TEST_P(KeyBlobTest,WrongNonce)166 TEST_P(KeyBlobTest, WrongNonce) {
167 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
168 ASSERT_EQ(KM_ERROR_OK, Serialize());
169
170 // Find the nonce, then modify it.
171 auto nonce_ptr = std::search(serialized_blob_.begin(), serialized_blob_.end(),
172 encrypted_key_.nonce.begin(), encrypted_key_.nonce.end());
173 ASSERT_NE(nonce_ptr, serialized_blob_.end());
174 (*const_cast<uint8_t*>(nonce_ptr))++;
175
176 // Deserialization shouldn't be affected, but decryption should fail.
177 ASSERT_EQ(KM_ERROR_OK, Deserialize());
178 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, Decrypt());
179 }
180
TEST_P(KeyBlobTest,WrongTag)181 TEST_P(KeyBlobTest, WrongTag) {
182 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
183 ASSERT_EQ(KM_ERROR_OK, Serialize());
184
185 // Find the tag, then modify it.
186 auto tag_ptr = std::search(serialized_blob_.begin(), serialized_blob_.end(),
187 encrypted_key_.tag.begin(), encrypted_key_.tag.end());
188 ASSERT_NE(tag_ptr, serialized_blob_.end());
189 (*const_cast<uint8_t*>(tag_ptr))++;
190
191 // Deserialization shouldn't be affected, but decryption should fail.
192 ASSERT_EQ(KM_ERROR_OK, Deserialize());
193 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, Decrypt());
194 }
195
TEST_P(KeyBlobTest,WrongCiphertext)196 TEST_P(KeyBlobTest, WrongCiphertext) {
197 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
198 ASSERT_EQ(KM_ERROR_OK, Serialize());
199
200 // Find the ciphertext, then modify it.
201 auto ciphertext_ptr =
202 std::search(serialized_blob_.begin(), serialized_blob_.end(),
203 encrypted_key_.ciphertext.begin(), encrypted_key_.ciphertext.end());
204 ASSERT_NE(ciphertext_ptr, serialized_blob_.end());
205 (*const_cast<uint8_t*>(ciphertext_ptr))++;
206
207 // Deserialization shouldn't be affected, but decryption should fail.
208 ASSERT_EQ(KM_ERROR_OK, Deserialize());
209 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, Decrypt());
210 }
211
TEST_P(KeyBlobTest,WrongMasterKey)212 TEST_P(KeyBlobTest, WrongMasterKey) {
213 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
214 ASSERT_EQ(KM_ERROR_OK, Serialize());
215
216 uint8_t wrong_master_data[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
217 KeymasterKeyBlob wrong_master(wrong_master_data, array_length(wrong_master_data));
218
219 // Decrypting with wrong master key should fail.
220 ASSERT_EQ(KM_ERROR_OK, Deserialize());
221 auto result = DecryptKey(deserialized_key_, hidden_, secure_deletion_data_, wrong_master);
222 ASSERT_FALSE(result.isOk());
223 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
224 }
225
TEST_P(KeyBlobTest,WrongHwEnforced)226 TEST_P(KeyBlobTest, WrongHwEnforced) {
227 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
228 ASSERT_EQ(KM_ERROR_OK, Serialize());
229
230 // Find enforced serialization data and modify it.
231 size_t hw_enforced_size = hw_enforced_.SerializedSize();
232 UniquePtr<uint8_t[]> hw_enforced_data(new (std::nothrow) uint8_t[hw_enforced_size]);
233 hw_enforced_.Serialize(hw_enforced_data.get(), hw_enforced_data.get() + hw_enforced_size);
234
235 auto hw_enforced_ptr =
236 std::search(serialized_blob_.begin(), serialized_blob_.end(), hw_enforced_data.get(),
237 hw_enforced_data.get() + hw_enforced_size);
238 ASSERT_NE(serialized_blob_.end(), hw_enforced_ptr);
239 (*(const_cast<uint8_t*>(hw_enforced_ptr) + hw_enforced_size - 1))++;
240
241 // Deserialization shouldn't be affected, but decryption should fail.
242 ASSERT_EQ(KM_ERROR_OK, Deserialize());
243 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, Decrypt());
244 }
245
TEST_P(KeyBlobTest,WrongSwEnforced)246 TEST_P(KeyBlobTest, WrongSwEnforced) {
247 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
248 ASSERT_EQ(KM_ERROR_OK, Serialize());
249
250 // Find enforced serialization data and modify it.
251 size_t sw_enforced_size = sw_enforced_.SerializedSize();
252 UniquePtr<uint8_t[]> sw_enforced_data(new uint8_t[sw_enforced_size]);
253 sw_enforced_.Serialize(sw_enforced_data.get(), sw_enforced_data.get() + sw_enforced_size);
254
255 auto sw_enforced_ptr =
256 std::search(serialized_blob_.begin(), serialized_blob_.end(), sw_enforced_data.get(),
257 sw_enforced_data.get() + sw_enforced_size);
258 ASSERT_NE(serialized_blob_.end(), sw_enforced_ptr);
259 (*(const_cast<uint8_t*>(sw_enforced_ptr) + sw_enforced_size - 1))++;
260
261 // Deserialization shouldn't be affected, but decryption should fail.
262 ASSERT_EQ(KM_ERROR_OK, Deserialize());
263 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, Decrypt());
264 }
265
TEST_P(KeyBlobTest,EmptyHidden)266 TEST_P(KeyBlobTest, EmptyHidden) {
267 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
268 ASSERT_EQ(KM_ERROR_OK, Serialize());
269
270 AuthorizationSet wrong_hidden;
271
272 // Deserialization shouldn't be affected, but decryption should fail.
273 ASSERT_EQ(KM_ERROR_OK, Deserialize());
274 auto result = DecryptKey(deserialized_key_, wrong_hidden, secure_deletion_data_, master_key_);
275 EXPECT_FALSE(result.isOk());
276 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
277 }
278
TEST_P(KeyBlobTest,WrongRootOfTrust)279 TEST_P(KeyBlobTest, WrongRootOfTrust) {
280 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
281 ASSERT_EQ(KM_ERROR_OK, Serialize());
282
283 AuthorizationSet wrong_hidden;
284 wrong_hidden.push_back(TAG_ROOT_OF_TRUST, "bar", 2);
285 wrong_hidden.push_back(TAG_APPLICATION_ID, "my_app", 6);
286
287 // Deserialization shouldn't be affected, but decryption should fail.
288 ASSERT_EQ(KM_ERROR_OK, Deserialize());
289 auto result = DecryptKey(deserialized_key_, wrong_hidden, secure_deletion_data_, master_key_);
290 EXPECT_FALSE(result.isOk());
291 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
292 }
293
TEST_P(KeyBlobTest,WrongAppId)294 TEST_P(KeyBlobTest, WrongAppId) {
295 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
296 ASSERT_EQ(KM_ERROR_OK, Serialize());
297
298 AuthorizationSet wrong_hidden;
299 wrong_hidden.push_back(TAG_ROOT_OF_TRUST, "foo", 3);
300 wrong_hidden.push_back(TAG_APPLICATION_ID, "your_app", 7);
301
302 // Deserialization shouldn't be affected, but decryption should fail.
303 ASSERT_EQ(KM_ERROR_OK, Deserialize());
304 auto result = DecryptKey(deserialized_key_, wrong_hidden, secure_deletion_data_, master_key_);
305 EXPECT_FALSE(result.isOk());
306 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
307 }
308
309 // This test is especially useful when compiled for 32-bit mode and run under valgrind.
TEST_P(KeyBlobTest,FuzzTest)310 TEST_P(KeyBlobTest, FuzzTest) {
311 time_t now = time(NULL);
312 std::cout << "Seeding rand() with " << now << " for fuzz test." << std::endl;
313 srand(now);
314
315 // Fill large buffer with random bytes.
316 const int kBufSize = 10000;
317 UniquePtr<uint8_t[]> buf(new uint8_t[kBufSize]);
318 for (size_t i = 0; i < kBufSize; ++i)
319 buf[i] = static_cast<uint8_t>(rand());
320
321 // Try to deserialize every offset with multiple methods.
322 size_t deserialize_auth_encrypted_success = 0;
323 for (size_t i = 0; i < kBufSize; ++i) {
324 keymaster_key_blob_t blob = {buf.get() + i, kBufSize - i};
325 KeymasterKeyBlob key_blob(blob);
326
327 // Integrity-assured blob.
328 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB,
329 DeserializeIntegrityAssuredBlob(key_blob, hidden_, &key_material_, &hw_enforced_,
330 &sw_enforced_));
331
332 // Auth-encrypted blob.
333 auto deserialized = DeserializeAuthEncryptedBlob(key_blob);
334 if (deserialized.isOk()) {
335 // It's possible (though unlikely) to deserialize successfully. Decryption should
336 // always fail, though.
337 ++deserialize_auth_encrypted_success;
338 auto decrypted = DecryptKey(*deserialized, hidden_, secure_deletion_data_, master_key_);
339 ASSERT_FALSE(decrypted.isOk());
340 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, decrypted.error())
341 << "Somehow successfully parsed and decrypted a blob with seed " << now
342 << " at offset " << i;
343 } else {
344 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, deserialized.error());
345 }
346 }
347 }
348
TEST_P(KeyBlobTest,UnderflowTest)349 TEST_P(KeyBlobTest, UnderflowTest) {
350 uint8_t buf[0];
351 keymaster_key_blob_t blob = {buf, 0};
352 KeymasterKeyBlob key_blob(blob);
353 EXPECT_NE(nullptr, key_blob.key_material);
354 EXPECT_EQ(0U, key_blob.key_material_size);
355
356 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB,
357 DeserializeIntegrityAssuredBlob(key_blob, hidden_, &key_material_, &hw_enforced_,
358 &sw_enforced_));
359
360 auto deserialized = DeserializeAuthEncryptedBlob(key_blob);
361 EXPECT_FALSE(deserialized.isOk());
362 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, deserialized.error());
363 }
364
TEST_P(KeyBlobTest,DupBufferToolarge)365 TEST_P(KeyBlobTest, DupBufferToolarge) {
366 uint8_t buf[0];
367 keymaster_key_blob_t blob = {buf, 0};
368 blob.key_material_size = 16 * 1024 * 1024 + 1;
369 KeymasterKeyBlob key_blob(blob);
370 EXPECT_EQ(nullptr, key_blob.key_material);
371 EXPECT_EQ(0U, key_blob.key_material_size);
372
373 ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB,
374 DeserializeIntegrityAssuredBlob(key_blob, hidden_, &key_material_, &hw_enforced_,
375 &sw_enforced_));
376
377 auto deserialized = DeserializeAuthEncryptedBlob(key_blob);
378 EXPECT_FALSE(deserialized.isOk());
379 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, deserialized.error());
380 }
381
382 INSTANTIATE_TEST_SUITE_P(AllFormats, KeyBlobTest,
383 ::testing::Values(AES_OCB, AES_GCM_WITH_SW_ENFORCED,
384 AES_GCM_WITH_SECURE_DELETION,
385 AES_GCM_WITH_SW_ENFORCED_VERSIONED,
386 AES_GCM_WITH_SECURE_DELETION_VERSIONED),
__anon68f930950202(const ::testing::TestParamInfo<KeyBlobTest::ParamType>& info) 387 [](const ::testing::TestParamInfo<KeyBlobTest::ParamType>& info) {
388 switch (info.param) {
389 case AES_OCB:
390 return "AES_OCB";
391 case AES_GCM_WITH_SW_ENFORCED:
392 return "AES_GCM_WITH_SW_ENFORCED";
393 case AES_GCM_WITH_SECURE_DELETION:
394 return "AES_GCM_WITH_SECURE_DELETION";
395 case AES_GCM_WITH_SW_ENFORCED_VERSIONED:
396 return "AES_GCM_WITH_SW_ENFORCED_VERSIONED";
397 case AES_GCM_WITH_SECURE_DELETION_VERSIONED:
398 return "AES_GCM_WITH_SECURE_DELETION_VERSIONED";
399 }
400 CHECK(false) << "Shouldn't be able to get here";
401 return "Unexpected";
402 });
403
404 using SecureDeletionTest = KeyBlobTest;
405
406 INSTANTIATE_TEST_SUITE_P(SecureDeletionFormats, SecureDeletionTest,
407 ::testing::Values(AES_GCM_WITH_SECURE_DELETION,
408 AES_GCM_WITH_SECURE_DELETION_VERSIONED),
__anon68f930950302(const ::testing::TestParamInfo<KeyBlobTest::ParamType>& info) 409 [](const ::testing::TestParamInfo<KeyBlobTest::ParamType>& info) {
410 switch (info.param) {
411 case AES_OCB:
412 return "AES_OCB";
413 case AES_GCM_WITH_SW_ENFORCED:
414 return "AES_GCM_WITH_SW_ENFORCED";
415 case AES_GCM_WITH_SECURE_DELETION:
416 return "AES_GCM_WITH_SECURE_DELETION";
417 case AES_GCM_WITH_SW_ENFORCED_VERSIONED:
418 return "AES_GCM_WITH_SW_ENFORCED_VERSIONED";
419 case AES_GCM_WITH_SECURE_DELETION_VERSIONED:
420 return "AES_GCM_WITH_SECURE_DELETION_VERSIONED";
421 }
422 CHECK(false) << "Shouldn't be able to get here";
423 return "Unexpected";
424 });
425
TEST_P(SecureDeletionTest,WrongFactoryResetSecret)426 TEST_P(SecureDeletionTest, WrongFactoryResetSecret) {
427 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
428 ASSERT_EQ(KM_ERROR_OK, Serialize());
429
430 SecureDeletionData wrong_secure_deletion(std::move(secure_deletion_data_));
431 wrong_secure_deletion.factory_reset_secret.Reinitialize("Wrong", sizeof("Wrong"));
432
433 // Deserialization shouldn't be affected, but decryption should fail.
434 ASSERT_EQ(KM_ERROR_OK, Deserialize());
435 auto result = DecryptKey(deserialized_key_, hidden_, wrong_secure_deletion, master_key_);
436 EXPECT_FALSE(result.isOk());
437 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
438 }
439
TEST_P(SecureDeletionTest,WrongSecureDeletionSecret)440 TEST_P(SecureDeletionTest, WrongSecureDeletionSecret) {
441 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
442 ASSERT_EQ(KM_ERROR_OK, Serialize());
443
444 SecureDeletionData wrong_secure_deletion(std::move(secure_deletion_data_));
445 wrong_secure_deletion.secure_deletion_secret.Reinitialize("Wrong", sizeof("Wrong"));
446
447 // Deserialization shouldn't be affected, but decryption should fail.
448 ASSERT_EQ(KM_ERROR_OK, Deserialize());
449 auto result = DecryptKey(deserialized_key_, hidden_, wrong_secure_deletion, master_key_);
450 EXPECT_FALSE(result.isOk());
451 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
452 }
453
TEST_P(SecureDeletionTest,WrongSecureDeletionKeySlot)454 TEST_P(SecureDeletionTest, WrongSecureDeletionKeySlot) {
455 ASSERT_EQ(KM_ERROR_OK, Encrypt(GetParam()));
456 ASSERT_EQ(KM_ERROR_OK, Serialize());
457
458 SecureDeletionData wrong_secure_deletion(std::move(secure_deletion_data_));
459 ++wrong_secure_deletion.key_slot;
460
461 // Deserialization shouldn't be affected, but decryption should fail.
462 ASSERT_EQ(KM_ERROR_OK, Deserialize());
463 auto result = DecryptKey(deserialized_key_, hidden_, wrong_secure_deletion, master_key_);
464 EXPECT_FALSE(result.isOk());
465 EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, result.error());
466 }
467
TEST(KmErrorOrDeathTest,UncheckedError)468 TEST(KmErrorOrDeathTest, UncheckedError) {
469 ASSERT_DEATH({ KmErrorOr<int> kmError(KM_ERROR_UNKNOWN_ERROR); }, "");
470 }
471
TEST(KmErrorOrDeathTest,UseValueWithoutChecking)472 TEST(KmErrorOrDeathTest, UseValueWithoutChecking) {
473 ASSERT_DEATH(
474 {
475 KmErrorOr<int> kmError(KM_ERROR_UNKNOWN_ERROR);
476 kmError.value();
477 kmError.isOk(); // Check here so dtor won't abort().
478 },
479 "");
480 }
481
TEST(KmErrorOrDeathTest,CheckAfterReturn)482 TEST(KmErrorOrDeathTest, CheckAfterReturn) {
483 auto func = []() -> KmErrorOr<int> {
484 // This instance will have its content moved and then be destroyed. It
485 // shouldn't abort()
486 return KmErrorOr<int>(KM_ERROR_UNEXPECTED_NULL_POINTER);
487 };
488
489 {
490 auto err = func();
491 ASSERT_FALSE(err.isOk()); // Check here, so it isn't destroyed.
492 }
493
494 ASSERT_DEATH({ auto err = func(); }, "");
495 }
496
TEST(KmErrorOrDeathTest,CheckAfterMoveAssign)497 TEST(KmErrorOrDeathTest, CheckAfterMoveAssign) {
498 ASSERT_DEATH(
499 {
500 KmErrorOr<int> err(KM_ERROR_UNEXPECTED_NULL_POINTER);
501 KmErrorOr<int> err2(4);
502
503 err2 = std::move(err); // This swaps err and err2
504
505 // Checking only one isn't enough. Both were unchecked.
506 EXPECT_FALSE(err2.isOk());
507 },
508 "");
509
510 ASSERT_DEATH(
511 {
512 KmErrorOr<int> err(KM_ERROR_UNEXPECTED_NULL_POINTER);
513 KmErrorOr<int> err2(4);
514
515 err2 = std::move(err); // This swaps err and err2
516
517 // Checking only one isn't enough. Both were unchecked.
518 EXPECT_TRUE(err.isOk());
519 },
520 "");
521
522 {
523 KmErrorOr<int> err(KM_ERROR_UNEXPECTED_NULL_POINTER);
524 KmErrorOr<int> err2(4);
525 err2 = std::move(err); // This swaps err and err2
526
527 // Must check both to avoid abort().
528 EXPECT_TRUE(err.isOk());
529 EXPECT_FALSE(err2.isOk());
530 }
531
532 ASSERT_DEATH(
533 {
534 KmErrorOr<int> err(KM_ERROR_UNEXPECTED_NULL_POINTER);
535 KmErrorOr<int> err2(4);
536
537 err.isOk(); // Check err before swap
538 err2 = std::move(err); // This swaps err and err2
539 },
540 "");
541
542 {
543 KmErrorOr<int> err(KM_ERROR_UNEXPECTED_NULL_POINTER);
544 KmErrorOr<int> err2(4);
545
546 err.isOk(); // Check err before swap
547 err2 = std::move(err); // This swaps err and err2
548
549 // err2 is checked, check err
550 EXPECT_TRUE(err.isOk());
551 }
552 }
553
TEST(KmErrorOr,CheckAfterMove)554 TEST(KmErrorOr, CheckAfterMove) {
555 KmErrorOr<int> err(KM_ERROR_UNEXPECTED_NULL_POINTER);
556
557 KmErrorOr<int> err2(std::move(err)); // err won't abort
558 EXPECT_FALSE(err2.isOk()); // err2 won't abort
559 EXPECT_EQ(err2.error(), KM_ERROR_UNEXPECTED_NULL_POINTER);
560 }
561
TEST(KmErrorOrTest,UseErrorWithoutChecking)562 TEST(KmErrorOrTest, UseErrorWithoutChecking) {
563 KmErrorOr<int> kmError(99);
564 // Checking error before using isOk() always returns KM_ERROR_UNKNOWN_ERROR.
565 ASSERT_EQ(KM_ERROR_UNKNOWN_ERROR, kmError.error());
566 ASSERT_TRUE(kmError.isOk());
567 ASSERT_EQ(KM_ERROR_OK, kmError.error());
568 ASSERT_EQ(99, *kmError);
569 }
570
TEST(KmErrorTest,DefaultCtor)571 TEST(KmErrorTest, DefaultCtor) {
572 KmErrorOr<int> err;
573 // Default-constructed objects don't need to be tested. Should not crash.
574 }
575
576 } // namespace keymaster::test
577