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