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