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