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