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