1 /*
2 * Copyright (C) 2016 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 #define LOG_TAG "keymaster_hidl_hal_test"
18 #include <cutils/log.h>
19
20 #include <iostream>
21
22 #include <openssl/evp.h>
23 #include <openssl/mem.h>
24 #include <openssl/x509.h>
25
26 #include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
27 #include <android/hardware/keymaster/3.0/types.h>
28
29 #include <cutils/properties.h>
30
31 #include <keymaster/keymaster_configuration.h>
32
33 #include "authorization_set.h"
34 #include "key_param_output.h"
35
36 #include <VtsHalHidlTargetTestBase.h>
37 #include <VtsHalHidlTargetTestEnvBase.h>
38
39 #include "attestation_record.h"
40 #include "openssl_utils.h"
41
42 using ::android::sp;
43 using ::std::string;
44
45 static bool arm_deleteAllKeys = false;
46 static bool dump_Attestations = false;
47
48 namespace android {
49 namespace hardware {
50
operator ==(const hidl_vec<T> & a,const hidl_vec<T> & b)51 template <typename T> bool operator==(const hidl_vec<T>& a, const hidl_vec<T>& b) {
52 if (a.size() != b.size()) {
53 return false;
54 }
55 for (size_t i = 0; i < a.size(); ++i) {
56 if (a[i] != b[i]) {
57 return false;
58 }
59 }
60 return true;
61 }
62
63 namespace keymaster {
64 namespace V3_0 {
65
operator ==(const KeyParameter & a,const KeyParameter & b)66 bool operator==(const KeyParameter& a, const KeyParameter& b) {
67 if (a.tag != b.tag) {
68 return false;
69 }
70
71 switch (a.tag) {
72
73 /* Boolean tags */
74 case Tag::INVALID:
75 case Tag::CALLER_NONCE:
76 case Tag::INCLUDE_UNIQUE_ID:
77 case Tag::ECIES_SINGLE_HASH_MODE:
78 case Tag::BOOTLOADER_ONLY:
79 case Tag::NO_AUTH_REQUIRED:
80 case Tag::ALLOW_WHILE_ON_BODY:
81 case Tag::EXPORTABLE:
82 case Tag::ALL_APPLICATIONS:
83 case Tag::ROLLBACK_RESISTANT:
84 case Tag::RESET_SINCE_ID_ROTATION:
85 return true;
86
87 /* Integer tags */
88 case Tag::KEY_SIZE:
89 case Tag::MIN_MAC_LENGTH:
90 case Tag::MIN_SECONDS_BETWEEN_OPS:
91 case Tag::MAX_USES_PER_BOOT:
92 case Tag::ALL_USERS:
93 case Tag::USER_ID:
94 case Tag::OS_VERSION:
95 case Tag::OS_PATCHLEVEL:
96 case Tag::MAC_LENGTH:
97 case Tag::AUTH_TIMEOUT:
98 return a.f.integer == b.f.integer;
99
100 /* Long integer tags */
101 case Tag::RSA_PUBLIC_EXPONENT:
102 case Tag::USER_SECURE_ID:
103 return a.f.longInteger == b.f.longInteger;
104
105 /* Date-time tags */
106 case Tag::ACTIVE_DATETIME:
107 case Tag::ORIGINATION_EXPIRE_DATETIME:
108 case Tag::USAGE_EXPIRE_DATETIME:
109 case Tag::CREATION_DATETIME:
110 return a.f.dateTime == b.f.dateTime;
111
112 /* Bytes tags */
113 case Tag::APPLICATION_ID:
114 case Tag::APPLICATION_DATA:
115 case Tag::ROOT_OF_TRUST:
116 case Tag::UNIQUE_ID:
117 case Tag::ATTESTATION_CHALLENGE:
118 case Tag::ATTESTATION_APPLICATION_ID:
119 case Tag::ATTESTATION_ID_BRAND:
120 case Tag::ATTESTATION_ID_DEVICE:
121 case Tag::ATTESTATION_ID_PRODUCT:
122 case Tag::ATTESTATION_ID_SERIAL:
123 case Tag::ATTESTATION_ID_IMEI:
124 case Tag::ATTESTATION_ID_MEID:
125 case Tag::ATTESTATION_ID_MANUFACTURER:
126 case Tag::ATTESTATION_ID_MODEL:
127 case Tag::ASSOCIATED_DATA:
128 case Tag::NONCE:
129 case Tag::AUTH_TOKEN:
130 return a.blob == b.blob;
131
132 /* Enum tags */
133 case Tag::PURPOSE:
134 return a.f.purpose == b.f.purpose;
135 case Tag::ALGORITHM:
136 return a.f.algorithm == b.f.algorithm;
137 case Tag::BLOCK_MODE:
138 return a.f.blockMode == b.f.blockMode;
139 case Tag::DIGEST:
140 return a.f.digest == b.f.digest;
141 case Tag::PADDING:
142 return a.f.paddingMode == b.f.paddingMode;
143 case Tag::EC_CURVE:
144 return a.f.ecCurve == b.f.ecCurve;
145 case Tag::BLOB_USAGE_REQUIREMENTS:
146 return a.f.keyBlobUsageRequirements == b.f.keyBlobUsageRequirements;
147 case Tag::USER_AUTH_TYPE:
148 return a.f.integer == b.f.integer;
149 case Tag::ORIGIN:
150 return a.f.origin == b.f.origin;
151
152 /* Unsupported tags */
153 case Tag::KDF:
154 return false;
155 }
156 }
157
operator ==(const AuthorizationSet & a,const AuthorizationSet & b)158 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
159 return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
160 }
161
operator ==(const KeyCharacteristics & a,const KeyCharacteristics & b)162 bool operator==(const KeyCharacteristics& a, const KeyCharacteristics& b) {
163 // This isn't very efficient. Oh, well.
164 AuthorizationSet a_sw(a.softwareEnforced);
165 AuthorizationSet b_sw(b.softwareEnforced);
166 AuthorizationSet a_tee(b.teeEnforced);
167 AuthorizationSet b_tee(b.teeEnforced);
168
169 a_sw.Sort();
170 b_sw.Sort();
171 a_tee.Sort();
172 b_tee.Sort();
173
174 return a_sw == b_sw && a_tee == b_sw;
175 }
176
operator <<(::std::ostream & os,const AuthorizationSet & set)177 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
178 if (set.size() == 0)
179 os << "(Empty)" << ::std::endl;
180 else {
181 os << "\n";
182 for (size_t i = 0; i < set.size(); ++i)
183 os << set[i] << ::std::endl;
184 }
185 return os;
186 }
187
188 namespace test {
189 namespace {
190
191 template <TagType tag_type, Tag tag, typename ValueT>
contains(hidl_vec<KeyParameter> & set,TypedTag<tag_type,tag> ttag,ValueT expected_value)192 bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag> ttag, ValueT expected_value) {
193 size_t count = std::count_if(set.begin(), set.end(), [&](const KeyParameter& param) {
194 return param.tag == tag && accessTagValue(ttag, param) == expected_value;
195 });
196 return count == 1;
197 }
198
199 template <TagType tag_type, Tag tag>
contains(hidl_vec<KeyParameter> & set,TypedTag<tag_type,tag>)200 bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag>) {
201 size_t count = std::count_if(set.begin(), set.end(),
202 [&](const KeyParameter& param) { return param.tag == tag; });
203 return count > 0;
204 }
205
206 constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
207 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
208 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
209 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
210 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
211 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
212 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
213 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
214 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
215 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
216 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
217 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
218 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
219 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
220 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
221 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
222
hex2str(string a)223 string hex2str(string a) {
224 string b;
225 size_t num = a.size() / 2;
226 b.resize(num);
227 for (size_t i = 0; i < num; i++) {
228 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
229 }
230 return b;
231 }
232
233 char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
234 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
235
bin2hex(const hidl_vec<uint8_t> & data)236 string bin2hex(const hidl_vec<uint8_t>& data) {
237 string retval;
238 retval.reserve(data.size() * 2 + 1);
239 for (uint8_t byte : data) {
240 retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
241 retval.push_back(nibble2hex[0x0F & byte]);
242 }
243 return retval;
244 }
245
246 string rsa_key = hex2str(
247 "30820275020100300d06092a864886f70d01010105000482025f3082025b"
248 "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
249 "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
250 "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
251 "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
252 "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
253 "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
254 "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
255 "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
256 "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
257 "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
258 "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
259 "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
260 "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
261 "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
262 "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
263 "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
264 "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
265 "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
266 "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
267 "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
268 "3492d6");
269
270 string ec_256_key = hex2str(
271 "308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
272 "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
273 "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
274 "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
275 "1c6eb00083cf3376d11fd44949e0b2183bfe");
276
277 string ec_521_key = hex2str(
278 "3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
279 "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
280 "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
281 "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
282 "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
283 "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
284 "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
285 "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
286 "D9");
287
288 struct RSA_Delete {
operator ()android::hardware::keymaster::V3_0::test::__anon93d6503a0111::RSA_Delete289 void operator()(RSA* p) { RSA_free(p); }
290 };
291
parse_cert_blob(const hidl_vec<uint8_t> & blob)292 X509* parse_cert_blob(const hidl_vec<uint8_t>& blob) {
293 const uint8_t* p = blob.data();
294 return d2i_X509(nullptr, &p, blob.size());
295 }
296
verify_chain(const hidl_vec<hidl_vec<uint8_t>> & chain)297 bool verify_chain(const hidl_vec<hidl_vec<uint8_t>>& chain) {
298 for (size_t i = 0; i < chain.size() - 1; ++i) {
299 X509_Ptr key_cert(parse_cert_blob(chain[i]));
300 X509_Ptr signing_cert;
301 if (i < chain.size() - 1) {
302 signing_cert.reset(parse_cert_blob(chain[i + 1]));
303 } else {
304 signing_cert.reset(parse_cert_blob(chain[i]));
305 }
306 EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
307 if (!key_cert.get() || !signing_cert.get()) return false;
308
309 EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
310 EXPECT_TRUE(!!signing_pubkey.get());
311 if (!signing_pubkey.get()) return false;
312
313 EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
314 << "Verification of certificate " << i << " failed";
315
316 char* cert_issuer = //
317 X509_NAME_oneline(X509_get_issuer_name(key_cert.get()), nullptr, 0);
318 char* signer_subj =
319 X509_NAME_oneline(X509_get_subject_name(signing_cert.get()), nullptr, 0);
320 EXPECT_STREQ(cert_issuer, signer_subj) << "Cert " << i
321 << " has wrong issuer. (Possibly b/38394614)";
322 if (i == 0) {
323 char* cert_sub = X509_NAME_oneline(X509_get_subject_name(key_cert.get()), nullptr, 0);
324 EXPECT_STREQ("/CN=Android Keystore Key", cert_sub)
325 << "Cert " << i << " has wrong subject. (Possibly b/38394614)";
326 OPENSSL_free(cert_sub);
327 }
328
329 OPENSSL_free(cert_issuer);
330 OPENSSL_free(signer_subj);
331
332 if (dump_Attestations) std::cout << bin2hex(chain[i]) << std::endl;
333 }
334
335 return true;
336 }
337
338 // Extract attestation record from cert. Returned object is still part of cert; don't free it
339 // separately.
get_attestation_record(X509 * certificate)340 ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
341 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
342 EXPECT_TRUE(!!oid.get());
343 if (!oid.get()) return nullptr;
344
345 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
346 EXPECT_NE(-1, location);
347 if (location == -1) return nullptr;
348
349 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
350 EXPECT_TRUE(!!attest_rec_ext);
351 if (!attest_rec_ext) return nullptr;
352
353 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
354 EXPECT_TRUE(!!attest_rec);
355 return attest_rec;
356 }
357
tag_in_list(const KeyParameter & entry)358 bool tag_in_list(const KeyParameter& entry) {
359 // Attestations don't contain everything in key authorization lists, so we need to filter
360 // the key lists to produce the lists that we expect to match the attestations.
361 auto tag_list = {
362 Tag::USER_ID, Tag::INCLUDE_UNIQUE_ID, Tag::BLOB_USAGE_REQUIREMENTS,
363 Tag::EC_CURVE /* Tag::EC_CURVE will be included by KM2 implementations */,
364 };
365 return std::find(tag_list.begin(), tag_list.end(), entry.tag) != tag_list.end();
366 }
367
filter_tags(const AuthorizationSet & set)368 AuthorizationSet filter_tags(const AuthorizationSet& set) {
369 AuthorizationSet filtered;
370 std::remove_copy_if(set.begin(), set.end(), std::back_inserter(filtered), tag_in_list);
371 return filtered;
372 }
373
make_string(const uint8_t * data,size_t length)374 std::string make_string(const uint8_t* data, size_t length) {
375 return std::string(reinterpret_cast<const char*>(data), length);
376 }
377
make_string(const uint8_t (& a)[N])378 template <size_t N> std::string make_string(const uint8_t (&a)[N]) {
379 return make_string(a, N);
380 }
381
382 class HidlBuf : public hidl_vec<uint8_t> {
383 typedef hidl_vec<uint8_t> super;
384
385 public:
HidlBuf()386 HidlBuf() {}
HidlBuf(const super & other)387 HidlBuf(const super& other) : super(other) {}
HidlBuf(super && other)388 HidlBuf(super&& other) : super(std::move(other)) {}
HidlBuf(const std::string & other)389 explicit HidlBuf(const std::string& other) : HidlBuf() { *this = other; }
390
operator =(const super & other)391 HidlBuf& operator=(const super& other) {
392 super::operator=(other);
393 return *this;
394 }
395
operator =(super && other)396 HidlBuf& operator=(super&& other) {
397 super::operator=(std::move(other));
398 return *this;
399 }
400
operator =(const string & other)401 HidlBuf& operator=(const string& other) {
402 resize(other.size());
403 for (size_t i = 0; i < other.size(); ++i) {
404 (*this)[i] = static_cast<uint8_t>(other[i]);
405 }
406 return *this;
407 }
408
to_string() const409 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
410 };
411
412 constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF;
413
414 } // namespace
415
416 // Test environment for Keymaster HIDL HAL.
417 class KeymasterHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
418 public:
419 // get the test environment singleton
Instance()420 static KeymasterHidlEnvironment* Instance() {
421 static KeymasterHidlEnvironment* instance = new KeymasterHidlEnvironment;
422 return instance;
423 }
424
registerTestServices()425 virtual void registerTestServices() override { registerTestService<IKeymasterDevice>(); }
426 private:
KeymasterHidlEnvironment()427 KeymasterHidlEnvironment() {}
428 };
429
430 class KeymasterHidlTest : public ::testing::VtsHalHidlTargetTestBase {
431 public:
TearDown()432 void TearDown() override {
433 if (key_blob_.size()) {
434 CheckedDeleteKey();
435 }
436 AbortIfNeeded();
437 }
438
439 // SetUpTestCase runs only once per test case, not once per test.
SetUpTestCase()440 static void SetUpTestCase() {
441 keymaster_ = ::testing::VtsHalHidlTargetTestBase::getService<IKeymasterDevice>(
442 KeymasterHidlEnvironment::Instance()->getServiceName<IKeymasterDevice>());
443 ASSERT_NE(keymaster_, nullptr);
444
445 ASSERT_TRUE(
446 keymaster_
447 ->getHardwareFeatures([&](bool isSecure, bool supportsEc, bool supportsSymmetric,
448 bool supportsAttestation, bool supportsAllDigests,
449 const hidl_string& name, const hidl_string& author) {
450 is_secure_ = isSecure;
451 supports_ec_ = supportsEc;
452 supports_symmetric_ = supportsSymmetric;
453 supports_attestation_ = supportsAttestation;
454 supports_all_digests_ = supportsAllDigests;
455 name_ = name;
456 author_ = author;
457 })
458 .isOk());
459
460 os_version_ = ::keymaster::GetOsVersion();
461 os_patch_level_ = ::keymaster::GetOsPatchlevel();
462 }
463
TearDownTestCase()464 static void TearDownTestCase() { keymaster_.clear(); }
465
keymaster()466 static IKeymasterDevice& keymaster() { return *keymaster_; }
os_version()467 static uint32_t os_version() { return os_version_; }
os_patch_level()468 static uint32_t os_patch_level() { return os_patch_level_; }
469
UserAuths()470 AuthorizationSet UserAuths() { return AuthorizationSetBuilder().Authorization(TAG_USER_ID, 7); }
471
GenerateKey(const AuthorizationSet & key_desc,HidlBuf * key_blob,KeyCharacteristics * key_characteristics)472 ErrorCode GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob,
473 KeyCharacteristics* key_characteristics) {
474 EXPECT_NE(key_blob, nullptr);
475 EXPECT_NE(key_characteristics, nullptr);
476 EXPECT_EQ(0U, key_blob->size());
477
478 ErrorCode error;
479 EXPECT_TRUE(keymaster_
480 ->generateKey(key_desc.hidl_data(),
481 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
482 const KeyCharacteristics& hidl_key_characteristics) {
483 error = hidl_error;
484 *key_blob = hidl_key_blob;
485 *key_characteristics = hidl_key_characteristics;
486 })
487 .isOk());
488 // On error, blob & characteristics should be empty.
489 if (error != ErrorCode::OK) {
490 EXPECT_EQ(0U, key_blob->size());
491 EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
492 key_characteristics->teeEnforced.size()));
493 }
494 return error;
495 }
496
GenerateKey(const AuthorizationSet & key_desc)497 ErrorCode GenerateKey(const AuthorizationSet& key_desc) {
498 return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
499 }
500
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material,HidlBuf * key_blob,KeyCharacteristics * key_characteristics)501 ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
502 const string& key_material, HidlBuf* key_blob,
503 KeyCharacteristics* key_characteristics) {
504 ErrorCode error;
505 EXPECT_TRUE(keymaster_
506 ->importKey(key_desc.hidl_data(), format, HidlBuf(key_material),
507 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
508 const KeyCharacteristics& hidl_key_characteristics) {
509 error = hidl_error;
510 *key_blob = hidl_key_blob;
511 *key_characteristics = hidl_key_characteristics;
512 })
513 .isOk());
514 // On error, blob & characteristics should be empty.
515 if (error != ErrorCode::OK) {
516 EXPECT_EQ(0U, key_blob->size());
517 EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
518 key_characteristics->teeEnforced.size()));
519 }
520 return error;
521 }
522
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material)523 ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
524 const string& key_material) {
525 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
526 }
527
ExportKey(KeyFormat format,const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,HidlBuf * key_material)528 ErrorCode ExportKey(KeyFormat format, const HidlBuf& key_blob, const HidlBuf& client_id,
529 const HidlBuf& app_data, HidlBuf* key_material) {
530 ErrorCode error;
531 EXPECT_TRUE(
532 keymaster_
533 ->exportKey(format, key_blob, client_id, app_data,
534 [&](ErrorCode hidl_error_code, const HidlBuf& hidl_key_material) {
535 error = hidl_error_code;
536 *key_material = hidl_key_material;
537 })
538 .isOk());
539 // On error, blob should be empty.
540 if (error != ErrorCode::OK) {
541 EXPECT_EQ(0U, key_material->size());
542 }
543 return error;
544 }
545
ExportKey(KeyFormat format,HidlBuf * key_material)546 ErrorCode ExportKey(KeyFormat format, HidlBuf* key_material) {
547 HidlBuf client_id, app_data;
548 return ExportKey(format, key_blob_, client_id, app_data, key_material);
549 }
550
DeleteKey(HidlBuf * key_blob,bool keep_key_blob=false)551 ErrorCode DeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) {
552 auto rc = keymaster_->deleteKey(*key_blob);
553 if (!keep_key_blob) *key_blob = HidlBuf();
554 if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
555 return rc;
556 }
557
DeleteKey(bool keep_key_blob=false)558 ErrorCode DeleteKey(bool keep_key_blob = false) {
559 return DeleteKey(&key_blob_, keep_key_blob);
560 }
561
DeleteAllKeys()562 ErrorCode DeleteAllKeys() {
563 ErrorCode error = keymaster_->deleteAllKeys();
564 return error;
565 }
566
CheckedDeleteKey(HidlBuf * key_blob,bool keep_key_blob=false)567 void CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) {
568 auto rc = DeleteKey(key_blob, keep_key_blob);
569 EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
570 }
571
CheckedDeleteKey()572 void CheckedDeleteKey() { CheckedDeleteKey(&key_blob_); }
573
GetCharacteristics(const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,KeyCharacteristics * key_characteristics)574 ErrorCode GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
575 const HidlBuf& app_data, KeyCharacteristics* key_characteristics) {
576 ErrorCode error = ErrorCode::UNKNOWN_ERROR;
577 EXPECT_TRUE(
578 keymaster_
579 ->getKeyCharacteristics(
580 key_blob, client_id, app_data,
581 [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_key_characteristics) {
582 error = hidl_error, *key_characteristics = hidl_key_characteristics;
583 })
584 .isOk());
585 return error;
586 }
587
GetCharacteristics(const HidlBuf & key_blob,KeyCharacteristics * key_characteristics)588 ErrorCode GetCharacteristics(const HidlBuf& key_blob, KeyCharacteristics* key_characteristics) {
589 HidlBuf client_id, app_data;
590 return GetCharacteristics(key_blob, client_id, app_data, key_characteristics);
591 }
592
Begin(KeyPurpose purpose,const HidlBuf & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params,OperationHandle * op_handle)593 ErrorCode Begin(KeyPurpose purpose, const HidlBuf& key_blob, const AuthorizationSet& in_params,
594 AuthorizationSet* out_params, OperationHandle* op_handle) {
595 SCOPED_TRACE("Begin");
596 ErrorCode error;
597 OperationHandle saved_handle = *op_handle;
598 EXPECT_TRUE(
599 keymaster_
600 ->begin(purpose, key_blob, in_params.hidl_data(),
601 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
602 uint64_t hidl_op_handle) {
603 error = hidl_error;
604 *out_params = hidl_out_params;
605 *op_handle = hidl_op_handle;
606 })
607 .isOk());
608 if (error != ErrorCode::OK) {
609 // Some implementations may modify *op_handle on error.
610 *op_handle = saved_handle;
611 }
612 return error;
613 }
614
Begin(KeyPurpose purpose,const AuthorizationSet & in_params,AuthorizationSet * out_params)615 ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
616 AuthorizationSet* out_params) {
617 SCOPED_TRACE("Begin");
618 EXPECT_EQ(kOpHandleSentinel, op_handle_);
619 return Begin(purpose, key_blob_, in_params, out_params, &op_handle_);
620 }
621
Begin(KeyPurpose purpose,const AuthorizationSet & in_params)622 ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
623 SCOPED_TRACE("Begin");
624 AuthorizationSet out_params;
625 ErrorCode error = Begin(purpose, in_params, &out_params);
626 EXPECT_TRUE(out_params.empty());
627 return error;
628 }
629
Update(OperationHandle op_handle,const AuthorizationSet & in_params,const string & input,AuthorizationSet * out_params,string * output,size_t * input_consumed)630 ErrorCode Update(OperationHandle op_handle, const AuthorizationSet& in_params,
631 const string& input, AuthorizationSet* out_params, string* output,
632 size_t* input_consumed) {
633 SCOPED_TRACE("Update");
634 ErrorCode error;
635 EXPECT_TRUE(keymaster_
636 ->update(op_handle, in_params.hidl_data(), HidlBuf(input),
637 [&](ErrorCode hidl_error, uint32_t hidl_input_consumed,
638 const hidl_vec<KeyParameter>& hidl_out_params,
639 const HidlBuf& hidl_output) {
640 error = hidl_error;
641 out_params->push_back(AuthorizationSet(hidl_out_params));
642 output->append(hidl_output.to_string());
643 *input_consumed = hidl_input_consumed;
644 })
645 .isOk());
646 return error;
647 }
648
Update(const string & input,string * out,size_t * input_consumed)649 ErrorCode Update(const string& input, string* out, size_t* input_consumed) {
650 SCOPED_TRACE("Update");
651 AuthorizationSet out_params;
652 ErrorCode error = Update(op_handle_, AuthorizationSet() /* in_params */, input, &out_params,
653 out, input_consumed);
654 EXPECT_TRUE(out_params.empty());
655 return error;
656 }
657
Finish(OperationHandle op_handle,const AuthorizationSet & in_params,const string & input,const string & signature,AuthorizationSet * out_params,string * output)658 ErrorCode Finish(OperationHandle op_handle, const AuthorizationSet& in_params,
659 const string& input, const string& signature, AuthorizationSet* out_params,
660 string* output) {
661 SCOPED_TRACE("Finish");
662 ErrorCode error;
663 EXPECT_TRUE(
664 keymaster_
665 ->finish(op_handle, in_params.hidl_data(), HidlBuf(input), HidlBuf(signature),
666 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
667 const HidlBuf& hidl_output) {
668 error = hidl_error;
669 *out_params = hidl_out_params;
670 output->append(hidl_output.to_string());
671 })
672 .isOk());
673 op_handle_ = kOpHandleSentinel; // So dtor doesn't Abort().
674 return error;
675 }
676
Finish(const string & message,string * output)677 ErrorCode Finish(const string& message, string* output) {
678 SCOPED_TRACE("Finish");
679 AuthorizationSet out_params;
680 string finish_output;
681 ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message,
682 "" /* signature */, &out_params, output);
683 if (error != ErrorCode::OK) {
684 return error;
685 }
686 EXPECT_EQ(0U, out_params.size());
687 return error;
688 }
689
Finish(const string & message,const string & signature,string * output)690 ErrorCode Finish(const string& message, const string& signature, string* output) {
691 SCOPED_TRACE("Finish");
692 AuthorizationSet out_params;
693 ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, signature,
694 &out_params, output);
695 op_handle_ = kOpHandleSentinel; // So dtor doesn't Abort().
696 if (error != ErrorCode::OK) {
697 return error;
698 }
699 EXPECT_EQ(0U, out_params.size());
700 return error;
701 }
702
Abort(OperationHandle op_handle)703 ErrorCode Abort(OperationHandle op_handle) {
704 SCOPED_TRACE("Abort");
705 auto retval = keymaster_->abort(op_handle);
706 EXPECT_TRUE(retval.isOk());
707 return retval;
708 }
709
AbortIfNeeded()710 void AbortIfNeeded() {
711 SCOPED_TRACE("AbortIfNeeded");
712 if (op_handle_ != kOpHandleSentinel) {
713 EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
714 op_handle_ = kOpHandleSentinel;
715 }
716 }
717
AttestKey(const HidlBuf & key_blob,const AuthorizationSet & attest_params,hidl_vec<hidl_vec<uint8_t>> * cert_chain)718 ErrorCode AttestKey(const HidlBuf& key_blob, const AuthorizationSet& attest_params,
719 hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
720 SCOPED_TRACE("AttestKey");
721 ErrorCode error;
722 auto rc = keymaster_->attestKey(
723 key_blob, attest_params.hidl_data(),
724 [&](ErrorCode hidl_error, const hidl_vec<hidl_vec<uint8_t>>& hidl_cert_chain) {
725 error = hidl_error;
726 *cert_chain = hidl_cert_chain;
727 });
728
729 EXPECT_TRUE(rc.isOk()) << rc.description();
730 if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
731
732 return error;
733 }
734
AttestKey(const AuthorizationSet & attest_params,hidl_vec<hidl_vec<uint8_t>> * cert_chain)735 ErrorCode AttestKey(const AuthorizationSet& attest_params,
736 hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
737 SCOPED_TRACE("AttestKey");
738 return AttestKey(key_blob_, attest_params, cert_chain);
739 }
740
ProcessMessage(const HidlBuf & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)741 string ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation, const string& message,
742 const AuthorizationSet& in_params, AuthorizationSet* out_params) {
743 SCOPED_TRACE("ProcessMessage");
744 AuthorizationSet begin_out_params;
745 EXPECT_EQ(ErrorCode::OK,
746 Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_));
747
748 string unused;
749 AuthorizationSet finish_params;
750 AuthorizationSet finish_out_params;
751 string output;
752 EXPECT_EQ(ErrorCode::OK,
753 Finish(op_handle_, finish_params, message, unused, &finish_out_params, &output));
754 op_handle_ = kOpHandleSentinel;
755
756 out_params->push_back(begin_out_params);
757 out_params->push_back(finish_out_params);
758 return output;
759 }
760
SignMessage(const HidlBuf & key_blob,const string & message,const AuthorizationSet & params)761 string SignMessage(const HidlBuf& key_blob, const string& message,
762 const AuthorizationSet& params) {
763 SCOPED_TRACE("SignMessage");
764 AuthorizationSet out_params;
765 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
766 EXPECT_TRUE(out_params.empty());
767 return signature;
768 }
769
SignMessage(const string & message,const AuthorizationSet & params)770 string SignMessage(const string& message, const AuthorizationSet& params) {
771 SCOPED_TRACE("SignMessage");
772 return SignMessage(key_blob_, message, params);
773 }
774
MacMessage(const string & message,Digest digest,size_t mac_length)775 string MacMessage(const string& message, Digest digest, size_t mac_length) {
776 SCOPED_TRACE("MacMessage");
777 return SignMessage(
778 key_blob_, message,
779 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
780 }
781
CheckHmacTestVector(const string & key,const string & message,Digest digest,const string & expected_mac)782 void CheckHmacTestVector(const string& key, const string& message, Digest digest,
783 const string& expected_mac) {
784 SCOPED_TRACE("CheckHmacTestVector");
785 ASSERT_EQ(ErrorCode::OK,
786 ImportKey(AuthorizationSetBuilder()
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .HmacKey(key.size() * 8)
789 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
790 .Digest(digest),
791 KeyFormat::RAW, key));
792 string signature = MacMessage(message, digest, expected_mac.size() * 8);
793 EXPECT_EQ(expected_mac, signature) << "Test vector didn't match for digest " << (int)digest;
794 CheckedDeleteKey();
795 }
796
CheckAesCtrTestVector(const string & key,const string & nonce,const string & message,const string & expected_ciphertext)797 void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message,
798 const string& expected_ciphertext) {
799 SCOPED_TRACE("CheckAesCtrTestVector");
800 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
801 .Authorization(TAG_NO_AUTH_REQUIRED)
802 .AesEncryptionKey(key.size() * 8)
803 .BlockMode(BlockMode::CTR)
804 .Authorization(TAG_CALLER_NONCE)
805 .Padding(PaddingMode::NONE),
806 KeyFormat::RAW, key));
807
808 auto params = AuthorizationSetBuilder()
809 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
810 .BlockMode(BlockMode::CTR)
811 .Padding(PaddingMode::NONE);
812 AuthorizationSet out_params;
813 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
814 EXPECT_EQ(expected_ciphertext, ciphertext);
815 }
816
VerifyMessage(const HidlBuf & key_blob,const string & message,const string & signature,const AuthorizationSet & params)817 void VerifyMessage(const HidlBuf& key_blob, const string& message, const string& signature,
818 const AuthorizationSet& params) {
819 SCOPED_TRACE("VerifyMessage");
820 AuthorizationSet begin_out_params;
821 ASSERT_EQ(ErrorCode::OK,
822 Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params, &op_handle_));
823
824 string unused;
825 AuthorizationSet finish_params;
826 AuthorizationSet finish_out_params;
827 string output;
828 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, signature,
829 &finish_out_params, &output));
830 op_handle_ = kOpHandleSentinel;
831 EXPECT_TRUE(output.empty());
832 }
833
VerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)834 void VerifyMessage(const string& message, const string& signature,
835 const AuthorizationSet& params) {
836 SCOPED_TRACE("VerifyMessage");
837 VerifyMessage(key_blob_, message, signature, params);
838 }
839
EncryptMessage(const HidlBuf & key_blob,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)840 string EncryptMessage(const HidlBuf& key_blob, const string& message,
841 const AuthorizationSet& in_params, AuthorizationSet* out_params) {
842 SCOPED_TRACE("EncryptMessage");
843 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
844 }
845
EncryptMessage(const string & message,const AuthorizationSet & params,AuthorizationSet * out_params)846 string EncryptMessage(const string& message, const AuthorizationSet& params,
847 AuthorizationSet* out_params) {
848 SCOPED_TRACE("EncryptMessage");
849 return EncryptMessage(key_blob_, message, params, out_params);
850 }
851
EncryptMessage(const string & message,const AuthorizationSet & params)852 string EncryptMessage(const string& message, const AuthorizationSet& params) {
853 SCOPED_TRACE("EncryptMessage");
854 AuthorizationSet out_params;
855 string ciphertext = EncryptMessage(message, params, &out_params);
856 EXPECT_TRUE(out_params.empty())
857 << "Output params should be empty. Contained: " << out_params;
858 return ciphertext;
859 }
860
DecryptMessage(const HidlBuf & key_blob,const string & ciphertext,const AuthorizationSet & params)861 string DecryptMessage(const HidlBuf& key_blob, const string& ciphertext,
862 const AuthorizationSet& params) {
863 SCOPED_TRACE("DecryptMessage");
864 AuthorizationSet out_params;
865 string plaintext =
866 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
867 EXPECT_TRUE(out_params.empty());
868 return plaintext;
869 }
870
DecryptMessage(const string & ciphertext,const AuthorizationSet & params)871 string DecryptMessage(const string& ciphertext, const AuthorizationSet& params) {
872 SCOPED_TRACE("DecryptMessage");
873 return DecryptMessage(key_blob_, ciphertext, params);
874 }
875
876 template <TagType tag_type, Tag tag, typename ValueT>
CheckKm0CryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)877 void CheckKm0CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
878 SCOPED_TRACE("CheckKm0CryptoParam");
879 if (is_secure_) {
880 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected));
881 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag));
882 } else {
883 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected));
884 EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag));
885 }
886 }
887
888 template <TagType tag_type, Tag tag, typename ValueT>
CheckKm1CryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)889 void CheckKm1CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
890 SCOPED_TRACE("CheckKm1CryptoParam");
891 if (is_secure_ && supports_symmetric_) {
892 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected));
893 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag));
894 } else {
895 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected));
896 EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag));
897 }
898 }
899
900 template <TagType tag_type, Tag tag, typename ValueT>
CheckKm2CryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)901 void CheckKm2CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
902 SCOPED_TRACE("CheckKm2CryptoParam");
903 if (supports_attestation_) {
904 EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected));
905 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag));
906 } else if (!supports_symmetric_ /* KM version < 1 or SW */) {
907 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected));
908 EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag));
909 }
910 }
911
CheckOrigin(bool asymmetric=false)912 void CheckOrigin(bool asymmetric = false) {
913 SCOPED_TRACE("CheckOrigin");
914 if (is_secure_ && supports_symmetric_) {
915 EXPECT_TRUE(
916 contains(key_characteristics_.teeEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED));
917 } else if (is_secure_) {
918 // wrapped KM0
919 if (asymmetric) {
920 EXPECT_TRUE(
921 contains(key_characteristics_.teeEnforced, TAG_ORIGIN, KeyOrigin::UNKNOWN));
922 } else {
923 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, TAG_ORIGIN,
924 KeyOrigin::IMPORTED));
925 }
926 } else {
927 EXPECT_TRUE(
928 contains(key_characteristics_.softwareEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED));
929 }
930 }
931
IsSecure()932 static bool IsSecure() { return is_secure_; }
SupportsEc()933 static bool SupportsEc() { return supports_ec_; }
SupportsSymmetric()934 static bool SupportsSymmetric() { return supports_symmetric_; }
SupportsAllDigests()935 static bool SupportsAllDigests() { return supports_all_digests_; }
SupportsAttestation()936 static bool SupportsAttestation() { return supports_attestation_; }
937
Km2Profile()938 static bool Km2Profile() {
939 return SupportsAttestation() && SupportsAllDigests() && SupportsSymmetric() &&
940 SupportsEc() && IsSecure();
941 }
942
Km1Profile()943 static bool Km1Profile() {
944 return !SupportsAttestation() && SupportsSymmetric() && SupportsEc() && IsSecure();
945 }
946
Km0Profile()947 static bool Km0Profile() {
948 return !SupportsAttestation() && !SupportsAllDigests() && !SupportsSymmetric() &&
949 IsSecure();
950 }
951
SwOnlyProfile()952 static bool SwOnlyProfile() {
953 return !SupportsAttestation() && !SupportsAllDigests() && !SupportsSymmetric() &&
954 !SupportsEc() && !IsSecure();
955 }
956
957 HidlBuf key_blob_;
958 KeyCharacteristics key_characteristics_;
959 OperationHandle op_handle_ = kOpHandleSentinel;
960
961 private:
962 static sp<IKeymasterDevice> keymaster_;
963 static uint32_t os_version_;
964 static uint32_t os_patch_level_;
965
966 static bool is_secure_;
967 static bool supports_ec_;
968 static bool supports_symmetric_;
969 static bool supports_attestation_;
970 static bool supports_all_digests_;
971 static hidl_string name_;
972 static hidl_string author_;
973 };
974
verify_attestation_record(const string & challenge,const string & app_id,AuthorizationSet expected_sw_enforced,AuthorizationSet expected_tee_enforced,const hidl_vec<uint8_t> & attestation_cert)975 bool verify_attestation_record(const string& challenge, const string& app_id,
976 AuthorizationSet expected_sw_enforced,
977 AuthorizationSet expected_tee_enforced,
978 const hidl_vec<uint8_t>& attestation_cert) {
979 X509_Ptr cert(parse_cert_blob(attestation_cert));
980 EXPECT_TRUE(!!cert.get());
981 if (!cert.get()) return false;
982
983 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
984 EXPECT_TRUE(!!attest_rec);
985 if (!attest_rec) return false;
986
987 AuthorizationSet att_sw_enforced;
988 AuthorizationSet att_tee_enforced;
989 uint32_t att_attestation_version;
990 uint32_t att_keymaster_version;
991 SecurityLevel att_attestation_security_level;
992 SecurityLevel att_keymaster_security_level;
993 HidlBuf att_challenge;
994 HidlBuf att_unique_id;
995 HidlBuf att_app_id;
996 EXPECT_EQ(ErrorCode::OK,
997 parse_attestation_record(attest_rec->data, //
998 attest_rec->length, //
999 &att_attestation_version, //
1000 &att_attestation_security_level, //
1001 &att_keymaster_version, //
1002 &att_keymaster_security_level, //
1003 &att_challenge, //
1004 &att_sw_enforced, //
1005 &att_tee_enforced, //
1006 &att_unique_id));
1007
1008 EXPECT_TRUE(att_attestation_version == 1 || att_attestation_version == 2);
1009
1010 expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID,
1011 HidlBuf(app_id));
1012
1013 if (!KeymasterHidlTest::IsSecure()) {
1014 // SW is KM3
1015 EXPECT_EQ(att_keymaster_version, 3U);
1016 }
1017
1018 if (KeymasterHidlTest::SupportsSymmetric()) {
1019 EXPECT_GE(att_keymaster_version, 1U);
1020 }
1021
1022 if (KeymasterHidlTest::SupportsAttestation()) {
1023 EXPECT_GE(att_keymaster_version, 2U);
1024 }
1025
1026 EXPECT_EQ(KeymasterHidlTest::IsSecure() ? SecurityLevel::TRUSTED_ENVIRONMENT
1027 : SecurityLevel::SOFTWARE,
1028 att_keymaster_security_level);
1029 EXPECT_EQ(KeymasterHidlTest::SupportsAttestation() ? SecurityLevel::TRUSTED_ENVIRONMENT
1030 : SecurityLevel::SOFTWARE,
1031 att_attestation_security_level);
1032
1033 EXPECT_EQ(challenge.length(), att_challenge.size());
1034 EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
1035
1036 att_sw_enforced.Sort();
1037 expected_sw_enforced.Sort();
1038 EXPECT_EQ(filter_tags(expected_sw_enforced), filter_tags(att_sw_enforced))
1039 << "(Possibly b/38394619)";
1040
1041 att_tee_enforced.Sort();
1042 expected_tee_enforced.Sort();
1043 EXPECT_EQ(filter_tags(expected_tee_enforced), filter_tags(att_tee_enforced))
1044 << "(Possibly b/38394619)";
1045
1046 return true;
1047 }
1048
1049 sp<IKeymasterDevice> KeymasterHidlTest::keymaster_;
1050 uint32_t KeymasterHidlTest::os_version_;
1051 uint32_t KeymasterHidlTest::os_patch_level_;
1052 bool KeymasterHidlTest::is_secure_;
1053 bool KeymasterHidlTest::supports_ec_;
1054 bool KeymasterHidlTest::supports_symmetric_;
1055 bool KeymasterHidlTest::supports_all_digests_;
1056 bool KeymasterHidlTest::supports_attestation_;
1057 hidl_string KeymasterHidlTest::name_;
1058 hidl_string KeymasterHidlTest::author_;
1059
1060 typedef KeymasterHidlTest KeymasterVersionTest;
1061
1062 /*
1063 * KeymasterVersionTest.SensibleFeatures:
1064 *
1065 * Queries keymaster to find the set of features it supports. Fails if the combination doesn't
1066 * correspond to any well-defined keymaster version.
1067 */
TEST_F(KeymasterVersionTest,SensibleFeatures)1068 TEST_F(KeymasterVersionTest, SensibleFeatures) {
1069 EXPECT_TRUE(Km2Profile() || Km1Profile() || Km0Profile() || SwOnlyProfile())
1070 << "Keymaster feature set doesn't fit any reasonable profile. Reported features:"
1071 << "SupportsAttestation [" << SupportsAttestation() << "], "
1072 << "SupportsSymmetric [" << SupportsSymmetric() << "], "
1073 << "SupportsAllDigests [" << SupportsAllDigests() << "], "
1074 << "SupportsEc [" << SupportsEc() << "], "
1075 << "IsSecure [" << IsSecure() << "]";
1076 }
1077
1078 class NewKeyGenerationTest : public KeymasterHidlTest {
1079 protected:
CheckBaseParams(const KeyCharacteristics & keyCharacteristics,bool asymmetric=false)1080 void CheckBaseParams(const KeyCharacteristics& keyCharacteristics, bool asymmetric = false) {
1081 // TODO(swillden): Distinguish which params should be in which auth list.
1082
1083 AuthorizationSet auths(keyCharacteristics.teeEnforced);
1084 auths.push_back(AuthorizationSet(keyCharacteristics.softwareEnforced));
1085
1086 if (!SupportsSymmetric() && asymmetric) {
1087 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::UNKNOWN));
1088 } else {
1089 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1090 }
1091
1092 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1093 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1094 EXPECT_TRUE(auths.Contains(TAG_USER_ID, 7))
1095 << "User ID should be 7, was " << auths.GetTagValue(TAG_USER_ID);
1096
1097 // Verify that App ID, App data and ROT are NOT included.
1098 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1099 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_ID));
1100 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1101
1102 // Check that some unexpected tags/values are NOT present.
1103 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
1104 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1105 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301));
1106
1107 // Now check that unspecified, defaulted tags are correct.
1108 EXPECT_TRUE(auths.Contains(TAG_CREATION_DATETIME));
1109
1110 if (SupportsAttestation()) {
1111 EXPECT_TRUE(auths.Contains(TAG_OS_VERSION, os_version()))
1112 << "OS version is " << os_version() << " key reported "
1113 << auths.GetTagValue(TAG_OS_VERSION);
1114 EXPECT_TRUE(auths.Contains(TAG_OS_PATCHLEVEL, os_patch_level()))
1115 << "OS patch level is " << os_patch_level() << " key reported "
1116 << auths.GetTagValue(TAG_OS_PATCHLEVEL);
1117 }
1118 }
1119 };
1120
1121 /*
1122 * NewKeyGenerationTest.Rsa
1123 *
1124 * Verifies that keymaster can generate all required RSA key sizes, and that the resulting keys have
1125 * correct characteristics.
1126 */
TEST_F(NewKeyGenerationTest,Rsa)1127 TEST_F(NewKeyGenerationTest, Rsa) {
1128 for (auto key_size : {1024, 2048, 3072, 4096}) {
1129 HidlBuf key_blob;
1130 KeyCharacteristics key_characteristics;
1131 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1132 .RsaSigningKey(key_size, 3)
1133 .Digest(Digest::NONE)
1134 .Padding(PaddingMode::NONE)
1135 .Authorizations(UserAuths()),
1136 &key_blob, &key_characteristics));
1137
1138 ASSERT_GT(key_blob.size(), 0U);
1139 CheckBaseParams(key_characteristics, true /* asymmetric */);
1140
1141 AuthorizationSet crypto_params;
1142 if (IsSecure()) {
1143 crypto_params = key_characteristics.teeEnforced;
1144 } else {
1145 crypto_params = key_characteristics.softwareEnforced;
1146 }
1147
1148 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, KM_ALGORITHM_RSA));
1149 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size));
1150 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 3));
1151
1152 CheckedDeleteKey(&key_blob);
1153 }
1154 }
1155
1156 /*
1157 * NewKeyGenerationTest.RsaNoDefaultSize
1158 *
1159 * Verifies that failing to specify a key size for RSA key generation returns UNSUPPORTED_KEY_SIZE.
1160 */
TEST_F(NewKeyGenerationTest,RsaNoDefaultSize)1161 TEST_F(NewKeyGenerationTest, RsaNoDefaultSize) {
1162 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1163 GenerateKey(AuthorizationSetBuilder()
1164 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1165 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
1166 .SigningKey()));
1167 }
1168
1169 /*
1170 * NewKeyGenerationTest.Ecdsa
1171 *
1172 * Verifies that keymaster can generate all required EC key sizes, and that the resulting keys have
1173 * correct characteristics.
1174 */
TEST_F(NewKeyGenerationTest,Ecdsa)1175 TEST_F(NewKeyGenerationTest, Ecdsa) {
1176 for (auto key_size : {224, 256, 384, 521}) {
1177 HidlBuf key_blob;
1178 KeyCharacteristics key_characteristics;
1179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1180 .EcdsaSigningKey(key_size)
1181 .Digest(Digest::NONE)
1182 .Authorizations(UserAuths()),
1183 &key_blob, &key_characteristics));
1184 ASSERT_GT(key_blob.size(), 0U);
1185 CheckBaseParams(key_characteristics, true /* asymmetric */);
1186
1187 AuthorizationSet crypto_params;
1188 if (IsSecure()) {
1189 crypto_params = key_characteristics.teeEnforced;
1190 } else {
1191 crypto_params = key_characteristics.softwareEnforced;
1192 }
1193
1194 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1195 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size));
1196
1197 CheckedDeleteKey(&key_blob);
1198 }
1199 }
1200
1201 /*
1202 * NewKeyGenerationTest.EcdsaDefaultSize
1203 *
1204 * Verifies that failing to specify a key size for EC key generation returns UNSUPPORTED_KEY_SIZE.
1205 */
TEST_F(NewKeyGenerationTest,EcdsaDefaultSize)1206 TEST_F(NewKeyGenerationTest, EcdsaDefaultSize) {
1207 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1208 GenerateKey(AuthorizationSetBuilder()
1209 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1210 .SigningKey()
1211 .Digest(Digest::NONE)));
1212 }
1213
1214 /*
1215 * NewKeyGenerationTest.EcdsaInvalidSize
1216 *
1217 * Verifies that failing to specify an invalid key size for EC key generation returns
1218 * UNSUPPORTED_KEY_SIZE.
1219 */
TEST_F(NewKeyGenerationTest,EcdsaInvalidSize)1220 TEST_F(NewKeyGenerationTest, EcdsaInvalidSize) {
1221 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1222 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(Digest::NONE)));
1223 }
1224
1225 /*
1226 * NewKeyGenerationTest.EcdsaMismatchKeySize
1227 *
1228 * Verifies that specifying mismatched key size and curve for EC key generation returns
1229 * INVALID_ARGUMENT.
1230 */
TEST_F(NewKeyGenerationTest,EcdsaMismatchKeySize)1231 TEST_F(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1232 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1233 GenerateKey(AuthorizationSetBuilder()
1234 .EcdsaSigningKey(224)
1235 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
1236 .Digest(Digest::NONE)))
1237 << "(Possibly b/36233343)";
1238 }
1239
TEST_F(NewKeyGenerationTest,EcdsaAllValidSizes)1240 TEST_F(NewKeyGenerationTest, EcdsaAllValidSizes) {
1241 size_t valid_sizes[] = {224, 256, 384, 521};
1242 for (size_t size : valid_sizes) {
1243 EXPECT_EQ(ErrorCode::OK,
1244 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(Digest::NONE)))
1245 << "Failed to generate size: " << size;
1246 CheckedDeleteKey();
1247 }
1248 }
1249
1250 /*
1251 * NewKeyGenerationTest.EcdsaAllValidCurves
1252 *
1253 * Verifies that keymaster supports all required EC curves.
1254 */
TEST_F(NewKeyGenerationTest,EcdsaAllValidCurves)1255 TEST_F(NewKeyGenerationTest, EcdsaAllValidCurves) {
1256 EcCurve curves[] = {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1257 for (auto curve : curves) {
1258 EXPECT_EQ(
1259 ErrorCode::OK,
1260 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(curve).Digest(Digest::SHA_2_512)))
1261 << "Failed to generate key on curve: " << curve;
1262 CheckedDeleteKey();
1263 }
1264 }
1265
1266 /*
1267 * NewKeyGenerationTest.Hmac
1268 *
1269 * Verifies that keymaster supports all required digests, and that the resulting keys have correct
1270 * characteristics.
1271 */
TEST_F(NewKeyGenerationTest,Hmac)1272 TEST_F(NewKeyGenerationTest, Hmac) {
1273 for (auto digest : {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256,
1274 Digest::SHA_2_384, Digest::SHA_2_512}) {
1275 HidlBuf key_blob;
1276 KeyCharacteristics key_characteristics;
1277 constexpr size_t key_size = 128;
1278 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1279 .HmacKey(key_size)
1280 .Digest(digest)
1281 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1282 .Authorizations(UserAuths()),
1283 &key_blob, &key_characteristics));
1284
1285 ASSERT_GT(key_blob.size(), 0U);
1286 CheckBaseParams(key_characteristics);
1287
1288 AuthorizationSet teeEnforced = key_characteristics.teeEnforced;
1289 AuthorizationSet softwareEnforced = key_characteristics.softwareEnforced;
1290 if (SupportsAttestation() || SupportsAllDigests()) {
1291 // Either KM2, which must support all, or KM1 that claims full support
1292 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1293 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size));
1294 } else if (SupportsSymmetric()) {
1295 if (digest == Digest::SHA1 || digest == Digest::SHA_2_256) {
1296 // KM1 must support SHA1 and SHA256 in hardware
1297 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1298 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size));
1299 } else {
1300 // Othere digests may or may not be supported
1301 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC) ||
1302 softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1303 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size) ||
1304 softwareEnforced.Contains(TAG_KEY_SIZE, key_size));
1305 }
1306 } else {
1307 // KM0 and SW KM do all digests in SW.
1308 EXPECT_TRUE(softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1309 EXPECT_TRUE(softwareEnforced.Contains(TAG_KEY_SIZE, key_size));
1310 }
1311
1312 CheckedDeleteKey(&key_blob);
1313 }
1314 }
1315
1316 /*
1317 * NewKeyGenerationTest.HmacCheckKeySizes
1318 *
1319 * Verifies that keymaster supports all key sizes, and rejects all invalid key sizes.
1320 */
TEST_F(NewKeyGenerationTest,HmacCheckKeySizes)1321 TEST_F(NewKeyGenerationTest, HmacCheckKeySizes) {
1322 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1323 if (key_size < 64 || key_size % 8 != 0) {
1324 // To keep this test from being very slow, we only test a random fraction of non-byte
1325 // key sizes. We test only ~10% of such cases. Since there are 392 of them, we expect
1326 // to run ~40 of them in each run.
1327 if (key_size % 8 == 0 || random() % 10 == 0) {
1328 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1329 GenerateKey(AuthorizationSetBuilder()
1330 .HmacKey(key_size)
1331 .Digest(Digest::SHA_2_256)
1332 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1333 << "HMAC key size " << key_size << " invalid (Possibly b/33462346)";
1334 }
1335 } else {
1336 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1337 .HmacKey(key_size)
1338 .Digest(Digest::SHA_2_256)
1339 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1340 CheckedDeleteKey();
1341 }
1342 }
1343 }
1344
1345 /*
1346 * NewKeyGenerationTest.HmacCheckMinMacLengths
1347 *
1348 * Verifies that keymaster supports all required MAC lengths and rejects all invalid lengths. This
1349 * test is probabilistic in order to keep the runtime down, but any failure prints out the specific
1350 * MAC length that failed, so reproducing a failed run will be easy.
1351 */
TEST_F(NewKeyGenerationTest,HmacCheckMinMacLengths)1352 TEST_F(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1353 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1354 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1355 // To keep this test from being very long, we only test a random fraction of non-byte
1356 // lengths. We test only ~10% of such cases. Since there are 172 of them, we expect to
1357 // run ~17 of them in each run.
1358 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1359 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1360 GenerateKey(AuthorizationSetBuilder()
1361 .HmacKey(128)
1362 .Digest(Digest::SHA_2_256)
1363 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1364 << "HMAC min mac length " << min_mac_length << " invalid.";
1365 }
1366 } else {
1367 EXPECT_EQ(ErrorCode::OK,
1368 GenerateKey(AuthorizationSetBuilder()
1369 .HmacKey(128)
1370 .Digest(Digest::SHA_2_256)
1371 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)));
1372 CheckedDeleteKey();
1373 }
1374 }
1375 }
1376
1377 /*
1378 * NewKeyGenerationTest.HmacMultipleDigests
1379 *
1380 * Verifies that keymaster rejects HMAC key generation with multiple specified digest algorithms.
1381 */
TEST_F(NewKeyGenerationTest,HmacMultipleDigests)1382 TEST_F(NewKeyGenerationTest, HmacMultipleDigests) {
1383 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1384 GenerateKey(AuthorizationSetBuilder()
1385 .HmacKey(128)
1386 .Digest(Digest::SHA1)
1387 .Digest(Digest::SHA_2_256)
1388 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1389 }
1390
1391 /*
1392 * NewKeyGenerationTest.HmacDigestNone
1393 *
1394 * Verifies that keymaster rejects HMAC key generation with no digest or Digest::NONE
1395 */
TEST_F(NewKeyGenerationTest,HmacDigestNone)1396 TEST_F(NewKeyGenerationTest, HmacDigestNone) {
1397 ASSERT_EQ(
1398 ErrorCode::UNSUPPORTED_DIGEST,
1399 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH, 128)));
1400
1401 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1402 GenerateKey(AuthorizationSetBuilder()
1403 .HmacKey(128)
1404 .Digest(Digest::NONE)
1405 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1406 }
1407
1408 typedef KeymasterHidlTest GetKeyCharacteristicsTest;
1409
1410 /*
1411 * GetKeyCharacteristicsTest.HmacDigestNone
1412 *
1413 * Verifies that getKeyCharacteristics functions, and that generated and retrieved key
1414 * characteristics match.
1415 */
TEST_F(GetKeyCharacteristicsTest,SimpleRsa)1416 TEST_F(GetKeyCharacteristicsTest, SimpleRsa) {
1417 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1418 .RsaSigningKey(1024, 3)
1419 .Digest(Digest::NONE)
1420 .Padding(PaddingMode::NONE)));
1421
1422 KeyCharacteristics retrieved_chars;
1423 ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob_, &retrieved_chars));
1424
1425 AuthorizationSet gen_sw = key_characteristics_.softwareEnforced;
1426 AuthorizationSet gen_tee = key_characteristics_.teeEnforced;
1427 AuthorizationSet retrieved_sw = retrieved_chars.softwareEnforced;
1428 AuthorizationSet retrieved_tee = retrieved_chars.teeEnforced;
1429
1430 EXPECT_EQ(gen_sw, retrieved_sw);
1431 EXPECT_EQ(gen_tee, retrieved_tee);
1432 }
1433
1434 typedef KeymasterHidlTest SigningOperationsTest;
1435
1436 /*
1437 * SigningOperationsTest.RsaSuccess
1438 *
1439 * Verifies that raw RSA signature operations succeed.
1440 */
TEST_F(SigningOperationsTest,RsaSuccess)1441 TEST_F(SigningOperationsTest, RsaSuccess) {
1442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1443 .RsaSigningKey(1024, 3)
1444 .Digest(Digest::NONE)
1445 .Padding(PaddingMode::NONE)
1446 .Authorization(TAG_NO_AUTH_REQUIRED)));
1447 string message = "12345678901234567890123456789012";
1448 string signature = SignMessage(
1449 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1450 }
1451
1452 /*
1453 * SigningOperationsTest.RsaPssSha256Success
1454 *
1455 * Verifies that RSA-PSS signature operations succeed.
1456 */
TEST_F(SigningOperationsTest,RsaPssSha256Success)1457 TEST_F(SigningOperationsTest, RsaPssSha256Success) {
1458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1459 .RsaSigningKey(1024, 3)
1460 .Digest(Digest::SHA_2_256)
1461 .Padding(PaddingMode::RSA_PSS)
1462 .Authorization(TAG_NO_AUTH_REQUIRED)));
1463 // Use large message, which won't work without digesting.
1464 string message(1024, 'a');
1465 string signature = SignMessage(
1466 message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1467 }
1468
1469 /*
1470 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1471 *
1472 * Verifies that keymaster rejects signature operations that specify a padding mode when the key
1473 * supports only unpadded operations.
1474 */
TEST_F(SigningOperationsTest,RsaPaddingNoneDoesNotAllowOther)1475 TEST_F(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1476 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1477 .RsaSigningKey(1024, 3)
1478 .Digest(Digest::NONE)
1479 .Authorization(TAG_NO_AUTH_REQUIRED)
1480 .Padding(PaddingMode::NONE)));
1481 string message = "12345678901234567890123456789012";
1482 string signature;
1483
1484 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1485 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1486 .Digest(Digest::NONE)
1487 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1488 }
1489
1490 /*
1491 * SigningOperationsTest.RsaPkcs1Sha256Success
1492 *
1493 * Verifies that digested RSA-PKCS1 signature operations succeed.
1494 */
TEST_F(SigningOperationsTest,RsaPkcs1Sha256Success)1495 TEST_F(SigningOperationsTest, RsaPkcs1Sha256Success) {
1496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1497 .RsaSigningKey(1024, 3)
1498 .Digest(Digest::SHA_2_256)
1499 .Authorization(TAG_NO_AUTH_REQUIRED)
1500 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1501 string message(1024, 'a');
1502 string signature = SignMessage(message, AuthorizationSetBuilder()
1503 .Digest(Digest::SHA_2_256)
1504 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1505 }
1506
1507 /*
1508 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1509 *
1510 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1511 */
TEST_F(SigningOperationsTest,RsaPkcs1NoDigestSuccess)1512 TEST_F(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1513 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1514 .RsaSigningKey(1024, 3)
1515 .Digest(Digest::NONE)
1516 .Authorization(TAG_NO_AUTH_REQUIRED)
1517 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1518 string message(53, 'a');
1519 string signature = SignMessage(
1520 message,
1521 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1522 }
1523
1524 /*
1525 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1526 *
1527 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1528 * given a too-long message.
1529 */
TEST_F(SigningOperationsTest,RsaPkcs1NoDigestTooLong)1530 TEST_F(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1532 .RsaSigningKey(1024, 3)
1533 .Digest(Digest::NONE)
1534 .Authorization(TAG_NO_AUTH_REQUIRED)
1535 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1536 string message(129, 'a');
1537
1538 EXPECT_EQ(ErrorCode::OK,
1539 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1540 .Digest(Digest::NONE)
1541 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1542 string signature;
1543 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1544 }
1545
1546 /*
1547 * SigningOperationsTest.RsaPssSha512TooSmallKey
1548 *
1549 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1550 * used with a key that is too small for the message.
1551 *
1552 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the keymaster
1553 * specification requires that salt_size == digest_size, so the message will be digest_size * 2 +
1554 * 16. Such a message can only be signed by a given key if the key is at least that size. This test
1555 * uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large for a
1556 * 1024-bit key.
1557 */
TEST_F(SigningOperationsTest,RsaPssSha512TooSmallKey)1558 TEST_F(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1560 .RsaSigningKey(1024, 3)
1561 .Digest(Digest::SHA_2_512)
1562 .Authorization(TAG_NO_AUTH_REQUIRED)
1563 .Padding(PaddingMode::RSA_PSS)));
1564 EXPECT_EQ(
1565 ErrorCode::INCOMPATIBLE_DIGEST,
1566 Begin(KeyPurpose::SIGN,
1567 AuthorizationSetBuilder().Digest(Digest::SHA_2_512).Padding(PaddingMode::RSA_PSS)))
1568 << "(Possibly b/33346750)";
1569 }
1570
1571 /*
1572 * SigningOperationsTest.RsaNoPaddingTooLong
1573 *
1574 * Verifies that raw RSA signature operations fail with the correct error code when
1575 * given a too-long message.
1576 */
TEST_F(SigningOperationsTest,RsaNoPaddingTooLong)1577 TEST_F(SigningOperationsTest, RsaNoPaddingTooLong) {
1578 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1579 .RsaSigningKey(1024, 3)
1580 .Digest(Digest::NONE)
1581 .Authorization(TAG_NO_AUTH_REQUIRED)
1582 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1583 // One byte too long
1584 string message(1024 / 8 + 1, 'a');
1585 ASSERT_EQ(ErrorCode::OK,
1586 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1587 .Digest(Digest::NONE)
1588 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1589 string result;
1590 ErrorCode finish_error_code = Finish(message, &result);
1591 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1592 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1593
1594 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1595 message = string(128 * 1024, 'a');
1596 ASSERT_EQ(ErrorCode::OK,
1597 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1598 .Digest(Digest::NONE)
1599 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1600 finish_error_code = Finish(message, &result);
1601 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1602 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1603 }
1604
1605 /*
1606 * SigningOperationsTest.RsaAbort
1607 *
1608 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the test,
1609 * but the behavior should be algorithm and purpose-independent.
1610 */
TEST_F(SigningOperationsTest,RsaAbort)1611 TEST_F(SigningOperationsTest, RsaAbort) {
1612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1613 .RsaSigningKey(1024, 3)
1614 .Digest(Digest::NONE)
1615 .Authorization(TAG_NO_AUTH_REQUIRED)
1616 .Padding(PaddingMode::NONE)));
1617
1618 ASSERT_EQ(ErrorCode::OK,
1619 Begin(KeyPurpose::SIGN,
1620 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1621 EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
1622
1623 // Another abort should fail
1624 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort(op_handle_));
1625
1626 // Set to sentinel, so TearDown() doesn't try to abort again.
1627 op_handle_ = kOpHandleSentinel;
1628 }
1629
1630 /*
1631 * SigningOperationsTest.RsaUnsupportedPadding
1632 *
1633 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used with a
1634 * padding mode inappropriate for RSA.
1635 */
TEST_F(SigningOperationsTest,RsaUnsupportedPadding)1636 TEST_F(SigningOperationsTest, RsaUnsupportedPadding) {
1637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1638 .RsaSigningKey(1024, 3)
1639 .Authorization(TAG_NO_AUTH_REQUIRED)
1640 .Digest(Digest::SHA_2_256 /* supported digest */)
1641 .Padding(PaddingMode::PKCS7)));
1642 ASSERT_EQ(
1643 ErrorCode::UNSUPPORTED_PADDING_MODE,
1644 Begin(KeyPurpose::SIGN,
1645 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1646 }
1647
1648 /*
1649 * SigningOperationsTest.RsaPssNoDigest
1650 *
1651 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
1652 */
TEST_F(SigningOperationsTest,RsaNoDigest)1653 TEST_F(SigningOperationsTest, RsaNoDigest) {
1654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1655 .RsaSigningKey(1024, 3)
1656 .Authorization(TAG_NO_AUTH_REQUIRED)
1657 .Digest(Digest::NONE)
1658 .Padding(PaddingMode::RSA_PSS)));
1659 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1660 Begin(KeyPurpose::SIGN,
1661 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1662
1663 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1664 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1665 }
1666
1667 /*
1668 * SigningOperationsTest.RsaPssNoDigest
1669 *
1670 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
1671 * supported in some cases (as validated in other tests), but a mode must be specified.
1672 */
TEST_F(SigningOperationsTest,RsaNoPadding)1673 TEST_F(SigningOperationsTest, RsaNoPadding) {
1674 // Padding must be specified
1675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1676 .RsaKey(1024, 3)
1677 .Authorization(TAG_NO_AUTH_REQUIRED)
1678 .SigningKey()
1679 .Digest(Digest::NONE)));
1680 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1681 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1682 }
1683
1684 /*
1685 * SigningOperationsTest.RsaShortMessage
1686 *
1687 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1688 */
TEST_F(SigningOperationsTest,RsaTooShortMessage)1689 TEST_F(SigningOperationsTest, RsaTooShortMessage) {
1690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1691 .Authorization(TAG_NO_AUTH_REQUIRED)
1692 .RsaSigningKey(1024, 3)
1693 .Digest(Digest::NONE)
1694 .Padding(PaddingMode::NONE)));
1695
1696 // Barely shorter
1697 string message(1024 / 8 - 1, 'a');
1698 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1699
1700 // Much shorter
1701 message = "a";
1702 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1703 }
1704
1705 /*
1706 * SigningOperationsTest.RsaSignWithEncryptionKey
1707 *
1708 * Verifies that RSA encryption keys cannot be used to sign.
1709 */
TEST_F(SigningOperationsTest,RsaSignWithEncryptionKey)1710 TEST_F(SigningOperationsTest, RsaSignWithEncryptionKey) {
1711 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1712 .Authorization(TAG_NO_AUTH_REQUIRED)
1713 .RsaEncryptionKey(1024, 3)
1714 .Digest(Digest::NONE)
1715 .Padding(PaddingMode::NONE)));
1716 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1717 Begin(KeyPurpose::SIGN,
1718 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1719 }
1720
1721 /*
1722 * SigningOperationsTest.RsaSignTooLargeMessage
1723 *
1724 * Verifies that attempting a raw signature of a message which is the same length as the key, but
1725 * numerically larger than the public modulus, fails with the correct error.
1726 */
TEST_F(SigningOperationsTest,RsaSignTooLargeMessage)1727 TEST_F(SigningOperationsTest, RsaSignTooLargeMessage) {
1728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1729 .Authorization(TAG_NO_AUTH_REQUIRED)
1730 .RsaSigningKey(1024, 3)
1731 .Digest(Digest::NONE)
1732 .Padding(PaddingMode::NONE)));
1733
1734 // Largest possible message will always be larger than the public modulus.
1735 string message(1024 / 8, static_cast<char>(0xff));
1736 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1737 .Authorization(TAG_NO_AUTH_REQUIRED)
1738 .Digest(Digest::NONE)
1739 .Padding(PaddingMode::NONE)));
1740 string signature;
1741 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1742 }
1743
1744 /*
1745 * SigningOperationsTest.EcdsaAllSizesAndHashes
1746 *
1747 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1748 */
TEST_F(SigningOperationsTest,EcdsaAllSizesAndHashes)1749 TEST_F(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1750 for (auto key_size : {224, 256, 384, 521}) {
1751 for (auto digest : {
1752 Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1753 Digest::SHA_2_512,
1754 }) {
1755 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1756 .Authorization(TAG_NO_AUTH_REQUIRED)
1757 .EcdsaSigningKey(key_size)
1758 .Digest(digest));
1759 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1760 << " and digest " << digest;
1761 if (error != ErrorCode::OK) continue;
1762
1763 string message(1024, 'a');
1764 if (digest == Digest::NONE) message.resize(key_size / 8);
1765 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1766 CheckedDeleteKey();
1767 }
1768 }
1769 }
1770
1771 /*
1772 * SigningOperationsTest.EcdsaAllCurves
1773 *
1774 * Verifies that ECDSA operations succeed with all possible curves.
1775 */
TEST_F(SigningOperationsTest,EcdsaAllCurves)1776 TEST_F(SigningOperationsTest, EcdsaAllCurves) {
1777 for (auto curve : {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}) {
1778 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1779 .Authorization(TAG_NO_AUTH_REQUIRED)
1780 .EcdsaSigningKey(curve)
1781 .Digest(Digest::SHA_2_256));
1782 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1783 if (error != ErrorCode::OK) continue;
1784
1785 string message(1024, 'a');
1786 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1787 CheckedDeleteKey();
1788 }
1789 }
1790
1791 /*
1792 * SigningOperationsTest.EcdsaNoDigestHugeData
1793 *
1794 * Verifies that ECDSA operations support very large messages, even without digesting. This should
1795 * work because ECDSA actually only signs the leftmost L_n bits of the message, however large it may
1796 * be. Not using digesting is a bad idea, but in some cases digesting is done by the framework.
1797 */
TEST_F(SigningOperationsTest,EcdsaNoDigestHugeData)1798 TEST_F(SigningOperationsTest, EcdsaNoDigestHugeData) {
1799 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1800 .Authorization(TAG_NO_AUTH_REQUIRED)
1801 .EcdsaSigningKey(224)
1802 .Digest(Digest::NONE)));
1803 string message(2 * 1024, 'a');
1804 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1805 }
1806
1807 /*
1808 * SigningOperationsTest.AesEcbSign
1809 *
1810 * Verifies that attempts to use AES keys to sign fail in the correct way.
1811 */
TEST_F(SigningOperationsTest,AesEcbSign)1812 TEST_F(SigningOperationsTest, AesEcbSign) {
1813 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1814 .Authorization(TAG_NO_AUTH_REQUIRED)
1815 .SigningKey()
1816 .AesEncryptionKey(128)
1817 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)))
1818 << "(Possibly b/36252957)";
1819
1820 AuthorizationSet out_params;
1821 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1822 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params))
1823 << "(Possibly b/36233187)";
1824
1825 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1826 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params))
1827 << "(Possibly b/36233187)";
1828 }
1829
1830 /*
1831 * SigningOperationsTest.HmacAllDigests
1832 *
1833 * Verifies that HMAC works with all digests.
1834 */
TEST_F(SigningOperationsTest,HmacAllDigests)1835 TEST_F(SigningOperationsTest, HmacAllDigests) {
1836 for (auto digest : {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1837 Digest::SHA_2_512}) {
1838 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1839 .Authorization(TAG_NO_AUTH_REQUIRED)
1840 .HmacKey(128)
1841 .Digest(digest)
1842 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1843 << "Failed to create HMAC key with digest " << digest;
1844 string message = "12345678901234567890123456789012";
1845 string signature = MacMessage(message, digest, 160);
1846 EXPECT_EQ(160U / 8U, signature.size())
1847 << "Failed to sign with HMAC key with digest " << digest;
1848 CheckedDeleteKey();
1849 }
1850 }
1851
1852 /*
1853 * SigningOperationsTest.HmacSha256TooLargeMacLength
1854 *
1855 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the digest
1856 * size.
1857 */
TEST_F(SigningOperationsTest,HmacSha256TooLargeMacLength)1858 TEST_F(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1859 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1860 .Authorization(TAG_NO_AUTH_REQUIRED)
1861 .HmacKey(128)
1862 .Digest(Digest::SHA_2_256)
1863 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1864 AuthorizationSet output_params;
1865 EXPECT_EQ(
1866 ErrorCode::UNSUPPORTED_MAC_LENGTH,
1867 Begin(
1868 KeyPurpose::SIGN, key_blob_,
1869 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 264),
1870 &output_params, &op_handle_));
1871 }
1872
1873 /*
1874 * SigningOperationsTest.HmacSha256TooSmallMacLength
1875 *
1876 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1877 * specified minimum MAC length.
1878 */
TEST_F(SigningOperationsTest,HmacSha256TooSmallMacLength)1879 TEST_F(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1880 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1881 .Authorization(TAG_NO_AUTH_REQUIRED)
1882 .HmacKey(128)
1883 .Digest(Digest::SHA_2_256)
1884 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1885 AuthorizationSet output_params;
1886 EXPECT_EQ(
1887 ErrorCode::INVALID_MAC_LENGTH,
1888 Begin(
1889 KeyPurpose::SIGN, key_blob_,
1890 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 120),
1891 &output_params, &op_handle_));
1892 }
1893
1894 /*
1895 * SigningOperationsTest.HmacRfc4231TestCase3
1896 *
1897 * Validates against the test vectors from RFC 4231 test case 3.
1898 */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase3)1899 TEST_F(SigningOperationsTest, HmacRfc4231TestCase3) {
1900 string key(20, 0xaa);
1901 string message(50, 0xdd);
1902 uint8_t sha_224_expected[] = {
1903 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1904 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1905 };
1906 uint8_t sha_256_expected[] = {
1907 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1908 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1909 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1910 };
1911 uint8_t sha_384_expected[] = {
1912 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1913 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1914 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1915 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1916 };
1917 uint8_t sha_512_expected[] = {
1918 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1919 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1920 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1921 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1922 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1923 };
1924
1925 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1926 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1927 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1928 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1929 }
1930
1931 /*
1932 * SigningOperationsTest.HmacRfc4231TestCase5
1933 *
1934 * Validates against the test vectors from RFC 4231 test case 5.
1935 */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase5)1936 TEST_F(SigningOperationsTest, HmacRfc4231TestCase5) {
1937 string key(20, 0x0c);
1938 string message = "Test With Truncation";
1939
1940 uint8_t sha_224_expected[] = {
1941 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1942 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1943 };
1944 uint8_t sha_256_expected[] = {
1945 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1946 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1947 };
1948 uint8_t sha_384_expected[] = {
1949 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1950 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1951 };
1952 uint8_t sha_512_expected[] = {
1953 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1954 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1955 };
1956
1957 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1958 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1959 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1960 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1961 }
1962
1963 /*
1964 * SigningOperationsTest.HmacRfc4231TestCase6
1965 *
1966 * Validates against the test vectors from RFC 4231 test case 6.
1967 */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase6)1968 TEST_F(SigningOperationsTest, HmacRfc4231TestCase6) {
1969 string key(131, 0xaa);
1970 string message = "Test Using Larger Than Block-Size Key - Hash Key First";
1971
1972 uint8_t sha_224_expected[] = {
1973 0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
1974 0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
1975 };
1976 uint8_t sha_256_expected[] = {
1977 0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
1978 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
1979 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
1980 };
1981 uint8_t sha_384_expected[] = {
1982 0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
1983 0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
1984 0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
1985 0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
1986 };
1987 uint8_t sha_512_expected[] = {
1988 0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
1989 0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
1990 0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
1991 0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
1992 0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
1993 };
1994
1995 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1996 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1997 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1998 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1999 }
2000
2001 /*
2002 * SigningOperationsTest.HmacRfc4231TestCase7
2003 *
2004 * Validates against the test vectors from RFC 4231 test case 7.
2005 */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase7)2006 TEST_F(SigningOperationsTest, HmacRfc4231TestCase7) {
2007 string key(131, 0xaa);
2008 string message = "This is a test using a larger than block-size key and a larger than "
2009 "block-size data. The key needs to be hashed before being used by the HMAC "
2010 "algorithm.";
2011
2012 uint8_t sha_224_expected[] = {
2013 0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
2014 0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
2015 };
2016 uint8_t sha_256_expected[] = {
2017 0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
2018 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
2019 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
2020 };
2021 uint8_t sha_384_expected[] = {
2022 0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
2023 0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
2024 0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
2025 0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
2026 };
2027 uint8_t sha_512_expected[] = {
2028 0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
2029 0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
2030 0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
2031 0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
2032 0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
2033 };
2034
2035 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2036 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2037 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2038 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2039 }
2040
2041 typedef KeymasterHidlTest VerificationOperationsTest;
2042
2043 /*
2044 * VerificationOperationsTest.RsaSuccess
2045 *
2046 * Verifies that a simple RSA signature/verification sequence succeeds.
2047 */
TEST_F(VerificationOperationsTest,RsaSuccess)2048 TEST_F(VerificationOperationsTest, RsaSuccess) {
2049 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2050 .Authorization(TAG_NO_AUTH_REQUIRED)
2051 .RsaSigningKey(1024, 3)
2052 .Digest(Digest::NONE)
2053 .Padding(PaddingMode::NONE)));
2054 string message = "12345678901234567890123456789012";
2055 string signature = SignMessage(
2056 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2057 VerifyMessage(message, signature,
2058 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2059 }
2060
2061 /*
2062 * VerificationOperationsTest.RsaSuccess
2063 *
2064 * Verifies RSA signature/verification for all padding modes and digests.
2065 */
TEST_F(VerificationOperationsTest,RsaAllPaddingsAndDigests)2066 TEST_F(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2067 ASSERT_EQ(ErrorCode::OK,
2068 GenerateKey(AuthorizationSetBuilder()
2069 .Authorization(TAG_NO_AUTH_REQUIRED)
2070 .RsaSigningKey(2048, 3)
2071 .Digest(Digest::NONE, Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
2072 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512)
2073 .Padding(PaddingMode::NONE)
2074 .Padding(PaddingMode::RSA_PSS)
2075 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2076
2077 string message(128, 'a');
2078 string corrupt_message(message);
2079 ++corrupt_message[corrupt_message.size() / 2];
2080
2081 for (auto padding :
2082 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2083
2084 for (auto digest : {Digest::NONE, Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
2085 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}) {
2086 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2087 // Digesting only makes sense with padding.
2088 continue;
2089 }
2090
2091 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2092 // PSS requires digesting.
2093 continue;
2094 }
2095
2096 string signature =
2097 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2098 VerifyMessage(message, signature,
2099 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2100
2101 if (digest != Digest::NONE) {
2102 // Verify with OpenSSL.
2103 HidlBuf pubkey;
2104 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2105
2106 const uint8_t* p = pubkey.data();
2107 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
2108 ASSERT_TRUE(pkey.get());
2109
2110 EVP_MD_CTX digest_ctx;
2111 EVP_MD_CTX_init(&digest_ctx);
2112 EVP_PKEY_CTX* pkey_ctx;
2113 const EVP_MD* md = openssl_digest(digest);
2114 ASSERT_NE(md, nullptr);
2115 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */,
2116 pkey.get()));
2117
2118 switch (padding) {
2119 case PaddingMode::RSA_PSS:
2120 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
2121 EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
2122 break;
2123 case PaddingMode::RSA_PKCS1_1_5_SIGN:
2124 // PKCS1 is the default; don't need to set anything.
2125 break;
2126 default:
2127 FAIL();
2128 break;
2129 }
2130
2131 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
2132 EXPECT_EQ(1, EVP_DigestVerifyFinal(
2133 &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
2134 signature.size()));
2135 EVP_MD_CTX_cleanup(&digest_ctx);
2136 }
2137
2138 // Corrupt signature shouldn't verify.
2139 string corrupt_signature(signature);
2140 ++corrupt_signature[corrupt_signature.size() / 2];
2141
2142 EXPECT_EQ(ErrorCode::OK,
2143 Begin(KeyPurpose::VERIFY,
2144 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2145 string result;
2146 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2147
2148 // Corrupt message shouldn't verify
2149 EXPECT_EQ(ErrorCode::OK,
2150 Begin(KeyPurpose::VERIFY,
2151 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2152 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2153 }
2154 }
2155 }
2156
2157 /*
2158 * VerificationOperationsTest.RsaSuccess
2159 *
2160 * Verifies ECDSA signature/verification for all digests and curves.
2161 */
TEST_F(VerificationOperationsTest,EcdsaAllDigestsAndCurves)2162 TEST_F(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2163 auto digests = {
2164 Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
2165 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512,
2166 };
2167
2168 string message = "1234567890";
2169 string corrupt_message = "2234567890";
2170 for (auto curve : {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}) {
2171 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2172 .Authorization(TAG_NO_AUTH_REQUIRED)
2173 .EcdsaSigningKey(curve)
2174 .Digest(digests));
2175 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2176 if (error != ErrorCode::OK) {
2177 continue;
2178 }
2179
2180 for (auto digest : digests) {
2181 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2182 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2183
2184 // Verify with OpenSSL
2185 if (digest != Digest::NONE) {
2186 HidlBuf pubkey;
2187 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2188 << curve << ' ' << digest;
2189
2190 const uint8_t* p = pubkey.data();
2191 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
2192 ASSERT_TRUE(pkey.get());
2193
2194 EVP_MD_CTX digest_ctx;
2195 EVP_MD_CTX_init(&digest_ctx);
2196 EVP_PKEY_CTX* pkey_ctx;
2197 const EVP_MD* md = openssl_digest(digest);
2198
2199 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */,
2200 pkey.get()))
2201 << curve << ' ' << digest;
2202
2203 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()))
2204 << curve << ' ' << digest;
2205
2206 EXPECT_EQ(1, EVP_DigestVerifyFinal(
2207 &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
2208 signature.size()))
2209 << curve << ' ' << digest;
2210
2211 EVP_MD_CTX_cleanup(&digest_ctx);
2212 }
2213
2214 // Corrupt signature shouldn't verify.
2215 string corrupt_signature(signature);
2216 ++corrupt_signature[corrupt_signature.size() / 2];
2217
2218 EXPECT_EQ(ErrorCode::OK,
2219 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2220 << curve << ' ' << digest;
2221
2222 string result;
2223 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2224 << curve << ' ' << digest;
2225
2226 // Corrupt message shouldn't verify
2227 EXPECT_EQ(ErrorCode::OK,
2228 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2229 << curve << ' ' << digest;
2230
2231 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2232 << curve << ' ' << digest;
2233 }
2234
2235 auto rc = DeleteKey();
2236 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2237 }
2238 }
2239
2240 /*
2241 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2242 *
2243 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2244 */
TEST_F(VerificationOperationsTest,HmacSigningKeyCannotVerify)2245 TEST_F(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2246 string key_material = "HelloThisIsAKey";
2247
2248 HidlBuf signing_key, verification_key;
2249 KeyCharacteristics signing_key_chars, verification_key_chars;
2250 EXPECT_EQ(ErrorCode::OK,
2251 ImportKey(AuthorizationSetBuilder()
2252 .Authorization(TAG_NO_AUTH_REQUIRED)
2253 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2254 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2255 .Digest(Digest::SHA1)
2256 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2257 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2258 EXPECT_EQ(ErrorCode::OK,
2259 ImportKey(AuthorizationSetBuilder()
2260 .Authorization(TAG_NO_AUTH_REQUIRED)
2261 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2262 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2263 .Digest(Digest::SHA1)
2264 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2265 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2266
2267 string message = "This is a message.";
2268 string signature = SignMessage(
2269 signing_key, message,
2270 AuthorizationSetBuilder().Digest(Digest::SHA1).Authorization(TAG_MAC_LENGTH, 160));
2271
2272 // Signing key should not work.
2273 AuthorizationSet out_params;
2274 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2275 Begin(KeyPurpose::VERIFY, signing_key, AuthorizationSetBuilder().Digest(Digest::SHA1),
2276 &out_params, &op_handle_));
2277
2278 // Verification key should work.
2279 VerifyMessage(verification_key, message, signature,
2280 AuthorizationSetBuilder().Digest(Digest::SHA1));
2281
2282 CheckedDeleteKey(&signing_key);
2283 CheckedDeleteKey(&verification_key);
2284 }
2285
2286 typedef KeymasterHidlTest ExportKeyTest;
2287
2288 /*
2289 * ExportKeyTest.RsaUnsupportedKeyFormat
2290 *
2291 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2292 */
TEST_F(ExportKeyTest,RsaUnsupportedKeyFormat)2293 TEST_F(ExportKeyTest, RsaUnsupportedKeyFormat) {
2294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2295 .RsaSigningKey(1024, 3)
2296 .Digest(Digest::NONE)
2297 .Padding(PaddingMode::NONE)));
2298 HidlBuf export_data;
2299 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data));
2300 }
2301
2302 /*
2303 * ExportKeyTest.RsaCorruptedKeyBlob
2304 *
2305 * Verifies that attempting to export RSA keys from corrupted key blobs fails. This is essentially
2306 * a poor-man's key blob fuzzer.
2307 */
TEST_F(ExportKeyTest,RsaCorruptedKeyBlob)2308 TEST_F(ExportKeyTest, RsaCorruptedKeyBlob) {
2309 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2310 .Authorization(TAG_NO_AUTH_REQUIRED)
2311 .RsaSigningKey(1024, 3)
2312 .Digest(Digest::NONE)
2313 .Padding(PaddingMode::NONE)));
2314 for (size_t i = 0; i < key_blob_.size(); ++i) {
2315 HidlBuf corrupted(key_blob_);
2316 ++corrupted[i];
2317
2318 HidlBuf export_data;
2319 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2320 ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data))
2321 << "Blob corrupted at offset " << i << " erroneously accepted as valid";
2322 }
2323 }
2324
2325 /*
2326 * ExportKeyTest.RsaCorruptedKeyBlob
2327 *
2328 * Verifies that attempting to export ECDSA keys from corrupted key blobs fails. This is
2329 * essentially a poor-man's key blob fuzzer.
2330 */
TEST_F(ExportKeyTest,EcCorruptedKeyBlob)2331 TEST_F(ExportKeyTest, EcCorruptedKeyBlob) {
2332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2333 .Authorization(TAG_NO_AUTH_REQUIRED)
2334 .EcdsaSigningKey(EcCurve::P_256)
2335 .Digest(Digest::NONE)));
2336 for (size_t i = 0; i < key_blob_.size(); ++i) {
2337 HidlBuf corrupted(key_blob_);
2338 ++corrupted[i];
2339
2340 HidlBuf export_data;
2341 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2342 ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data))
2343 << "Blob corrupted at offset " << i << " erroneously accepted as valid";
2344 }
2345 }
2346
2347 /*
2348 * ExportKeyTest.AesKeyUnexportable
2349 *
2350 * Verifies that attempting to export AES keys fails in the expected way.
2351 */
TEST_F(ExportKeyTest,AesKeyUnexportable)2352 TEST_F(ExportKeyTest, AesKeyUnexportable) {
2353 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2354 .Authorization(TAG_NO_AUTH_REQUIRED)
2355 .AesEncryptionKey(128)
2356 .EcbMode()
2357 .Padding(PaddingMode::NONE)));
2358
2359 HidlBuf export_data;
2360 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::X509, &export_data));
2361 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data));
2362 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::RAW, &export_data));
2363 }
2364 typedef KeymasterHidlTest ImportKeyTest;
2365
2366 /*
2367 * ImportKeyTest.RsaSuccess
2368 *
2369 * Verifies that importing and using an RSA key pair works correctly.
2370 */
TEST_F(ImportKeyTest,RsaSuccess)2371 TEST_F(ImportKeyTest, RsaSuccess) {
2372 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2373 .Authorization(TAG_NO_AUTH_REQUIRED)
2374 .RsaSigningKey(1024, 65537)
2375 .Digest(Digest::SHA_2_256)
2376 .Padding(PaddingMode::RSA_PSS),
2377 KeyFormat::PKCS8, rsa_key));
2378
2379 CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::RSA);
2380 CheckKm0CryptoParam(TAG_KEY_SIZE, 1024U);
2381 CheckKm0CryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2382 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2383 CheckKm1CryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2384 CheckOrigin(true /* asymmetric */);
2385
2386 string message(1024 / 8, 'a');
2387 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2388 string signature = SignMessage(message, params);
2389 VerifyMessage(message, signature, params);
2390 }
2391
2392 /*
2393 * ImportKeyTest.RsaKeySizeMismatch
2394 *
2395 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2396 * correct way.
2397 */
TEST_F(ImportKeyTest,RsaKeySizeMismatch)2398 TEST_F(ImportKeyTest, RsaKeySizeMismatch) {
2399 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2400 ImportKey(AuthorizationSetBuilder()
2401 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2402 .Digest(Digest::NONE)
2403 .Padding(PaddingMode::NONE),
2404 KeyFormat::PKCS8, rsa_key));
2405 }
2406
2407 /*
2408 * ImportKeyTest.RsaPublicExponentMismatch
2409 *
2410 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key fails
2411 * in the correct way.
2412 */
TEST_F(ImportKeyTest,RsaPublicExponentMismatch)2413 TEST_F(ImportKeyTest, RsaPublicExponentMismatch) {
2414 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2415 ImportKey(AuthorizationSetBuilder()
2416 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2417 .Digest(Digest::NONE)
2418 .Padding(PaddingMode::NONE),
2419 KeyFormat::PKCS8, rsa_key));
2420 }
2421
2422 /*
2423 * ImportKeyTest.EcdsaSuccess
2424 *
2425 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2426 */
TEST_F(ImportKeyTest,EcdsaSuccess)2427 TEST_F(ImportKeyTest, EcdsaSuccess) {
2428 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2429 .Authorization(TAG_NO_AUTH_REQUIRED)
2430 .EcdsaSigningKey(256)
2431 .Digest(Digest::SHA_2_256),
2432 KeyFormat::PKCS8, ec_256_key))
2433 << "(Possibly b/33945114)";
2434
2435 CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::EC);
2436 CheckKm0CryptoParam(TAG_KEY_SIZE, 256U);
2437 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2438 CheckKm2CryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2439
2440 CheckOrigin(true /* asymmetric */);
2441
2442 string message(32, 'a');
2443 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2444 string signature = SignMessage(message, params);
2445 VerifyMessage(message, signature, params);
2446 }
2447
2448 /*
2449 * ImportKeyTest.Ecdsa521Success
2450 *
2451 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2452 */
TEST_F(ImportKeyTest,Ecdsa521Success)2453 TEST_F(ImportKeyTest, Ecdsa521Success) {
2454 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2455 .Authorization(TAG_NO_AUTH_REQUIRED)
2456 .EcdsaSigningKey(521)
2457 .Digest(Digest::SHA_2_256),
2458 KeyFormat::PKCS8, ec_521_key))
2459 << "(Possibly b/33945114)";
2460
2461 CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::EC);
2462 CheckKm0CryptoParam(TAG_KEY_SIZE, 521U);
2463 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2464 CheckKm2CryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2465
2466 CheckOrigin(true /* asymmetric */);
2467
2468 string message(32, 'a');
2469 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2470 string signature = SignMessage(message, params);
2471 VerifyMessage(message, signature, params);
2472 }
2473
2474 /*
2475 * ImportKeyTest.EcdsaSizeMismatch
2476 *
2477 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2478 * correct way.
2479 */
TEST_F(ImportKeyTest,EcdsaSizeMismatch)2480 TEST_F(ImportKeyTest, EcdsaSizeMismatch) {
2481 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2482 ImportKey(AuthorizationSetBuilder()
2483 .EcdsaSigningKey(224 /* Doesn't match key */)
2484 .Digest(Digest::NONE),
2485 KeyFormat::PKCS8, ec_256_key));
2486 }
2487
2488 /*
2489 * ImportKeyTest.EcdsaCurveMismatch
2490 *
2491 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in the
2492 * correct way.
2493 */
TEST_F(ImportKeyTest,EcdsaCurveMismatch)2494 TEST_F(ImportKeyTest, EcdsaCurveMismatch) {
2495 if (SupportsSymmetric() && !SupportsAttestation()) {
2496 // KM1 hardware doesn't know about curves
2497 return;
2498 }
2499
2500 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2501 ImportKey(AuthorizationSetBuilder()
2502 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
2503 .Digest(Digest::NONE),
2504 KeyFormat::PKCS8, ec_256_key))
2505 << "(Possibly b/36233241)";
2506 }
2507
2508 /*
2509 * ImportKeyTest.AesSuccess
2510 *
2511 * Verifies that importing and using an AES key works.
2512 */
TEST_F(ImportKeyTest,AesSuccess)2513 TEST_F(ImportKeyTest, AesSuccess) {
2514 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2515 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2516 .Authorization(TAG_NO_AUTH_REQUIRED)
2517 .AesEncryptionKey(key.size() * 8)
2518 .EcbMode()
2519 .Padding(PaddingMode::PKCS7),
2520 KeyFormat::RAW, key));
2521
2522 CheckKm1CryptoParam(TAG_ALGORITHM, Algorithm::AES);
2523 CheckKm1CryptoParam(TAG_KEY_SIZE, 128U);
2524 CheckKm1CryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2525 CheckKm1CryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2526 CheckOrigin();
2527
2528 string message = "Hello World!";
2529 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2530 string ciphertext = EncryptMessage(message, params);
2531 string plaintext = DecryptMessage(ciphertext, params);
2532 EXPECT_EQ(message, plaintext);
2533 }
2534
2535 /*
2536 * ImportKeyTest.AesSuccess
2537 *
2538 * Verifies that importing and using an HMAC key works.
2539 */
TEST_F(ImportKeyTest,HmacKeySuccess)2540 TEST_F(ImportKeyTest, HmacKeySuccess) {
2541 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2542 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2543 .Authorization(TAG_NO_AUTH_REQUIRED)
2544 .HmacKey(key.size() * 8)
2545 .Digest(Digest::SHA_2_256)
2546 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2547 KeyFormat::RAW, key));
2548
2549 CheckKm1CryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2550 CheckKm1CryptoParam(TAG_KEY_SIZE, 128U);
2551 CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2552 CheckOrigin();
2553
2554 string message = "Hello World!";
2555 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2556 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2557 }
2558
2559 typedef KeymasterHidlTest EncryptionOperationsTest;
2560
2561 /*
2562 * EncryptionOperationsTest.RsaNoPaddingSuccess
2563 *
2564 * Verifies that raw RSA encryption works.
2565 */
TEST_F(EncryptionOperationsTest,RsaNoPaddingSuccess)2566 TEST_F(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2567 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2568 .Authorization(TAG_NO_AUTH_REQUIRED)
2569 .RsaEncryptionKey(1024, 3)
2570 .Padding(PaddingMode::NONE)));
2571
2572 string message = string(1024 / 8, 'a');
2573 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2574 string ciphertext1 = EncryptMessage(message, params);
2575 EXPECT_EQ(1024U / 8, ciphertext1.size());
2576
2577 string ciphertext2 = EncryptMessage(message, params);
2578 EXPECT_EQ(1024U / 8, ciphertext2.size());
2579
2580 // Unpadded RSA is deterministic
2581 EXPECT_EQ(ciphertext1, ciphertext2);
2582 }
2583
2584 /*
2585 * EncryptionOperationsTest.RsaNoPaddingShortMessage
2586 *
2587 * Verifies that raw RSA encryption of short messages works.
2588 */
TEST_F(EncryptionOperationsTest,RsaNoPaddingShortMessage)2589 TEST_F(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2591 .Authorization(TAG_NO_AUTH_REQUIRED)
2592 .RsaEncryptionKey(1024, 3)
2593 .Padding(PaddingMode::NONE)));
2594
2595 string message = "1";
2596 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2597
2598 string ciphertext = EncryptMessage(message, params);
2599 EXPECT_EQ(1024U / 8, ciphertext.size());
2600
2601 string expected_plaintext = string(1024 / 8 - 1, 0) + message;
2602 string plaintext = DecryptMessage(ciphertext, params);
2603
2604 EXPECT_EQ(expected_plaintext, plaintext);
2605
2606 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2607 message = static_cast<char>(1);
2608 ciphertext = EncryptMessage(message, params);
2609 EXPECT_EQ(1024U / 8, ciphertext.size());
2610 EXPECT_EQ(ciphertext, string(1024 / 8 - 1, 0) + message);
2611 }
2612
2613 /*
2614 * EncryptionOperationsTest.RsaNoPaddingTooLong
2615 *
2616 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2617 */
TEST_F(EncryptionOperationsTest,RsaNoPaddingTooLong)2618 TEST_F(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2619 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2620 .Authorization(TAG_NO_AUTH_REQUIRED)
2621 .RsaEncryptionKey(1024, 3)
2622 .Padding(PaddingMode::NONE)));
2623
2624 string message(1024 / 8 + 1, 'a');
2625
2626 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2627 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2628
2629 string result;
2630 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2631 }
2632
2633 /*
2634 * EncryptionOperationsTest.RsaNoPaddingTooLarge
2635 *
2636 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected way.
2637 */
TEST_F(EncryptionOperationsTest,RsaNoPaddingTooLarge)2638 TEST_F(EncryptionOperationsTest, RsaNoPaddingTooLarge) {
2639 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2640 .Authorization(TAG_NO_AUTH_REQUIRED)
2641 .RsaEncryptionKey(1024, 3)
2642 .Padding(PaddingMode::NONE)));
2643
2644 HidlBuf exported;
2645 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &exported));
2646
2647 const uint8_t* p = exported.data();
2648 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
2649 RSA_Ptr rsa(EVP_PKEY_get1_RSA(pkey.get()));
2650
2651 size_t modulus_len = BN_num_bytes(rsa->n);
2652 ASSERT_EQ(1024U / 8, modulus_len);
2653 std::unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
2654 BN_bn2bin(rsa->n, modulus_buf.get());
2655
2656 // The modulus is too big to encrypt.
2657 string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2658
2659 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2660 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2661
2662 string result;
2663 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &result));
2664
2665 // One smaller than the modulus is okay.
2666 BN_sub(rsa->n, rsa->n, BN_value_one());
2667 modulus_len = BN_num_bytes(rsa->n);
2668 ASSERT_EQ(1024U / 8, modulus_len);
2669 BN_bn2bin(rsa->n, modulus_buf.get());
2670 message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2671 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2672 EXPECT_EQ(ErrorCode::OK, Finish(message, &result));
2673 }
2674
2675 /*
2676 * EncryptionOperationsTest.RsaOaepSuccess
2677 *
2678 * Verifies that RSA-OAEP encryption operations work, with all digests.
2679 */
TEST_F(EncryptionOperationsTest,RsaOaepSuccess)2680 TEST_F(EncryptionOperationsTest, RsaOaepSuccess) {
2681 auto digests = {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
2682 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
2683
2684 size_t key_size = 2048; // Need largish key for SHA-512 test.
2685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2686 .Authorization(TAG_NO_AUTH_REQUIRED)
2687 .RsaEncryptionKey(key_size, 3)
2688 .Padding(PaddingMode::RSA_OAEP)
2689 .Digest(digests)));
2690
2691 string message = "Hello";
2692
2693 for (auto digest : digests) {
2694 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2695 string ciphertext1 = EncryptMessage(message, params);
2696 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2697 EXPECT_EQ(key_size / 8, ciphertext1.size());
2698
2699 string ciphertext2 = EncryptMessage(message, params);
2700 EXPECT_EQ(key_size / 8, ciphertext2.size());
2701
2702 // OAEP randomizes padding so every result should be different (with astronomically high
2703 // probability).
2704 EXPECT_NE(ciphertext1, ciphertext2);
2705
2706 string plaintext1 = DecryptMessage(ciphertext1, params);
2707 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2708 string plaintext2 = DecryptMessage(ciphertext2, params);
2709 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2710
2711 // Decrypting corrupted ciphertext should fail.
2712 size_t offset_to_corrupt = random() % ciphertext1.size();
2713 char corrupt_byte;
2714 do {
2715 corrupt_byte = static_cast<char>(random() % 256);
2716 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2717 ciphertext1[offset_to_corrupt] = corrupt_byte;
2718
2719 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2720 string result;
2721 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2722 EXPECT_EQ(0U, result.size());
2723 }
2724 }
2725
2726 /*
2727 * EncryptionOperationsTest.RsaOaepInvalidDigest
2728 *
2729 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2730 * without a digest.
2731 */
TEST_F(EncryptionOperationsTest,RsaOaepInvalidDigest)2732 TEST_F(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2733 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2734 .Authorization(TAG_NO_AUTH_REQUIRED)
2735 .RsaEncryptionKey(1024, 3)
2736 .Padding(PaddingMode::RSA_OAEP)
2737 .Digest(Digest::NONE)));
2738 string message = "Hello World!";
2739
2740 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2741 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2742 }
2743
2744 /*
2745 * EncryptionOperationsTest.RsaOaepInvalidDigest
2746 *
2747 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt with a
2748 * different digest than was used to encrypt.
2749 */
TEST_F(EncryptionOperationsTest,RsaOaepDecryptWithWrongDigest)2750 TEST_F(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .RsaEncryptionKey(1024, 3)
2754 .Padding(PaddingMode::RSA_OAEP)
2755 .Digest(Digest::SHA_2_256, Digest::SHA_2_224)));
2756 string message = "Hello World!";
2757 string ciphertext = EncryptMessage(
2758 message,
2759 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2760
2761 EXPECT_EQ(
2762 ErrorCode::OK,
2763 Begin(KeyPurpose::DECRYPT,
2764 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP)));
2765 string result;
2766 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2767 EXPECT_EQ(0U, result.size());
2768 }
2769
2770 /*
2771 * EncryptionOperationsTest.RsaOaepTooLarge
2772 *
2773 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2774 * too-large message.
2775 */
TEST_F(EncryptionOperationsTest,RsaOaepTooLarge)2776 TEST_F(EncryptionOperationsTest, RsaOaepTooLarge) {
2777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2778 .Authorization(TAG_NO_AUTH_REQUIRED)
2779 .RsaEncryptionKey(1024, 3)
2780 .Padding(PaddingMode::RSA_OAEP)
2781 .Digest(Digest::SHA1)));
2782 constexpr size_t digest_size = 160 /* SHA1 */ / 8;
2783 constexpr size_t oaep_overhead = 2 * digest_size + 2;
2784 string message(1024 / 8 - oaep_overhead + 1, 'a');
2785 EXPECT_EQ(ErrorCode::OK,
2786 Begin(KeyPurpose::ENCRYPT,
2787 AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::SHA1)));
2788 string result;
2789 auto error = Finish(message, &result);
2790 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2791 EXPECT_EQ(0U, result.size());
2792 }
2793
2794 /*
2795 * EncryptionOperationsTest.RsaPkcs1Success
2796 *
2797 * Verifies that RSA PKCS encryption/decrypts works.
2798 */
TEST_F(EncryptionOperationsTest,RsaPkcs1Success)2799 TEST_F(EncryptionOperationsTest, RsaPkcs1Success) {
2800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2801 .Authorization(TAG_NO_AUTH_REQUIRED)
2802 .RsaEncryptionKey(1024, 3)
2803 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2804
2805 string message = "Hello World!";
2806 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2807 string ciphertext1 = EncryptMessage(message, params);
2808 EXPECT_EQ(1024U / 8, ciphertext1.size());
2809
2810 string ciphertext2 = EncryptMessage(message, params);
2811 EXPECT_EQ(1024U / 8, ciphertext2.size());
2812
2813 // PKCS1 v1.5 randomizes padding so every result should be different.
2814 EXPECT_NE(ciphertext1, ciphertext2);
2815
2816 string plaintext = DecryptMessage(ciphertext1, params);
2817 EXPECT_EQ(message, plaintext);
2818
2819 // Decrypting corrupted ciphertext should fail.
2820 size_t offset_to_corrupt = random() % ciphertext1.size();
2821 char corrupt_byte;
2822 do {
2823 corrupt_byte = static_cast<char>(random() % 256);
2824 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2825 ciphertext1[offset_to_corrupt] = corrupt_byte;
2826
2827 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2828 string result;
2829 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2830 EXPECT_EQ(0U, result.size());
2831 }
2832
2833 /*
2834 * EncryptionOperationsTest.RsaPkcs1TooLarge
2835 *
2836 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2837 */
TEST_F(EncryptionOperationsTest,RsaPkcs1TooLarge)2838 TEST_F(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2839 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2840 .Authorization(TAG_NO_AUTH_REQUIRED)
2841 .RsaEncryptionKey(1024, 3)
2842 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2843 string message(1024 / 8 - 10, 'a');
2844
2845 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2846 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2847 string result;
2848 auto error = Finish(message, &result);
2849 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2850 EXPECT_EQ(0U, result.size());
2851 }
2852
2853 /*
2854 * EncryptionOperationsTest.EcdsaEncrypt
2855 *
2856 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2857 */
TEST_F(EncryptionOperationsTest,EcdsaEncrypt)2858 TEST_F(EncryptionOperationsTest, EcdsaEncrypt) {
2859 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2860 .Authorization(TAG_NO_AUTH_REQUIRED)
2861 .EcdsaSigningKey(224)
2862 .Digest(Digest::NONE)));
2863 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2864 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params))
2865 << "(Possibly b/33543625)";
2866 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params))
2867 << "(Possibly b/33543625)";
2868 }
2869
2870 /*
2871 * EncryptionOperationsTest.HmacEncrypt
2872 *
2873 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2874 */
TEST_F(EncryptionOperationsTest,HmacEncrypt)2875 TEST_F(EncryptionOperationsTest, HmacEncrypt) {
2876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2877 .Authorization(TAG_NO_AUTH_REQUIRED)
2878 .HmacKey(128)
2879 .Digest(Digest::SHA_2_256)
2880 .Padding(PaddingMode::NONE)
2881 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2882 auto params = AuthorizationSetBuilder()
2883 .Digest(Digest::SHA_2_256)
2884 .Padding(PaddingMode::NONE)
2885 .Authorization(TAG_MAC_LENGTH, 128);
2886 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params))
2887 << "(Possibly b/33543625)";
2888 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params))
2889 << "(Possibly b/33543625)";
2890 }
2891
2892 /*
2893 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2894 *
2895 * Verifies that AES ECB mode works.
2896 */
TEST_F(EncryptionOperationsTest,AesEcbRoundTripSuccess)2897 TEST_F(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2898 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2899 .Authorization(TAG_NO_AUTH_REQUIRED)
2900 .AesEncryptionKey(128)
2901 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2902 .Padding(PaddingMode::NONE)));
2903
2904 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2905
2906 // Two-block message.
2907 string message = "12345678901234567890123456789012";
2908 string ciphertext1 = EncryptMessage(message, params);
2909 EXPECT_EQ(message.size(), ciphertext1.size());
2910
2911 string ciphertext2 = EncryptMessage(string(message), params);
2912 EXPECT_EQ(message.size(), ciphertext2.size());
2913
2914 // ECB is deterministic.
2915 EXPECT_EQ(ciphertext1, ciphertext2);
2916
2917 string plaintext = DecryptMessage(ciphertext1, params);
2918 EXPECT_EQ(message, plaintext);
2919 }
2920
2921 /*
2922 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2923 *
2924 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2925 */
TEST_F(EncryptionOperationsTest,AesWrongMode)2926 TEST_F(EncryptionOperationsTest, AesWrongMode) {
2927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2928 .Authorization(TAG_NO_AUTH_REQUIRED)
2929 .AesEncryptionKey(128)
2930 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2931 .Padding(PaddingMode::NONE)));
2932 // Two-block message.
2933 string message = "12345678901234567890123456789012";
2934 EXPECT_EQ(
2935 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2936 Begin(KeyPurpose::ENCRYPT,
2937 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2938 }
2939
2940 /*
2941 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2942 *
2943 * Verifies that AES encryption fails in the correct way when provided an input that is not a
2944 * multiple of the block size and no padding is specified.
2945 */
TEST_F(EncryptionOperationsTest,AesEcbNoPaddingWrongInputSize)2946 TEST_F(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2948 .Authorization(TAG_NO_AUTH_REQUIRED)
2949 .AesEncryptionKey(128)
2950 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2951 .Padding(PaddingMode::NONE)));
2952 // Message is slightly shorter than two blocks.
2953 string message(16 * 2 - 1, 'a');
2954
2955 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2956 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2957 string ciphertext;
2958 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2959 EXPECT_EQ(0U, ciphertext.size());
2960 }
2961
2962 /*
2963 * EncryptionOperationsTest.AesEcbPkcs7Padding
2964 *
2965 * Verifies that AES PKCS7 padding works for any message length.
2966 */
TEST_F(EncryptionOperationsTest,AesEcbPkcs7Padding)2967 TEST_F(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2968 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2969 .Authorization(TAG_NO_AUTH_REQUIRED)
2970 .AesEncryptionKey(128)
2971 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2972 .Padding(PaddingMode::PKCS7)));
2973
2974 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2975
2976 // Try various message lengths; all should work.
2977 for (size_t i = 0; i < 32; ++i) {
2978 string message(i, 'a');
2979 string ciphertext = EncryptMessage(message, params);
2980 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2981 string plaintext = DecryptMessage(ciphertext, params);
2982 EXPECT_EQ(message, plaintext);
2983 }
2984 }
2985
2986 /*
2987 * EncryptionOperationsTest.AesEcbWrongPadding
2988 *
2989 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2990 * specified.
2991 */
TEST_F(EncryptionOperationsTest,AesEcbWrongPadding)2992 TEST_F(EncryptionOperationsTest, AesEcbWrongPadding) {
2993 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2994 .Authorization(TAG_NO_AUTH_REQUIRED)
2995 .AesEncryptionKey(128)
2996 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2997 .Padding(PaddingMode::NONE)));
2998
2999 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3000
3001 // Try various message lengths; all should fail
3002 for (size_t i = 0; i < 32; ++i) {
3003 string message(i, 'a');
3004 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3005 }
3006 }
3007
3008 /*
3009 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
3010 *
3011 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
3012 */
TEST_F(EncryptionOperationsTest,AesEcbPkcs7PaddingCorrupted)3013 TEST_F(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
3014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3015 .Authorization(TAG_NO_AUTH_REQUIRED)
3016 .AesEncryptionKey(128)
3017 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3018 .Padding(PaddingMode::PKCS7)));
3019
3020 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3021
3022 string message = "a";
3023 string ciphertext = EncryptMessage(message, params);
3024 EXPECT_EQ(16U, ciphertext.size());
3025 EXPECT_NE(ciphertext, message);
3026 ++ciphertext[ciphertext.size() / 2];
3027
3028 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3029 string plaintext;
3030 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3031 }
3032
CopyIv(const AuthorizationSet & set)3033 HidlBuf CopyIv(const AuthorizationSet& set) {
3034 auto iv = set.GetTagValue(TAG_NONCE);
3035 EXPECT_TRUE(iv.isOk());
3036 return iv.value();
3037 }
3038
3039 /*
3040 * EncryptionOperationsTest.AesCtrRoundTripSuccess
3041 *
3042 * Verifies that AES CTR mode works.
3043 */
TEST_F(EncryptionOperationsTest,AesCtrRoundTripSuccess)3044 TEST_F(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3045 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3046 .Authorization(TAG_NO_AUTH_REQUIRED)
3047 .AesEncryptionKey(128)
3048 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3049 .Padding(PaddingMode::NONE)));
3050
3051 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3052
3053 string message = "123";
3054 AuthorizationSet out_params;
3055 string ciphertext1 = EncryptMessage(message, params, &out_params);
3056 HidlBuf iv1 = CopyIv(out_params);
3057 EXPECT_EQ(16U, iv1.size());
3058
3059 EXPECT_EQ(message.size(), ciphertext1.size());
3060
3061 out_params.Clear();
3062 string ciphertext2 = EncryptMessage(message, params, &out_params);
3063 HidlBuf iv2 = CopyIv(out_params);
3064 EXPECT_EQ(16U, iv2.size());
3065
3066 // IVs should be random, so ciphertexts should differ.
3067 EXPECT_NE(ciphertext1, ciphertext2);
3068
3069 auto params_iv1 =
3070 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3071 auto params_iv2 =
3072 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3073
3074 string plaintext = DecryptMessage(ciphertext1, params_iv1);
3075 EXPECT_EQ(message, plaintext);
3076 plaintext = DecryptMessage(ciphertext2, params_iv2);
3077 EXPECT_EQ(message, plaintext);
3078
3079 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3080 plaintext = DecryptMessage(ciphertext1, params_iv2);
3081 EXPECT_NE(message, plaintext);
3082 plaintext = DecryptMessage(ciphertext2, params_iv1);
3083 EXPECT_NE(message, plaintext);
3084 }
3085
3086 /*
3087 * EncryptionOperationsTest.AesIncremental
3088 *
3089 * Verifies that AES works, all modes, when provided data in various size increments.
3090 */
TEST_F(EncryptionOperationsTest,AesIncremental)3091 TEST_F(EncryptionOperationsTest, AesIncremental) {
3092 auto block_modes = {
3093 BlockMode::ECB, BlockMode::CBC, BlockMode::CTR, BlockMode::GCM,
3094 };
3095
3096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3097 .Authorization(TAG_NO_AUTH_REQUIRED)
3098 .AesEncryptionKey(128)
3099 .BlockMode(block_modes)
3100 .Padding(PaddingMode::NONE)
3101 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3102
3103 for (int increment = 1; increment <= 240; ++increment) {
3104 for (auto block_mode : block_modes) {
3105 string message(240, 'a');
3106 auto params = AuthorizationSetBuilder()
3107 .BlockMode(block_mode)
3108 .Padding(PaddingMode::NONE)
3109 .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3110
3111 AuthorizationSet output_params;
3112 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3113
3114 string ciphertext;
3115 size_t input_consumed;
3116 string to_send;
3117 for (size_t i = 0; i < message.size(); i += increment) {
3118 to_send.append(message.substr(i, increment));
3119 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
3120 to_send = to_send.substr(input_consumed);
3121
3122 switch (block_mode) {
3123 case BlockMode::ECB:
3124 case BlockMode::CBC:
3125 // Implementations must take as many blocks as possible, leaving less than
3126 // a block.
3127 EXPECT_LE(to_send.length(), 16U);
3128 break;
3129 case BlockMode::GCM:
3130 case BlockMode::CTR:
3131 // Implementations must always take all the data.
3132 EXPECT_EQ(0U, to_send.length());
3133 break;
3134 }
3135 }
3136 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
3137
3138 switch (block_mode) {
3139 case BlockMode::GCM:
3140 EXPECT_EQ(message.size() + 16, ciphertext.size());
3141 break;
3142 case BlockMode::CTR:
3143 EXPECT_EQ(message.size(), ciphertext.size());
3144 break;
3145 case BlockMode::CBC:
3146 case BlockMode::ECB:
3147 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3148 break;
3149 }
3150
3151 auto iv = output_params.GetTagValue(TAG_NONCE);
3152 switch (block_mode) {
3153 case BlockMode::CBC:
3154 case BlockMode::GCM:
3155 case BlockMode::CTR:
3156 ASSERT_TRUE(iv.isOk()) << "No IV for block mode " << block_mode;
3157 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv.value().size());
3158 params.push_back(TAG_NONCE, iv.value());
3159 break;
3160
3161 case BlockMode::ECB:
3162 EXPECT_FALSE(iv.isOk()) << "ECB mode should not generate IV";
3163 break;
3164 }
3165
3166 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3167 << "Decrypt begin() failed for block mode " << block_mode;
3168
3169 string plaintext;
3170 for (size_t i = 0; i < ciphertext.size(); i += increment) {
3171 to_send.append(ciphertext.substr(i, increment));
3172 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
3173 to_send = to_send.substr(input_consumed);
3174 }
3175 ErrorCode error = Finish(to_send, &plaintext);
3176 ASSERT_EQ(ErrorCode::OK, error)
3177 << "Decryption failed for block mode " << block_mode << " and increment "
3178 << increment << " (Possibly b/33584622)";
3179 if (error == ErrorCode::OK) {
3180 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3181 << block_mode << " and increment " << increment;
3182 }
3183 }
3184 }
3185 }
3186
3187 struct AesCtrSp80038aTestVector {
3188 const char* key;
3189 const char* nonce;
3190 const char* plaintext;
3191 const char* ciphertext;
3192 };
3193
3194 // These test vectors are taken from
3195 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3196 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3197 // AES-128
3198 {
3199 "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3200 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3201 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3202 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3203 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3204 },
3205 // AES-192
3206 {
3207 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3208 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3209 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3210 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3211 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3212 },
3213 // AES-256
3214 {
3215 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3216 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3217 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3218 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3219 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3220 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3221 },
3222 };
3223
3224 /*
3225 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3226 *
3227 * Verifies AES CTR implementation against SP800-38A test vectors.
3228 */
TEST_F(EncryptionOperationsTest,AesCtrSp80038aTestVector)3229 TEST_F(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3230 for (size_t i = 0; i < 3; i++) {
3231 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3232 const string key = hex2str(test.key);
3233 const string nonce = hex2str(test.nonce);
3234 const string plaintext = hex2str(test.plaintext);
3235 const string ciphertext = hex2str(test.ciphertext);
3236 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3237 }
3238 }
3239
3240 /*
3241 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3242 *
3243 * Verifies that keymaster rejects use of CTR mode with PKCS7 padding in the correct way.
3244 */
TEST_F(EncryptionOperationsTest,AesCtrIncompatiblePaddingMode)3245 TEST_F(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3247 .Authorization(TAG_NO_AUTH_REQUIRED)
3248 .AesEncryptionKey(128)
3249 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3250 .Padding(PaddingMode::PKCS7)));
3251 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3252 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3253 }
3254
3255 /*
3256 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3257 *
3258 * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3259 */
TEST_F(EncryptionOperationsTest,AesCtrInvalidCallerNonce)3260 TEST_F(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3262 .Authorization(TAG_NO_AUTH_REQUIRED)
3263 .AesEncryptionKey(128)
3264 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3265 .Authorization(TAG_CALLER_NONCE)
3266 .Padding(PaddingMode::NONE)));
3267
3268 auto params = AuthorizationSetBuilder()
3269 .BlockMode(BlockMode::CTR)
3270 .Padding(PaddingMode::NONE)
3271 .Authorization(TAG_NONCE, HidlBuf(string(1, 'a')));
3272 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3273
3274 params = AuthorizationSetBuilder()
3275 .BlockMode(BlockMode::CTR)
3276 .Padding(PaddingMode::NONE)
3277 .Authorization(TAG_NONCE, HidlBuf(string(15, 'a')));
3278 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3279
3280 params = AuthorizationSetBuilder()
3281 .BlockMode(BlockMode::CTR)
3282 .Padding(PaddingMode::NONE)
3283 .Authorization(TAG_NONCE, HidlBuf(string(17, 'a')));
3284 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3285 }
3286
3287 /*
3288 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3289 *
3290 * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3291 */
TEST_F(EncryptionOperationsTest,AesCbcRoundTripSuccess)3292 TEST_F(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3293 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3294 .Authorization(TAG_NO_AUTH_REQUIRED)
3295 .AesEncryptionKey(128)
3296 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3297 .Padding(PaddingMode::NONE)));
3298 // Two-block message.
3299 string message = "12345678901234567890123456789012";
3300 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3301 AuthorizationSet out_params;
3302 string ciphertext1 = EncryptMessage(message, params, &out_params);
3303 HidlBuf iv1 = CopyIv(out_params);
3304 EXPECT_EQ(message.size(), ciphertext1.size());
3305
3306 out_params.Clear();
3307
3308 string ciphertext2 = EncryptMessage(message, params, &out_params);
3309 HidlBuf iv2 = CopyIv(out_params);
3310 EXPECT_EQ(message.size(), ciphertext2.size());
3311
3312 // IVs should be random, so ciphertexts should differ.
3313 EXPECT_NE(ciphertext1, ciphertext2);
3314
3315 params.push_back(TAG_NONCE, iv1);
3316 string plaintext = DecryptMessage(ciphertext1, params);
3317 EXPECT_EQ(message, plaintext);
3318 }
3319
3320 /*
3321 * EncryptionOperationsTest.AesCallerNonce
3322 *
3323 * Verifies that AES caller-provided nonces work correctly.
3324 */
TEST_F(EncryptionOperationsTest,AesCallerNonce)3325 TEST_F(EncryptionOperationsTest, AesCallerNonce) {
3326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3327 .Authorization(TAG_NO_AUTH_REQUIRED)
3328 .AesEncryptionKey(128)
3329 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3330 .Authorization(TAG_CALLER_NONCE)
3331 .Padding(PaddingMode::NONE)));
3332
3333 string message = "12345678901234567890123456789012";
3334
3335 // Don't specify nonce, should get a random one.
3336 AuthorizationSetBuilder params =
3337 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3338 AuthorizationSet out_params;
3339 string ciphertext = EncryptMessage(message, params, &out_params);
3340 EXPECT_EQ(message.size(), ciphertext.size());
3341 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3342
3343 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3344 string plaintext = DecryptMessage(ciphertext, params);
3345 EXPECT_EQ(message, plaintext);
3346
3347 // Now specify a nonce, should also work.
3348 params = AuthorizationSetBuilder()
3349 .BlockMode(BlockMode::CBC)
3350 .Padding(PaddingMode::NONE)
3351 .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3352 out_params.Clear();
3353 ciphertext = EncryptMessage(message, params, &out_params);
3354
3355 // Decrypt with correct nonce.
3356 plaintext = DecryptMessage(ciphertext, params);
3357 EXPECT_EQ(message, plaintext);
3358
3359 // Try with wrong nonce.
3360 params = AuthorizationSetBuilder()
3361 .BlockMode(BlockMode::CBC)
3362 .Padding(PaddingMode::NONE)
3363 .Authorization(TAG_NONCE, HidlBuf("aaaaaaaaaaaaaaaa"));
3364 plaintext = DecryptMessage(ciphertext, params);
3365 EXPECT_NE(message, plaintext);
3366 }
3367
3368 /*
3369 * EncryptionOperationsTest.AesCallerNonceProhibited
3370 *
3371 * Verifies that caller-provided nonces are not permitted when not specified in the key
3372 * authorizations.
3373 */
TEST_F(EncryptionOperationsTest,AesCallerNonceProhibited)3374 TEST_F(EncryptionOperationsTest, AesCallerNonceProhibited) {
3375 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3376 .Authorization(TAG_NO_AUTH_REQUIRED)
3377 .AesEncryptionKey(128)
3378 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3379 .Padding(PaddingMode::NONE)));
3380
3381 string message = "12345678901234567890123456789012";
3382
3383 // Don't specify nonce, should get a random one.
3384 AuthorizationSetBuilder params =
3385 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3386 AuthorizationSet out_params;
3387 string ciphertext = EncryptMessage(message, params, &out_params);
3388 EXPECT_EQ(message.size(), ciphertext.size());
3389 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3390
3391 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3392 string plaintext = DecryptMessage(ciphertext, params);
3393 EXPECT_EQ(message, plaintext);
3394
3395 // Now specify a nonce, should fail
3396 params = AuthorizationSetBuilder()
3397 .BlockMode(BlockMode::CBC)
3398 .Padding(PaddingMode::NONE)
3399 .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3400 out_params.Clear();
3401 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3402 }
3403
3404 /*
3405 * EncryptionOperationsTest.AesGcmRoundTripSuccess
3406 *
3407 * Verifies that AES GCM mode works.
3408 */
TEST_F(EncryptionOperationsTest,AesGcmRoundTripSuccess)3409 TEST_F(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3411 .Authorization(TAG_NO_AUTH_REQUIRED)
3412 .AesEncryptionKey(128)
3413 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3414 .Padding(PaddingMode::NONE)
3415 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3416
3417 string aad = "foobar";
3418 string message = "123456789012345678901234567890123456";
3419
3420 auto begin_params = AuthorizationSetBuilder()
3421 .BlockMode(BlockMode::GCM)
3422 .Padding(PaddingMode::NONE)
3423 .Authorization(TAG_MAC_LENGTH, 128);
3424
3425 auto update_params =
3426 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3427
3428 // Encrypt
3429 AuthorizationSet begin_out_params;
3430 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3431 << "Begin encrypt";
3432 string ciphertext;
3433 AuthorizationSet update_out_params;
3434 ASSERT_EQ(ErrorCode::OK,
3435 Finish(op_handle_, update_params, message, "", &update_out_params, &ciphertext));
3436
3437 // Grab nonce
3438 begin_params.push_back(begin_out_params);
3439
3440 // Decrypt.
3441 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3442 string plaintext;
3443 size_t input_consumed;
3444 ASSERT_EQ(ErrorCode::OK, Update(op_handle_, update_params, ciphertext, &update_out_params,
3445 &plaintext, &input_consumed));
3446 EXPECT_EQ(ciphertext.size(), input_consumed);
3447 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3448
3449 EXPECT_EQ(message, plaintext);
3450 }
3451
3452 /*
3453 * EncryptionOperationsTest.AesGcmTooShortTag
3454 *
3455 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3456 */
TEST_F(EncryptionOperationsTest,AesGcmTooShortTag)3457 TEST_F(EncryptionOperationsTest, AesGcmTooShortTag) {
3458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3459 .Authorization(TAG_NO_AUTH_REQUIRED)
3460 .AesEncryptionKey(128)
3461 .BlockMode(BlockMode::GCM)
3462 .Padding(PaddingMode::NONE)
3463 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3464 string message = "123456789012345678901234567890123456";
3465 auto params = AuthorizationSetBuilder()
3466 .BlockMode(BlockMode::GCM)
3467 .Padding(PaddingMode::NONE)
3468 .Authorization(TAG_MAC_LENGTH, 96);
3469
3470 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3471 }
3472
3473 /*
3474 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3475 *
3476 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3477 */
TEST_F(EncryptionOperationsTest,AesGcmTooShortTagOnDecrypt)3478 TEST_F(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3480 .Authorization(TAG_NO_AUTH_REQUIRED)
3481 .AesEncryptionKey(128)
3482 .BlockMode(BlockMode::GCM)
3483 .Padding(PaddingMode::NONE)
3484 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3485 string aad = "foobar";
3486 string message = "123456789012345678901234567890123456";
3487 auto params = AuthorizationSetBuilder()
3488 .BlockMode(BlockMode::GCM)
3489 .Padding(PaddingMode::NONE)
3490 .Authorization(TAG_MAC_LENGTH, 128);
3491
3492 auto finish_params =
3493 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3494
3495 // Encrypt
3496 AuthorizationSet begin_out_params;
3497 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3498 EXPECT_EQ(1U, begin_out_params.size());
3499 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE).isOk());
3500
3501 AuthorizationSet finish_out_params;
3502 string ciphertext;
3503 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3504 &finish_out_params, &ciphertext));
3505
3506 params = AuthorizationSetBuilder()
3507 .Authorizations(begin_out_params)
3508 .BlockMode(BlockMode::GCM)
3509 .Padding(PaddingMode::NONE)
3510 .Authorization(TAG_MAC_LENGTH, 96);
3511
3512 // Decrypt.
3513 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3514 }
3515
3516 /*
3517 * EncryptionOperationsTest.AesGcmCorruptKey
3518 *
3519 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3520 */
TEST_F(EncryptionOperationsTest,AesGcmCorruptKey)3521 TEST_F(EncryptionOperationsTest, AesGcmCorruptKey) {
3522 const uint8_t nonce_bytes[] = {
3523 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3524 };
3525 string nonce = make_string(nonce_bytes);
3526 const uint8_t ciphertext_bytes[] = {
3527 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
3528 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
3529 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
3530 0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3531 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3532 };
3533 string ciphertext = make_string(ciphertext_bytes);
3534
3535 auto params = AuthorizationSetBuilder()
3536 .BlockMode(BlockMode::GCM)
3537 .Padding(PaddingMode::NONE)
3538 .Authorization(TAG_MAC_LENGTH, 128)
3539 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3540
3541 auto import_params = AuthorizationSetBuilder()
3542 .Authorization(TAG_NO_AUTH_REQUIRED)
3543 .AesEncryptionKey(128)
3544 .BlockMode(BlockMode::GCM)
3545 .Padding(PaddingMode::NONE)
3546 .Authorization(TAG_CALLER_NONCE)
3547 .Authorization(TAG_MIN_MAC_LENGTH, 128);
3548
3549 // Import correct key and decrypt
3550 const uint8_t key_bytes[] = {
3551 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3552 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3553 };
3554 string key = make_string(key_bytes);
3555 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3556 string plaintext = DecryptMessage(ciphertext, params);
3557 CheckedDeleteKey();
3558
3559 // Corrupt key and attempt to decrypt
3560 key[0] = 0;
3561 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3562 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3563 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3564 CheckedDeleteKey();
3565 }
3566
3567 /*
3568 * EncryptionOperationsTest.AesGcmAadNoData
3569 *
3570 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3571 * encrypt.
3572 */
TEST_F(EncryptionOperationsTest,AesGcmAadNoData)3573 TEST_F(EncryptionOperationsTest, AesGcmAadNoData) {
3574 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3575 .Authorization(TAG_NO_AUTH_REQUIRED)
3576 .AesEncryptionKey(128)
3577 .BlockMode(BlockMode::GCM)
3578 .Padding(PaddingMode::NONE)
3579 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3580
3581 string aad = "1234567890123456";
3582 auto params = AuthorizationSetBuilder()
3583 .BlockMode(BlockMode::GCM)
3584 .Padding(PaddingMode::NONE)
3585 .Authorization(TAG_MAC_LENGTH, 128);
3586
3587 auto finish_params =
3588 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3589
3590 // Encrypt
3591 AuthorizationSet begin_out_params;
3592 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3593 string ciphertext;
3594 AuthorizationSet finish_out_params;
3595 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, "" /* input */, "" /* signature */,
3596 &finish_out_params, &ciphertext));
3597 EXPECT_TRUE(finish_out_params.empty());
3598
3599 // Grab nonce
3600 params.push_back(begin_out_params);
3601
3602 // Decrypt.
3603 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3604 string plaintext;
3605 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, ciphertext, "" /* signature */,
3606 &finish_out_params, &plaintext))
3607 << "(Possibly b/33615032)";
3608
3609 EXPECT_TRUE(finish_out_params.empty());
3610
3611 EXPECT_EQ("", plaintext);
3612 }
3613
3614 /*
3615 * EncryptionOperationsTest.AesGcmMultiPartAad
3616 *
3617 * Verifies that AES GCM mode works when provided additional authenticated data in multiple chunks.
3618 */
TEST_F(EncryptionOperationsTest,AesGcmMultiPartAad)3619 TEST_F(EncryptionOperationsTest, AesGcmMultiPartAad) {
3620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3621 .Authorization(TAG_NO_AUTH_REQUIRED)
3622 .AesEncryptionKey(128)
3623 .BlockMode(BlockMode::GCM)
3624 .Padding(PaddingMode::NONE)
3625 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3626
3627 string message = "123456789012345678901234567890123456";
3628 auto begin_params = AuthorizationSetBuilder()
3629 .BlockMode(BlockMode::GCM)
3630 .Padding(PaddingMode::NONE)
3631 .Authorization(TAG_MAC_LENGTH, 128);
3632 AuthorizationSet begin_out_params;
3633
3634 auto update_params =
3635 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3636
3637 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3638
3639 // No data, AAD only.
3640 string ciphertext;
3641 size_t input_consumed;
3642 AuthorizationSet update_out_params;
3643 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3644 &ciphertext, &input_consumed));
3645 EXPECT_EQ(0U, input_consumed);
3646 EXPECT_EQ(0U, ciphertext.size());
3647 EXPECT_TRUE(update_out_params.empty());
3648
3649 // AAD and data.
3650 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3651 &ciphertext, &input_consumed));
3652 EXPECT_EQ(message.size(), input_consumed);
3653 EXPECT_EQ(message.size(), ciphertext.size());
3654 EXPECT_TRUE(update_out_params.empty());
3655
3656 EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext));
3657
3658 // Grab nonce.
3659 begin_params.push_back(begin_out_params);
3660
3661 // Decrypt
3662 update_params =
3663 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6);
3664
3665 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3666 string plaintext;
3667 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, update_params, ciphertext, "" /* signature */,
3668 &update_out_params, &plaintext));
3669 EXPECT_TRUE(update_out_params.empty());
3670 EXPECT_EQ(message, plaintext);
3671 }
3672
3673 /*
3674 * EncryptionOperationsTest.AesGcmAadOutOfOrder
3675 *
3676 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3677 */
TEST_F(EncryptionOperationsTest,AesGcmAadOutOfOrder)3678 TEST_F(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3680 .Authorization(TAG_NO_AUTH_REQUIRED)
3681 .AesEncryptionKey(128)
3682 .BlockMode(BlockMode::GCM)
3683 .Padding(PaddingMode::NONE)
3684 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3685
3686 string message = "123456789012345678901234567890123456";
3687 auto begin_params = AuthorizationSetBuilder()
3688 .BlockMode(BlockMode::GCM)
3689 .Padding(PaddingMode::NONE)
3690 .Authorization(TAG_MAC_LENGTH, 128);
3691 AuthorizationSet begin_out_params;
3692
3693 auto update_params =
3694 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3695
3696 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3697
3698 // No data, AAD only.
3699 string ciphertext;
3700 size_t input_consumed;
3701 AuthorizationSet update_out_params;
3702 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3703 &ciphertext, &input_consumed));
3704 EXPECT_EQ(0U, input_consumed);
3705 EXPECT_EQ(0U, ciphertext.size());
3706 EXPECT_TRUE(update_out_params.empty());
3707
3708 // AAD and data.
3709 EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3710 &ciphertext, &input_consumed));
3711 EXPECT_EQ(message.size(), input_consumed);
3712 EXPECT_EQ(message.size(), ciphertext.size());
3713 EXPECT_TRUE(update_out_params.empty());
3714
3715 // More AAD
3716 EXPECT_EQ(ErrorCode::INVALID_TAG, Update(op_handle_, update_params, "", &update_out_params,
3717 &ciphertext, &input_consumed));
3718
3719 op_handle_ = kOpHandleSentinel;
3720 }
3721
3722 /*
3723 * EncryptionOperationsTest.AesGcmBadAad
3724 *
3725 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3726 */
TEST_F(EncryptionOperationsTest,AesGcmBadAad)3727 TEST_F(EncryptionOperationsTest, AesGcmBadAad) {
3728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3729 .Authorization(TAG_NO_AUTH_REQUIRED)
3730 .AesEncryptionKey(128)
3731 .BlockMode(BlockMode::GCM)
3732 .Padding(PaddingMode::NONE)
3733 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3734
3735 string message = "12345678901234567890123456789012";
3736 auto begin_params = AuthorizationSetBuilder()
3737 .BlockMode(BlockMode::GCM)
3738 .Padding(PaddingMode::NONE)
3739 .Authorization(TAG_MAC_LENGTH, 128);
3740
3741 auto finish_params =
3742 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3743
3744 // Encrypt
3745 AuthorizationSet begin_out_params;
3746 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3747 string ciphertext;
3748 AuthorizationSet finish_out_params;
3749 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3750 &finish_out_params, &ciphertext));
3751
3752 // Grab nonce
3753 begin_params.push_back(begin_out_params);
3754
3755 finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA,
3756 "barfoo" /* Wrong AAD */, (size_t)6);
3757
3758 // Decrypt.
3759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3760 string plaintext;
3761 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3762 Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3763 &plaintext));
3764 }
3765
3766 /*
3767 * EncryptionOperationsTest.AesGcmWrongNonce
3768 *
3769 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3770 */
TEST_F(EncryptionOperationsTest,AesGcmWrongNonce)3771 TEST_F(EncryptionOperationsTest, AesGcmWrongNonce) {
3772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3773 .Authorization(TAG_NO_AUTH_REQUIRED)
3774 .AesEncryptionKey(128)
3775 .BlockMode(BlockMode::GCM)
3776 .Padding(PaddingMode::NONE)
3777 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3778
3779 string message = "12345678901234567890123456789012";
3780 auto begin_params = AuthorizationSetBuilder()
3781 .BlockMode(BlockMode::GCM)
3782 .Padding(PaddingMode::NONE)
3783 .Authorization(TAG_MAC_LENGTH, 128);
3784
3785 auto finish_params =
3786 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3787
3788 // Encrypt
3789 AuthorizationSet begin_out_params;
3790 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3791 string ciphertext;
3792 AuthorizationSet finish_out_params;
3793 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3794 &finish_out_params, &ciphertext));
3795
3796 // Wrong nonce
3797 begin_params.push_back(TAG_NONCE, HidlBuf("123456789012"));
3798
3799 // Decrypt.
3800 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3801 string plaintext;
3802 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3803 Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3804 &plaintext));
3805
3806 // With wrong nonce, should have gotten garbage plaintext (or none).
3807 EXPECT_NE(message, plaintext);
3808 }
3809
3810 /*
3811 * EncryptionOperationsTest.AesGcmCorruptTag
3812 *
3813 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3814 */
TEST_F(EncryptionOperationsTest,AesGcmCorruptTag)3815 TEST_F(EncryptionOperationsTest, AesGcmCorruptTag) {
3816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3817 .Authorization(TAG_NO_AUTH_REQUIRED)
3818 .AesEncryptionKey(128)
3819 .BlockMode(BlockMode::GCM)
3820 .Padding(PaddingMode::NONE)
3821 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3822
3823 string aad = "1234567890123456";
3824 string message = "123456789012345678901234567890123456";
3825
3826 auto params = AuthorizationSetBuilder()
3827 .BlockMode(BlockMode::GCM)
3828 .Padding(PaddingMode::NONE)
3829 .Authorization(TAG_MAC_LENGTH, 128);
3830
3831 auto finish_params =
3832 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3833
3834 // Encrypt
3835 AuthorizationSet begin_out_params;
3836 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3837 string ciphertext;
3838 AuthorizationSet finish_out_params;
3839 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3840 &finish_out_params, &ciphertext));
3841 EXPECT_TRUE(finish_out_params.empty());
3842
3843 // Corrupt tag
3844 ++(*ciphertext.rbegin());
3845
3846 // Grab nonce
3847 params.push_back(begin_out_params);
3848
3849 // Decrypt.
3850 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3851 string plaintext;
3852 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3853 Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3854 &plaintext));
3855 EXPECT_TRUE(finish_out_params.empty());
3856 }
3857
3858 typedef KeymasterHidlTest MaxOperationsTest;
3859
3860 /*
3861 * MaxOperationsTest.TestLimitAes
3862 *
3863 * Verifies that the max uses per boot tag works correctly with AES keys.
3864 */
TEST_F(MaxOperationsTest,TestLimitAes)3865 TEST_F(MaxOperationsTest, TestLimitAes) {
3866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3867 .Authorization(TAG_NO_AUTH_REQUIRED)
3868 .AesEncryptionKey(128)
3869 .EcbMode()
3870 .Padding(PaddingMode::NONE)
3871 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3872
3873 string message = "1234567890123456";
3874
3875 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
3876
3877 EncryptMessage(message, params);
3878 EncryptMessage(message, params);
3879 EncryptMessage(message, params);
3880
3881 // Fourth time should fail.
3882 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
3883 }
3884
3885 /*
3886 * MaxOperationsTest.TestLimitAes
3887 *
3888 * Verifies that the max uses per boot tag works correctly with RSA keys.
3889 */
TEST_F(MaxOperationsTest,TestLimitRsa)3890 TEST_F(MaxOperationsTest, TestLimitRsa) {
3891 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3892 .Authorization(TAG_NO_AUTH_REQUIRED)
3893 .RsaSigningKey(1024, 3)
3894 .NoDigestOrPadding()
3895 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3896
3897 string message = "1234567890123456";
3898
3899 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
3900
3901 SignMessage(message, params);
3902 SignMessage(message, params);
3903 SignMessage(message, params);
3904
3905 // Fourth time should fail.
3906 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
3907 }
3908
3909 typedef KeymasterHidlTest AddEntropyTest;
3910
3911 /*
3912 * AddEntropyTest.AddEntropy
3913 *
3914 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy is
3915 * actually added.
3916 */
TEST_F(AddEntropyTest,AddEntropy)3917 TEST_F(AddEntropyTest, AddEntropy) {
3918 EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf("foo")));
3919 }
3920
3921 /*
3922 * AddEntropyTest.AddEmptyEntropy
3923 *
3924 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
3925 */
TEST_F(AddEntropyTest,AddEmptyEntropy)3926 TEST_F(AddEntropyTest, AddEmptyEntropy) {
3927 EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf()));
3928 }
3929
3930 /*
3931 * AddEntropyTest.AddLargeEntropy
3932 *
3933 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
3934 */
TEST_F(AddEntropyTest,AddLargeEntropy)3935 TEST_F(AddEntropyTest, AddLargeEntropy) {
3936 EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf(string(2 * 1024, 'a'))));
3937 }
3938
3939 typedef KeymasterHidlTest AttestationTest;
3940
3941 /*
3942 * AttestationTest.RsaAttestation
3943 *
3944 * Verifies that attesting to RSA keys works and generates the expected output.
3945 */
TEST_F(AttestationTest,RsaAttestation)3946 TEST_F(AttestationTest, RsaAttestation) {
3947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3948 .Authorization(TAG_NO_AUTH_REQUIRED)
3949 .RsaSigningKey(1024, 3)
3950 .Digest(Digest::NONE)
3951 .Padding(PaddingMode::NONE)
3952 .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3953
3954 hidl_vec<hidl_vec<uint8_t>> cert_chain;
3955 ASSERT_EQ(ErrorCode::OK,
3956 AttestKey(AuthorizationSetBuilder()
3957 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
3958 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
3959 &cert_chain));
3960 EXPECT_GE(cert_chain.size(), 2U);
3961 EXPECT_TRUE(verify_chain(cert_chain));
3962 EXPECT_TRUE(
3963 verify_attestation_record("challenge", "foo", //
3964 key_characteristics_.softwareEnforced, //
3965 key_characteristics_.teeEnforced, //
3966 cert_chain[0]));
3967 }
3968
3969 /*
3970 * AttestationTest.RsaAttestationRequiresAppId
3971 *
3972 * Verifies that attesting to RSA requires app ID.
3973 */
TEST_F(AttestationTest,RsaAttestationRequiresAppId)3974 TEST_F(AttestationTest, RsaAttestationRequiresAppId) {
3975 ASSERT_EQ(ErrorCode::OK,
3976 GenerateKey(AuthorizationSetBuilder()
3977 .Authorization(TAG_NO_AUTH_REQUIRED)
3978 .RsaSigningKey(1024, 3)
3979 .Digest(Digest::NONE)
3980 .Padding(PaddingMode::NONE)
3981 .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3982
3983 hidl_vec<hidl_vec<uint8_t>> cert_chain;
3984 EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
3985 AttestKey(AuthorizationSetBuilder().Authorization(
3986 TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")),
3987 &cert_chain));
3988 }
3989
3990 /*
3991 * AttestationTest.EcAttestation
3992 *
3993 * Verifies that attesting to EC keys works and generates the expected output.
3994 */
TEST_F(AttestationTest,EcAttestation)3995 TEST_F(AttestationTest, EcAttestation) {
3996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3997 .Authorization(TAG_NO_AUTH_REQUIRED)
3998 .EcdsaSigningKey(EcCurve::P_256)
3999 .Digest(Digest::SHA_2_256)
4000 .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4001
4002 hidl_vec<hidl_vec<uint8_t>> cert_chain;
4003 ASSERT_EQ(ErrorCode::OK,
4004 AttestKey(AuthorizationSetBuilder()
4005 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4006 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4007 &cert_chain));
4008 EXPECT_GE(cert_chain.size(), 2U);
4009 EXPECT_TRUE(verify_chain(cert_chain));
4010
4011 EXPECT_TRUE(
4012 verify_attestation_record("challenge", "foo", //
4013 key_characteristics_.softwareEnforced, //
4014 key_characteristics_.teeEnforced, //
4015 cert_chain[0]));
4016 }
4017
4018 /*
4019 * AttestationTest.EcAttestationRequiresAttestationAppId
4020 *
4021 * Verifies that attesting to EC keys requires app ID
4022 */
TEST_F(AttestationTest,EcAttestationRequiresAttestationAppId)4023 TEST_F(AttestationTest, EcAttestationRequiresAttestationAppId) {
4024 ASSERT_EQ(ErrorCode::OK,
4025 GenerateKey(AuthorizationSetBuilder()
4026 .Authorization(TAG_NO_AUTH_REQUIRED)
4027 .EcdsaSigningKey(EcCurve::P_256)
4028 .Digest(Digest::SHA_2_256)
4029 .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4030
4031 hidl_vec<hidl_vec<uint8_t>> cert_chain;
4032 EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
4033 AttestKey(AuthorizationSetBuilder().Authorization(
4034 TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")),
4035 &cert_chain));
4036 }
4037
4038 /*
4039 * AttestationTest.AesAttestation
4040 *
4041 * Verifies that attesting to AES keys fails in the expected way.
4042 */
TEST_F(AttestationTest,AesAttestation)4043 TEST_F(AttestationTest, AesAttestation) {
4044 ASSERT_EQ(ErrorCode::OK,
4045 GenerateKey(AuthorizationSetBuilder()
4046 .Authorization(TAG_NO_AUTH_REQUIRED)
4047 .AesEncryptionKey(128)
4048 .EcbMode()
4049 .Padding(PaddingMode::PKCS7)));
4050
4051 hidl_vec<hidl_vec<uint8_t>> cert_chain;
4052 EXPECT_EQ(
4053 ErrorCode::INCOMPATIBLE_ALGORITHM,
4054 AttestKey(
4055 AuthorizationSetBuilder()
4056 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4057 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4058 &cert_chain));
4059 }
4060
4061 /*
4062 * AttestationTest.HmacAttestation
4063 *
4064 * Verifies that attesting to HMAC keys fails in the expected way.
4065 */
TEST_F(AttestationTest,HmacAttestation)4066 TEST_F(AttestationTest, HmacAttestation) {
4067 ASSERT_EQ(ErrorCode::OK,
4068 GenerateKey(AuthorizationSetBuilder()
4069 .Authorization(TAG_NO_AUTH_REQUIRED)
4070 .HmacKey(128)
4071 .EcbMode()
4072 .Digest(Digest::SHA_2_256)
4073 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4074
4075 hidl_vec<hidl_vec<uint8_t>> cert_chain;
4076 EXPECT_EQ(
4077 ErrorCode::INCOMPATIBLE_ALGORITHM,
4078 AttestKey(
4079 AuthorizationSetBuilder()
4080 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4081 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4082 &cert_chain));
4083 }
4084
4085 typedef KeymasterHidlTest KeyDeletionTest;
4086
4087 /**
4088 * KeyDeletionTest.DeleteKey
4089 *
4090 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4091 * valid key blob.
4092 */
TEST_F(KeyDeletionTest,DeleteKey)4093 TEST_F(KeyDeletionTest, DeleteKey) {
4094 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4095 .RsaSigningKey(1024, 3)
4096 .Digest(Digest::NONE)
4097 .Padding(PaddingMode::NONE)
4098 .Authorization(TAG_NO_AUTH_REQUIRED)));
4099
4100 // Delete must work if rollback protection is implemented
4101 AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4102 bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4103
4104 if (rollback_protected) {
4105 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4106 } else {
4107 auto delete_result = DeleteKey(true /* keep key blob */);
4108 ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED);
4109 }
4110
4111 string message = "12345678901234567890123456789012";
4112 AuthorizationSet begin_out_params;
4113
4114 if (rollback_protected) {
4115 EXPECT_EQ(
4116 ErrorCode::INVALID_KEY_BLOB,
4117 Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder()
4118 .Digest(Digest::NONE)
4119 .Padding(PaddingMode::NONE),
4120 &begin_out_params, &op_handle_))
4121 << " (Possibly b/37623742)";
4122 } else {
4123 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_,
4124 AuthorizationSetBuilder()
4125 .Digest(Digest::NONE)
4126 .Padding(PaddingMode::NONE),
4127 &begin_out_params, &op_handle_));
4128 }
4129 AbortIfNeeded();
4130 key_blob_ = HidlBuf();
4131 }
4132
4133 /**
4134 * KeyDeletionTest.DeleteInvalidKey
4135 *
4136 * This test checks that the HAL excepts invalid key blobs.
4137 */
TEST_F(KeyDeletionTest,DeleteInvalidKey)4138 TEST_F(KeyDeletionTest, DeleteInvalidKey) {
4139 // Generate key just to check if rollback protection is implemented
4140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4141 .RsaSigningKey(1024, 3)
4142 .Digest(Digest::NONE)
4143 .Padding(PaddingMode::NONE)
4144 .Authorization(TAG_NO_AUTH_REQUIRED)));
4145
4146 // Delete must work if rollback protection is implemented
4147 AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4148 bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4149
4150 // Delete the key we don't care about the result at this point.
4151 DeleteKey();
4152
4153 // Now create an invalid key blob and delete it.
4154 key_blob_ = HidlBuf("just some garbage data which is not a valid key blob");
4155
4156 if (rollback_protected) {
4157 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4158 } else {
4159 auto delete_result = DeleteKey();
4160 ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED);
4161 }
4162 }
4163
4164 /**
4165 * KeyDeletionTest.DeleteAllKeys
4166 *
4167 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4168 *
4169 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4170 * FBE/FDE encryption keys, which means that the device will not even boot until after the
4171 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4172 * been provisioned. Use this test only on dedicated testing devices that have no valuable
4173 * credentials stored in Keystore/Keymaster.
4174 */
TEST_F(KeyDeletionTest,DeleteAllKeys)4175 TEST_F(KeyDeletionTest, DeleteAllKeys) {
4176 if (!arm_deleteAllKeys) return;
4177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4178 .RsaSigningKey(1024, 3)
4179 .Digest(Digest::NONE)
4180 .Padding(PaddingMode::NONE)
4181 .Authorization(TAG_NO_AUTH_REQUIRED)));
4182
4183 // Delete must work if rollback protection is implemented
4184 AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4185 bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4186
4187 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4188
4189 string message = "12345678901234567890123456789012";
4190 AuthorizationSet begin_out_params;
4191
4192 if (rollback_protected) {
4193 EXPECT_EQ(
4194 ErrorCode::INVALID_KEY_BLOB,
4195 Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder()
4196 .Digest(Digest::NONE)
4197 .Padding(PaddingMode::NONE),
4198 &begin_out_params, &op_handle_));
4199 } else {
4200 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_,
4201 AuthorizationSetBuilder()
4202 .Digest(Digest::NONE)
4203 .Padding(PaddingMode::NONE),
4204 &begin_out_params, &op_handle_));
4205 }
4206 AbortIfNeeded();
4207 key_blob_ = HidlBuf();
4208 }
4209
4210 } // namespace test
4211 } // namespace V3_0
4212 } // namespace keymaster
4213 } // namespace hardware
4214 } // namespace android
4215
main(int argc,char ** argv)4216 int main(int argc, char** argv) {
4217 using android::hardware::keymaster::V3_0::test::KeymasterHidlEnvironment;
4218 ::testing::AddGlobalTestEnvironment(KeymasterHidlEnvironment::Instance());
4219 ::testing::InitGoogleTest(&argc, argv);
4220 KeymasterHidlEnvironment::Instance()->init(&argc, argv);
4221 for (int i = 1; i < argc; ++i) {
4222 if (argv[i][0] == '-') {
4223 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
4224 arm_deleteAllKeys = true;
4225 }
4226 if (std::string(argv[i]) == "--dump_attestations") {
4227 dump_Attestations = true;
4228 }
4229 }
4230 }
4231 int status = RUN_ALL_TESTS();
4232 ALOGI("Test result = %d", status);
4233 return status;
4234 }
4235