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