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