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