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