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