blob: 30601538dd65d6266403fbfb793adff54fbd840e [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
23#include <openssl/evp.h>
24#include <openssl/mem.h>
25#include <openssl/x509.h>
26
27#include <cutils/properties.h>
28
Janis Danisevskis24c04702020-12-16 18:28:39 -080029#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
Shawn Willden08a7e432020-12-11 13:05:27 +000031#include <keymint_support/attestation_record.h>
32#include <keymint_support/key_param_output.h>
33#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070034
35#include "KeyMintAidlTestBase.h"
36
37static bool arm_deleteAllKeys = false;
38static bool dump_Attestations = false;
39
Janis Danisevskis24c04702020-12-16 18:28:39 -080040using aidl::android::hardware::security::keymint::AuthorizationSet;
41using aidl::android::hardware::security::keymint::KeyCharacteristics;
42using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070043
Janis Danisevskis24c04702020-12-16 18:28:39 -080044namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070045
46bool operator==(const keymint::AuthorizationSet& a, const keymint::AuthorizationSet& b) {
47 return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
48}
Shawn Willden08a7e432020-12-11 13:05:27 +000049
Janis Danisevskis24c04702020-12-16 18:28:39 -080050} // namespace aidl::android::hardware::security::keymint
Selene Huang31ab4042020-04-29 04:22:39 -070051
52namespace std {
53
Janis Danisevskis24c04702020-12-16 18:28:39 -080054using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070055
56template <>
57struct std::equal_to<KeyCharacteristics> {
58 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
59 // This isn't very efficient. Oh, well.
60 AuthorizationSet a_sw(a.softwareEnforced);
61 AuthorizationSet b_sw(b.softwareEnforced);
62 AuthorizationSet a_tee(b.hardwareEnforced);
63 AuthorizationSet b_tee(b.hardwareEnforced);
64
65 a_sw.Sort();
66 b_sw.Sort();
67 a_tee.Sort();
68 b_tee.Sort();
69
70 return ((a_sw == b_sw) && (a_tee == b_tee));
71 }
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
185/* TODO(seleneh) add attestation verification codes like verify_chain() and
186 * attestation tests after we decided on the keymint 1 attestation changes.
187 */
188
189std::string make_string(const uint8_t* data, size_t length) {
190 return std::string(reinterpret_cast<const char*>(data), length);
191}
192
193template <size_t N>
194std::string make_string(const uint8_t (&a)[N]) {
195 return make_string(a, N);
196}
197
198class AidlBuf : public vector<uint8_t> {
199 typedef vector<uint8_t> super;
200
201 public:
202 AidlBuf() {}
203 AidlBuf(const super& other) : super(other) {}
204 AidlBuf(super&& other) : super(std::move(other)) {}
205 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
206
207 AidlBuf& operator=(const super& other) {
208 super::operator=(other);
209 return *this;
210 }
211
212 AidlBuf& operator=(super&& other) {
213 super::operator=(std::move(other));
214 return *this;
215 }
216
217 AidlBuf& operator=(const string& other) {
218 resize(other.size());
219 for (size_t i = 0; i < other.size(); ++i) {
220 (*this)[i] = static_cast<uint8_t>(other[i]);
221 }
222 return *this;
223 }
224
225 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
226};
227
228} // namespace
229
230class NewKeyGenerationTest : public KeyMintAidlTestBase {
231 protected:
232 void CheckBaseParams(const KeyCharacteristics& keyCharacteristics) {
233 // TODO(swillden): Distinguish which params should be in which auth list.
234
235 AuthorizationSet auths(keyCharacteristics.hardwareEnforced);
236 auths.push_back(AuthorizationSet(keyCharacteristics.softwareEnforced));
237
238 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
239 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
240 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
241
242 // Verify that App ID, App data and ROT are NOT included.
243 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
244 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_ID));
245 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
246
247 // Check that some unexpected tags/values are NOT present.
248 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
249 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
250 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
251
252 // Now check that unspecified, defaulted tags are correct.
253 EXPECT_TRUE(auths.Contains(TAG_CREATION_DATETIME));
254
255 EXPECT_TRUE(auths.Contains(TAG_OS_VERSION, os_version()))
256 << "OS version is " << os_version() << " key reported "
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800257 << auths.GetTagValue(TAG_OS_VERSION)->get();
Selene Huang31ab4042020-04-29 04:22:39 -0700258 EXPECT_TRUE(auths.Contains(TAG_OS_PATCHLEVEL, os_patch_level()))
259 << "OS patch level is " << os_patch_level() << " key reported "
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800260 << auths.GetTagValue(TAG_OS_PATCHLEVEL)->get();
Selene Huang31ab4042020-04-29 04:22:39 -0700261 }
262};
263
264/*
265 * NewKeyGenerationTest.Rsa
266 *
267 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
268 * have correct characteristics.
269 */
270TEST_P(NewKeyGenerationTest, Rsa) {
271 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
272 vector<uint8_t> key_blob;
273 KeyCharacteristics key_characteristics;
274 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
275 .RsaSigningKey(key_size, 65537)
276 .Digest(Digest::NONE)
277 .Padding(PaddingMode::NONE),
278 &key_blob, &key_characteristics));
279
280 ASSERT_GT(key_blob.size(), 0U);
281 CheckBaseParams(key_characteristics);
282
283 AuthorizationSet crypto_params;
284 if (IsSecure()) {
285 crypto_params = key_characteristics.hardwareEnforced;
286 } else {
287 crypto_params = key_characteristics.softwareEnforced;
288 }
289
290 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
291 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
292 << "Key size " << key_size << "missing";
293 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
294
295 CheckedDeleteKey(&key_blob);
296 }
297}
298
299/*
300 * NewKeyGenerationTest.NoInvalidRsaSizes
301 *
302 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
303 */
304TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
305 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
306 vector<uint8_t> key_blob;
307 KeyCharacteristics key_characteristics;
308 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
309 GenerateKey(AuthorizationSetBuilder()
310 .RsaSigningKey(key_size, 65537)
311 .Digest(Digest::NONE)
312 .Padding(PaddingMode::NONE),
313 &key_blob, &key_characteristics));
314 }
315}
316
317/*
318 * NewKeyGenerationTest.RsaNoDefaultSize
319 *
320 * Verifies that failing to specify a key size for RSA key generation returns
321 * UNSUPPORTED_KEY_SIZE.
322 */
323TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
324 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
325 GenerateKey(AuthorizationSetBuilder()
326 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
327 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
328 .SigningKey()));
329}
330
331/*
332 * NewKeyGenerationTest.Ecdsa
333 *
334 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
335 * have correct characteristics.
336 */
337TEST_P(NewKeyGenerationTest, Ecdsa) {
338 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
339 vector<uint8_t> key_blob;
340 KeyCharacteristics key_characteristics;
341 ASSERT_EQ(ErrorCode::OK,
342 GenerateKey(
343 AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(Digest::NONE),
344 &key_blob, &key_characteristics));
345 ASSERT_GT(key_blob.size(), 0U);
346 CheckBaseParams(key_characteristics);
347
348 AuthorizationSet crypto_params;
349 if (IsSecure()) {
350 crypto_params = key_characteristics.hardwareEnforced;
351 } else {
352 crypto_params = key_characteristics.softwareEnforced;
353 }
354
355 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
356 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
357 << "Key size " << key_size << "missing";
358
359 CheckedDeleteKey(&key_blob);
360 }
361}
362
363/*
364 * NewKeyGenerationTest.EcdsaDefaultSize
365 *
366 * Verifies that failing to specify a key size for EC key generation returns
367 * UNSUPPORTED_KEY_SIZE.
368 */
369TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
370 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
371 GenerateKey(AuthorizationSetBuilder()
372 .Authorization(TAG_ALGORITHM, Algorithm::EC)
373 .SigningKey()
374 .Digest(Digest::NONE)));
375}
376
377/*
378 * NewKeyGenerationTest.EcdsaInvalidSize
379 *
380 * Verifies that specifying an invalid key size for EC key generation returns
381 * UNSUPPORTED_KEY_SIZE.
382 */
383TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
384 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
385 vector<uint8_t> key_blob;
386 KeyCharacteristics key_characteristics;
387 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
388 GenerateKey(
389 AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(Digest::NONE),
390 &key_blob, &key_characteristics));
391 }
392
393 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
394 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(Digest::NONE)));
395}
396
397/*
398 * NewKeyGenerationTest.EcdsaMismatchKeySize
399 *
400 * Verifies that specifying mismatched key size and curve for EC key generation returns
401 * INVALID_ARGUMENT.
402 */
403TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
404 if (SecLevel() == SecurityLevel::STRONGBOX) return;
405
406 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
407 GenerateKey(AuthorizationSetBuilder()
408 .EcdsaSigningKey(224)
409 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
410 .Digest(Digest::NONE)));
411}
412
413/*
414 * NewKeyGenerationTest.EcdsaAllValidSizes
415 *
416 * Verifies that keymint supports all required EC key sizes.
417 */
418TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
419 auto valid_sizes = ValidKeySizes(Algorithm::EC);
420 for (size_t size : valid_sizes) {
421 EXPECT_EQ(ErrorCode::OK,
422 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(Digest::NONE)))
423 << "Failed to generate size: " << size;
424 CheckedDeleteKey();
425 }
426}
427
428/*
429 * NewKeyGenerationTest.EcdsaInvalidCurves
430 *
431 * Verifies that keymint does not support any curve designated as unsupported.
432 */
433TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
434 Digest digest;
435 if (SecLevel() == SecurityLevel::STRONGBOX) {
436 digest = Digest::SHA_2_256;
437 } else {
438 digest = Digest::SHA_2_512;
439 }
440 for (auto curve : ValidCurves()) {
441 EXPECT_EQ(ErrorCode::OK,
442 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(curve).Digest(digest)))
443 << "Failed to generate key on curve: " << curve;
444 CheckedDeleteKey();
445 }
446}
447
448/*
449 * NewKeyGenerationTest.Hmac
450 *
451 * Verifies that keymint supports all required digests, and that the resulting keys have correct
452 * characteristics.
453 */
454TEST_P(NewKeyGenerationTest, Hmac) {
455 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
456 vector<uint8_t> key_blob;
457 KeyCharacteristics key_characteristics;
458 constexpr size_t key_size = 128;
459 ASSERT_EQ(ErrorCode::OK,
460 GenerateKey(
461 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
462 TAG_MIN_MAC_LENGTH, 128),
463 &key_blob, &key_characteristics));
464
465 ASSERT_GT(key_blob.size(), 0U);
466 CheckBaseParams(key_characteristics);
467
468 AuthorizationSet hardwareEnforced = key_characteristics.hardwareEnforced;
469 AuthorizationSet softwareEnforced = key_characteristics.softwareEnforced;
470 if (IsSecure()) {
471 EXPECT_TRUE(hardwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
472 EXPECT_TRUE(hardwareEnforced.Contains(TAG_KEY_SIZE, key_size))
473 << "Key size " << key_size << "missing";
474 } else {
475 EXPECT_TRUE(softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
476 EXPECT_TRUE(softwareEnforced.Contains(TAG_KEY_SIZE, key_size))
477 << "Key size " << key_size << "missing";
478 }
479
480 CheckedDeleteKey(&key_blob);
481 }
482}
483
484/*
485 * NewKeyGenerationTest.HmacCheckKeySizes
486 *
487 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
488 */
489TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
490 for (size_t key_size = 0; key_size <= 512; ++key_size) {
491 if (key_size < 64 || key_size % 8 != 0) {
492 // To keep this test from being very slow, we only test a random fraction of
493 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
494 // them, we expect to run ~40 of them in each run.
495 if (key_size % 8 == 0 || random() % 10 == 0) {
496 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
497 GenerateKey(AuthorizationSetBuilder()
498 .HmacKey(key_size)
499 .Digest(Digest::SHA_2_256)
500 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
501 << "HMAC key size " << key_size << " invalid";
502 }
503 } else {
504 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
505 .HmacKey(key_size)
506 .Digest(Digest::SHA_2_256)
507 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
508 << "Failed to generate HMAC key of size " << key_size;
509 CheckedDeleteKey();
510 }
511 }
512}
513
514/*
515 * NewKeyGenerationTest.HmacCheckMinMacLengths
516 *
517 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
518 * test is probabilistic in order to keep the runtime down, but any failure prints out the
519 * specific MAC length that failed, so reproducing a failed run will be easy.
520 */
521TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
522 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
523 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
524 // To keep this test from being very long, we only test a random fraction of
525 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
526 // we expect to run ~17 of them in each run.
527 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
528 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
529 GenerateKey(AuthorizationSetBuilder()
530 .HmacKey(128)
531 .Digest(Digest::SHA_2_256)
532 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
533 << "HMAC min mac length " << min_mac_length << " invalid.";
534 }
535 } else {
536 EXPECT_EQ(ErrorCode::OK,
537 GenerateKey(AuthorizationSetBuilder()
538 .HmacKey(128)
539 .Digest(Digest::SHA_2_256)
540 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
541 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
542 CheckedDeleteKey();
543 }
544 }
545}
546
547/*
548 * NewKeyGenerationTest.HmacMultipleDigests
549 *
550 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
551 */
552TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
553 if (SecLevel() == SecurityLevel::STRONGBOX) return;
554
555 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
556 GenerateKey(AuthorizationSetBuilder()
557 .HmacKey(128)
558 .Digest(Digest::SHA1)
559 .Digest(Digest::SHA_2_256)
560 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
561}
562
563/*
564 * NewKeyGenerationTest.HmacDigestNone
565 *
566 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
567 */
568TEST_P(NewKeyGenerationTest, HmacDigestNone) {
569 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
570 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
571 128)));
572
573 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
574 GenerateKey(AuthorizationSetBuilder()
575 .HmacKey(128)
576 .Digest(Digest::NONE)
577 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
578}
579
580INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
581
582typedef KeyMintAidlTestBase SigningOperationsTest;
583
584/*
585 * SigningOperationsTest.RsaSuccess
586 *
587 * Verifies that raw RSA signature operations succeed.
588 */
589TEST_P(SigningOperationsTest, RsaSuccess) {
590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
591 .RsaSigningKey(2048, 65537)
592 .Digest(Digest::NONE)
593 .Padding(PaddingMode::NONE)
594 .Authorization(TAG_NO_AUTH_REQUIRED)));
595 string message = "12345678901234567890123456789012";
596 string signature = SignMessage(
597 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
598}
599
600/*
601 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
602 *
603 * Verifies that using an RSA key requires the correct app ID/data.
604 */
605TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
606 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
607 .Authorization(TAG_NO_AUTH_REQUIRED)
608 .RsaSigningKey(2048, 65537)
609 .Digest(Digest::NONE)
610 .Padding(PaddingMode::NONE)
611 .Authorization(TAG_APPLICATION_ID, "clientid")
612 .Authorization(TAG_APPLICATION_DATA, "appdata")));
613 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
614 Begin(KeyPurpose::SIGN,
615 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
616 AbortIfNeeded();
617 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
618 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
619 .Digest(Digest::NONE)
620 .Padding(PaddingMode::NONE)
621 .Authorization(TAG_APPLICATION_ID, "clientid")));
622 AbortIfNeeded();
623 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
624 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
625 .Digest(Digest::NONE)
626 .Padding(PaddingMode::NONE)
627 .Authorization(TAG_APPLICATION_DATA, "appdata")));
628 AbortIfNeeded();
629 EXPECT_EQ(ErrorCode::OK,
630 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
631 .Digest(Digest::NONE)
632 .Padding(PaddingMode::NONE)
633 .Authorization(TAG_APPLICATION_DATA, "appdata")
634 .Authorization(TAG_APPLICATION_ID, "clientid")));
635 AbortIfNeeded();
636}
637
638/*
639 * SigningOperationsTest.RsaPssSha256Success
640 *
641 * Verifies that RSA-PSS signature operations succeed.
642 */
643TEST_P(SigningOperationsTest, RsaPssSha256Success) {
644 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
645 .RsaSigningKey(2048, 65537)
646 .Digest(Digest::SHA_2_256)
647 .Padding(PaddingMode::RSA_PSS)
648 .Authorization(TAG_NO_AUTH_REQUIRED)));
649 // Use large message, which won't work without digesting.
650 string message(1024, 'a');
651 string signature = SignMessage(
652 message,
653 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
654}
655
656/*
657 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
658 *
659 * Verifies that keymint rejects signature operations that specify a padding mode when the key
660 * supports only unpadded operations.
661 */
662TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
663 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
664 .RsaSigningKey(2048, 65537)
665 .Digest(Digest::NONE)
666 .Authorization(TAG_NO_AUTH_REQUIRED)
667 .Padding(PaddingMode::NONE)));
668 string message = "12345678901234567890123456789012";
669 string signature;
670
671 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
672 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
673 .Digest(Digest::NONE)
674 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
675}
676
677/*
678 * SigningOperationsTest.NoUserConfirmation
679 *
680 * Verifies that keymint rejects signing operations for keys with
681 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
682 * presented.
683 */
684TEST_P(SigningOperationsTest, NoUserConfirmation) {
685 if (SecLevel() == SecurityLevel::STRONGBOX) return;
686 ASSERT_EQ(ErrorCode::OK,
687 GenerateKey(AuthorizationSetBuilder()
688 .RsaSigningKey(1024, 65537)
689 .Digest(Digest::NONE)
690 .Padding(PaddingMode::NONE)
691 .Authorization(TAG_NO_AUTH_REQUIRED)
692 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)));
693
694 const string message = "12345678901234567890123456789012";
695 EXPECT_EQ(ErrorCode::OK,
696 Begin(KeyPurpose::SIGN,
697 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
698 string signature;
699 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
700}
701
702/*
703 * SigningOperationsTest.RsaPkcs1Sha256Success
704 *
705 * Verifies that digested RSA-PKCS1 signature operations succeed.
706 */
707TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
709 .RsaSigningKey(2048, 65537)
710 .Digest(Digest::SHA_2_256)
711 .Authorization(TAG_NO_AUTH_REQUIRED)
712 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
713 string message(1024, 'a');
714 string signature = SignMessage(message, AuthorizationSetBuilder()
715 .Digest(Digest::SHA_2_256)
716 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
717}
718
719/*
720 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
721 *
722 * Verifies that undigested RSA-PKCS1 signature operations succeed.
723 */
724TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
726 .RsaSigningKey(2048, 65537)
727 .Digest(Digest::NONE)
728 .Authorization(TAG_NO_AUTH_REQUIRED)
729 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
730 string message(53, 'a');
731 string signature = SignMessage(message, AuthorizationSetBuilder()
732 .Digest(Digest::NONE)
733 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
734}
735
736/*
737 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
738 *
739 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
740 * given a too-long message.
741 */
742TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
744 .RsaSigningKey(2048, 65537)
745 .Digest(Digest::NONE)
746 .Authorization(TAG_NO_AUTH_REQUIRED)
747 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
748 string message(257, 'a');
749
750 EXPECT_EQ(ErrorCode::OK,
751 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
752 .Digest(Digest::NONE)
753 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
754 string signature;
755 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
756}
757
758/*
759 * SigningOperationsTest.RsaPssSha512TooSmallKey
760 *
761 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
762 * used with a key that is too small for the message.
763 *
764 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
765 * keymint specification requires that salt_size == digest_size, so the message will be
766 * digest_size * 2 +
767 * 16. Such a message can only be signed by a given key if the key is at least that size. This
768 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
769 * for a 1024-bit key.
770 */
771TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
772 if (SecLevel() == SecurityLevel::STRONGBOX) return;
773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
774 .RsaSigningKey(1024, 65537)
775 .Digest(Digest::SHA_2_512)
776 .Authorization(TAG_NO_AUTH_REQUIRED)
777 .Padding(PaddingMode::RSA_PSS)));
778 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
779 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
780 .Digest(Digest::SHA_2_512)
781 .Padding(PaddingMode::RSA_PSS)));
782}
783
784/*
785 * SigningOperationsTest.RsaNoPaddingTooLong
786 *
787 * Verifies that raw RSA signature operations fail with the correct error code when
788 * given a too-long message.
789 */
790TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
792 .RsaSigningKey(2048, 65537)
793 .Digest(Digest::NONE)
794 .Authorization(TAG_NO_AUTH_REQUIRED)
795 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
796 // One byte too long
797 string message(2048 / 8 + 1, 'a');
798 ASSERT_EQ(ErrorCode::OK,
799 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
800 .Digest(Digest::NONE)
801 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
802 string result;
803 ErrorCode finish_error_code = Finish(message, &result);
804 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
805 finish_error_code == ErrorCode::INVALID_ARGUMENT);
806
807 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
808 message = string(128 * 1024, 'a');
809 ASSERT_EQ(ErrorCode::OK,
810 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
811 .Digest(Digest::NONE)
812 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
813 finish_error_code = Finish(message, &result);
814 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
815 finish_error_code == ErrorCode::INVALID_ARGUMENT);
816}
817
818/*
819 * SigningOperationsTest.RsaAbort
820 *
821 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
822 * test, but the behavior should be algorithm and purpose-independent.
823 */
824TEST_P(SigningOperationsTest, RsaAbort) {
825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
826 .RsaSigningKey(2048, 65537)
827 .Digest(Digest::NONE)
828 .Authorization(TAG_NO_AUTH_REQUIRED)
829 .Padding(PaddingMode::NONE)));
830
831 ASSERT_EQ(ErrorCode::OK,
832 Begin(KeyPurpose::SIGN,
833 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
834 EXPECT_EQ(ErrorCode::OK, Abort());
835
836 // Another abort should fail
837 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
838
839 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -0800840 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700841}
842
843/*
844 * SigningOperationsTest.RsaUnsupportedPadding
845 *
846 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
847 * with a padding mode inappropriate for RSA.
848 */
849TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
851 .RsaSigningKey(2048, 65537)
852 .Authorization(TAG_NO_AUTH_REQUIRED)
853 .Digest(Digest::SHA_2_256 /* supported digest */)
854 .Padding(PaddingMode::PKCS7)));
855 ASSERT_EQ(
856 ErrorCode::UNSUPPORTED_PADDING_MODE,
857 Begin(KeyPurpose::SIGN,
858 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
859}
860
861/*
862 * SigningOperationsTest.RsaPssNoDigest
863 *
864 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
865 */
866TEST_P(SigningOperationsTest, RsaNoDigest) {
867 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
868 .RsaSigningKey(2048, 65537)
869 .Authorization(TAG_NO_AUTH_REQUIRED)
870 .Digest(Digest::NONE)
871 .Padding(PaddingMode::RSA_PSS)));
872 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
873 Begin(KeyPurpose::SIGN,
874 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
875
876 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
877 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
878}
879
880/*
881 * SigningOperationsTest.RsaPssNoDigest
882 *
883 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
884 * supported in some cases (as validated in other tests), but a mode must be specified.
885 */
886TEST_P(SigningOperationsTest, RsaNoPadding) {
887 // Padding must be specified
888 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
889 .RsaKey(2048, 65537)
890 .Authorization(TAG_NO_AUTH_REQUIRED)
891 .SigningKey()
892 .Digest(Digest::NONE)));
893 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
894 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
895}
896
897/*
898 * SigningOperationsTest.RsaShortMessage
899 *
900 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
901 */
902TEST_P(SigningOperationsTest, RsaTooShortMessage) {
903 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
904 .Authorization(TAG_NO_AUTH_REQUIRED)
905 .RsaSigningKey(2048, 65537)
906 .Digest(Digest::NONE)
907 .Padding(PaddingMode::NONE)));
908
909 // Barely shorter
910 string message(2048 / 8 - 1, 'a');
911 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
912
913 // Much shorter
914 message = "a";
915 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
916}
917
918/*
919 * SigningOperationsTest.RsaSignWithEncryptionKey
920 *
921 * Verifies that RSA encryption keys cannot be used to sign.
922 */
923TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
924 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
925 .Authorization(TAG_NO_AUTH_REQUIRED)
926 .RsaEncryptionKey(2048, 65537)
927 .Digest(Digest::NONE)
928 .Padding(PaddingMode::NONE)));
929 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
930 Begin(KeyPurpose::SIGN,
931 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
932}
933
934/*
935 * SigningOperationsTest.RsaSignTooLargeMessage
936 *
937 * Verifies that attempting a raw signature of a message which is the same length as the key,
938 * but numerically larger than the public modulus, fails with the correct error.
939 */
940TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
942 .Authorization(TAG_NO_AUTH_REQUIRED)
943 .RsaSigningKey(2048, 65537)
944 .Digest(Digest::NONE)
945 .Padding(PaddingMode::NONE)));
946
947 // Largest possible message will always be larger than the public modulus.
948 string message(2048 / 8, static_cast<char>(0xff));
949 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
950 .Authorization(TAG_NO_AUTH_REQUIRED)
951 .Digest(Digest::NONE)
952 .Padding(PaddingMode::NONE)));
953 string signature;
954 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
955}
956
957/*
958 * SigningOperationsTest.EcdsaAllSizesAndHashes
959 *
960 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
961 */
962TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
963 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
964 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
965 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
966 .Authorization(TAG_NO_AUTH_REQUIRED)
967 .EcdsaSigningKey(key_size)
968 .Digest(digest));
969 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
970 << " and digest " << digest;
971 if (error != ErrorCode::OK) continue;
972
973 string message(1024, 'a');
974 if (digest == Digest::NONE) message.resize(key_size / 8);
975 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
976 CheckedDeleteKey();
977 }
978 }
979}
980
981/*
982 * SigningOperationsTest.EcdsaAllCurves
983 *
984 * Verifies that ECDSA operations succeed with all possible curves.
985 */
986TEST_P(SigningOperationsTest, EcdsaAllCurves) {
987 for (auto curve : ValidCurves()) {
988 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
989 .Authorization(TAG_NO_AUTH_REQUIRED)
990 .EcdsaSigningKey(curve)
991 .Digest(Digest::SHA_2_256));
992 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
993 if (error != ErrorCode::OK) continue;
994
995 string message(1024, 'a');
996 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
997 CheckedDeleteKey();
998 }
999}
1000
1001/*
1002 * SigningOperationsTest.EcdsaNoDigestHugeData
1003 *
1004 * Verifies that ECDSA operations support very large messages, even without digesting. This
1005 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
1006 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
1007 * the framework.
1008 */
1009TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
1010 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1011 .Authorization(TAG_NO_AUTH_REQUIRED)
1012 .EcdsaSigningKey(256)
1013 .Digest(Digest::NONE)));
1014 string message(1 * 1024, 'a');
1015 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1016}
1017
1018/*
1019 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
1020 *
1021 * Verifies that using an EC key requires the correct app ID/data.
1022 */
1023TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
1024 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1025 .Authorization(TAG_NO_AUTH_REQUIRED)
1026 .EcdsaSigningKey(256)
1027 .Digest(Digest::NONE)
1028 .Authorization(TAG_APPLICATION_ID, "clientid")
1029 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1030 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1031 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1032 AbortIfNeeded();
1033 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1034 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1035 .Digest(Digest::NONE)
1036 .Authorization(TAG_APPLICATION_ID, "clientid")));
1037 AbortIfNeeded();
1038 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1039 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1040 .Digest(Digest::NONE)
1041 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1042 AbortIfNeeded();
1043 EXPECT_EQ(ErrorCode::OK,
1044 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1045 .Digest(Digest::NONE)
1046 .Authorization(TAG_APPLICATION_DATA, "appdata")
1047 .Authorization(TAG_APPLICATION_ID, "clientid")));
1048 AbortIfNeeded();
1049}
1050
1051/*
1052 * SigningOperationsTest.AesEcbSign
1053 *
1054 * Verifies that attempts to use AES keys to sign fail in the correct way.
1055 */
1056TEST_P(SigningOperationsTest, AesEcbSign) {
1057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1058 .Authorization(TAG_NO_AUTH_REQUIRED)
1059 .SigningKey()
1060 .AesEncryptionKey(128)
1061 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
1062
1063 AuthorizationSet out_params;
1064 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1065 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
1066 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1067 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
1068}
1069
1070/*
1071 * SigningOperationsTest.HmacAllDigests
1072 *
1073 * Verifies that HMAC works with all digests.
1074 */
1075TEST_P(SigningOperationsTest, HmacAllDigests) {
1076 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1078 .Authorization(TAG_NO_AUTH_REQUIRED)
1079 .HmacKey(128)
1080 .Digest(digest)
1081 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1082 << "Failed to create HMAC key with digest " << digest;
1083 string message = "12345678901234567890123456789012";
1084 string signature = MacMessage(message, digest, 160);
1085 EXPECT_EQ(160U / 8U, signature.size())
1086 << "Failed to sign with HMAC key with digest " << digest;
1087 CheckedDeleteKey();
1088 }
1089}
1090
1091/*
1092 * SigningOperationsTest.HmacSha256TooLargeMacLength
1093 *
1094 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
1095 * digest size.
1096 */
1097TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1099 .Authorization(TAG_NO_AUTH_REQUIRED)
1100 .HmacKey(128)
1101 .Digest(Digest::SHA_2_256)
1102 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1103 AuthorizationSet output_params;
1104 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1105 AuthorizationSetBuilder()
1106 .Digest(Digest::SHA_2_256)
1107 .Authorization(TAG_MAC_LENGTH, 264),
1108 &output_params));
1109}
1110
1111/*
1112 * SigningOperationsTest.HmacSha256TooSmallMacLength
1113 *
1114 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1115 * specified minimum MAC length.
1116 */
1117TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1118 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1119 .Authorization(TAG_NO_AUTH_REQUIRED)
1120 .HmacKey(128)
1121 .Digest(Digest::SHA_2_256)
1122 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1123 AuthorizationSet output_params;
1124 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1125 AuthorizationSetBuilder()
1126 .Digest(Digest::SHA_2_256)
1127 .Authorization(TAG_MAC_LENGTH, 120),
1128 &output_params));
1129}
1130
1131/*
1132 * SigningOperationsTest.HmacRfc4231TestCase3
1133 *
1134 * Validates against the test vectors from RFC 4231 test case 3.
1135 */
1136TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1137 string key(20, 0xaa);
1138 string message(50, 0xdd);
1139 uint8_t sha_224_expected[] = {
1140 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1141 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1142 };
1143 uint8_t sha_256_expected[] = {
1144 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1145 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1146 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1147 };
1148 uint8_t sha_384_expected[] = {
1149 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1150 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1151 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1152 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1153 };
1154 uint8_t sha_512_expected[] = {
1155 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1156 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1157 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1158 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1159 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1160 };
1161
1162 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1163 if (SecLevel() != SecurityLevel::STRONGBOX) {
1164 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1165 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1166 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1167 }
1168}
1169
1170/*
1171 * SigningOperationsTest.HmacRfc4231TestCase5
1172 *
1173 * Validates against the test vectors from RFC 4231 test case 5.
1174 */
1175TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
1176 string key(20, 0x0c);
1177 string message = "Test With Truncation";
1178
1179 uint8_t sha_224_expected[] = {
1180 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1181 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1182 };
1183 uint8_t sha_256_expected[] = {
1184 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1185 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1186 };
1187 uint8_t sha_384_expected[] = {
1188 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1189 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1190 };
1191 uint8_t sha_512_expected[] = {
1192 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1193 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1194 };
1195
1196 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1197 if (SecLevel() != SecurityLevel::STRONGBOX) {
1198 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1199 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1200 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1201 }
1202}
1203
1204INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
1205
1206typedef KeyMintAidlTestBase VerificationOperationsTest;
1207
1208/*
1209 * VerificationOperationsTest.RsaSuccess
1210 *
1211 * Verifies that a simple RSA signature/verification sequence succeeds.
1212 */
1213TEST_P(VerificationOperationsTest, RsaSuccess) {
1214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1215 .Authorization(TAG_NO_AUTH_REQUIRED)
1216 .RsaSigningKey(2048, 65537)
1217 .Digest(Digest::NONE)
1218 .Padding(PaddingMode::NONE)));
1219 string message = "12345678901234567890123456789012";
1220 string signature = SignMessage(
1221 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1222 VerifyMessage(message, signature,
1223 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1224}
1225
1226/*
1227 * VerificationOperationsTest.RsaSuccess
1228 *
1229 * Verifies RSA signature/verification for all padding modes and digests.
1230 */
1231TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
1232 auto authorizations = AuthorizationSetBuilder()
1233 .Authorization(TAG_NO_AUTH_REQUIRED)
1234 .RsaSigningKey(2048, 65537)
1235 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
1236 .Padding(PaddingMode::NONE)
1237 .Padding(PaddingMode::RSA_PSS)
1238 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
1239
1240 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
1241
1242 string message(128, 'a');
1243 string corrupt_message(message);
1244 ++corrupt_message[corrupt_message.size() / 2];
1245
1246 for (auto padding :
1247 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
1248 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
1249 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
1250 // Digesting only makes sense with padding.
1251 continue;
1252 }
1253
1254 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
1255 // PSS requires digesting.
1256 continue;
1257 }
1258
1259 string signature =
1260 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
1261 VerifyMessage(message, signature,
1262 AuthorizationSetBuilder().Digest(digest).Padding(padding));
1263
1264 /* TODO(seleneh) add exportkey tests back later when we have decided on
1265 * the new api.
1266 if (digest != Digest::NONE) {
1267 // Verify with OpenSSL.
1268 vector<uint8_t> pubkey;
1269 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
1270
1271 const uint8_t* p = pubkey.data();
1272 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
1273 ASSERT_TRUE(pkey.get());
1274
1275 EVP_MD_CTX digest_ctx;
1276 EVP_MD_CTX_init(&digest_ctx);
1277 EVP_PKEY_CTX* pkey_ctx;
1278 const EVP_MD* md = openssl_digest(digest);
1279 ASSERT_NE(md, nullptr);
1280 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
1281 nullptr, pkey.get()));
1282
1283 switch (padding) {
1284 case PaddingMode::RSA_PSS:
1285 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
1286 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
1287 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
1288 // PKCS1 is the default; don't need to set anything.
1289 break;
1290 default:
1291 FAIL();
1292 break;
1293 }
1294
1295 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
1296 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1297 reinterpret_cast<const
1298 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
1299 }
1300 */
1301
1302 // Corrupt signature shouldn't verify.
1303 string corrupt_signature(signature);
1304 ++corrupt_signature[corrupt_signature.size() / 2];
1305
1306 EXPECT_EQ(ErrorCode::OK,
1307 Begin(KeyPurpose::VERIFY,
1308 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1309 string result;
1310 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
1311
1312 // Corrupt message shouldn't verify
1313 EXPECT_EQ(ErrorCode::OK,
1314 Begin(KeyPurpose::VERIFY,
1315 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1316 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
1317 }
1318 }
1319}
1320
1321/*
1322 * VerificationOperationsTest.RsaSuccess
1323 *
1324 * Verifies ECDSA signature/verification for all digests and curves.
1325 */
1326TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
1327 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
1328
1329 string message = "1234567890";
1330 string corrupt_message = "2234567890";
1331 for (auto curve : ValidCurves()) {
1332 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1333 .Authorization(TAG_NO_AUTH_REQUIRED)
1334 .EcdsaSigningKey(curve)
1335 .Digest(digests));
1336 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
1337 if (error != ErrorCode::OK) {
1338 continue;
1339 }
1340
1341 for (auto digest : digests) {
1342 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1343 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
1344
1345 /* TODO(seleneh) add exportkey tests back later when we have decided on
1346 * the new api.
1347
1348 // Verify with OpenSSL
1349 if (digest != Digest::NONE) {
1350 vector<uint8_t> pubkey;
1351 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
1352 << curve << ' ' << digest;
1353
1354 const uint8_t* p = pubkey.data();
1355 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
1356 ASSERT_TRUE(pkey.get());
1357
1358 EVP_MD_CTX digest_ctx;
1359 EVP_MD_CTX_init(&digest_ctx);
1360 EVP_PKEY_CTX* pkey_ctx;
1361 const EVP_MD* md = openssl_digest(digest);
1362
1363 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
1364 nullptr, pkey.get()))
1365 << curve << ' ' << digest;
1366
1367 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
1368 message.size()))
1369 << curve << ' ' << digest;
1370
1371 EXPECT_EQ(1,
1372 EVP_DigestVerifyFinal(&digest_ctx,
1373 reinterpret_cast<const
1374 uint8_t*>(signature.data()), signature.size()))
1375 << curve << ' ' << digest;
1376
1377 EVP_MD_CTX_cleanup(&digest_ctx);
1378 }
1379 */
1380 // Corrupt signature shouldn't verify.
1381 string corrupt_signature(signature);
1382 ++corrupt_signature[corrupt_signature.size() / 2];
1383
1384 EXPECT_EQ(ErrorCode::OK,
1385 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1386 << curve << ' ' << digest;
1387
1388 string result;
1389 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
1390 << curve << ' ' << digest;
1391
1392 // Corrupt message shouldn't verify
1393 EXPECT_EQ(ErrorCode::OK,
1394 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1395 << curve << ' ' << digest;
1396
1397 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
1398 << curve << ' ' << digest;
1399 }
1400
1401 auto rc = DeleteKey();
1402 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
1403 }
1404}
1405
1406/*
1407 * VerificationOperationsTest.HmacSigningKeyCannotVerify
1408 *
1409 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
1410 */
1411TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
1412 string key_material = "HelloThisIsAKey";
1413
1414 vector<uint8_t> signing_key, verification_key;
1415 KeyCharacteristics signing_key_chars, verification_key_chars;
1416 EXPECT_EQ(ErrorCode::OK,
1417 ImportKey(AuthorizationSetBuilder()
1418 .Authorization(TAG_NO_AUTH_REQUIRED)
1419 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1420 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
1421 .Digest(Digest::SHA_2_256)
1422 .Authorization(TAG_MIN_MAC_LENGTH, 160),
1423 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
1424 EXPECT_EQ(ErrorCode::OK,
1425 ImportKey(AuthorizationSetBuilder()
1426 .Authorization(TAG_NO_AUTH_REQUIRED)
1427 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1428 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
1429 .Digest(Digest::SHA_2_256)
1430 .Authorization(TAG_MIN_MAC_LENGTH, 160),
1431 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
1432
1433 string message = "This is a message.";
1434 string signature = SignMessage(
1435 signing_key, message,
1436 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
1437
1438 // Signing key should not work.
1439 AuthorizationSet out_params;
1440 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1441 Begin(KeyPurpose::VERIFY, signing_key,
1442 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
1443
1444 // Verification key should work.
1445 VerifyMessage(verification_key, message, signature,
1446 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1447
1448 CheckedDeleteKey(&signing_key);
1449 CheckedDeleteKey(&verification_key);
1450}
1451
1452INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
1453
1454typedef KeyMintAidlTestBase ExportKeyTest;
1455
1456/*
1457 * ExportKeyTest.RsaUnsupportedKeyFormat
1458 *
1459 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
1460 */
1461// TODO(seleneh) add ExportKey to GenerateKey
1462// check result
1463
1464class ImportKeyTest : public KeyMintAidlTestBase {
1465 public:
1466 template <TagType tag_type, Tag tag, typename ValueT>
1467 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
1468 SCOPED_TRACE("CheckCryptoParam");
1469 if (IsSecure()) {
1470 EXPECT_TRUE(contains(key_characteristics_.hardwareEnforced, ttag, expected))
1471 << "Tag " << tag << " with value " << expected << " not found";
1472 EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag))
1473 << "Tag " << tag << " found";
1474 } else {
1475 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected))
1476 << "Tag " << tag << " with value " << expected << " not found";
1477 EXPECT_FALSE(contains(key_characteristics_.hardwareEnforced, ttag))
1478 << "Tag " << tag << " found";
1479 }
1480 }
1481
1482 void CheckOrigin() {
1483 SCOPED_TRACE("CheckOrigin");
1484 if (IsSecure()) {
1485 EXPECT_TRUE(contains(key_characteristics_.hardwareEnforced, TAG_ORIGIN,
1486 KeyOrigin::IMPORTED));
1487 } else {
1488 EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, TAG_ORIGIN,
1489 KeyOrigin::IMPORTED));
1490 }
1491 }
1492};
1493
1494/*
1495 * ImportKeyTest.RsaSuccess
1496 *
1497 * Verifies that importing and using an RSA key pair works correctly.
1498 */
1499TEST_P(ImportKeyTest, RsaSuccess) {
1500 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1501 .Authorization(TAG_NO_AUTH_REQUIRED)
1502 .RsaSigningKey(1024, 65537)
1503 .Digest(Digest::SHA_2_256)
1504 .Padding(PaddingMode::RSA_PSS),
1505 KeyFormat::PKCS8, rsa_key));
1506
1507 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
1508 CheckCryptoParam(TAG_KEY_SIZE, 1024U);
1509 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
1510 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1511 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
1512 CheckOrigin();
1513
1514 string message(1024 / 8, 'a');
1515 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
1516 string signature = SignMessage(message, params);
1517 VerifyMessage(message, signature, params);
1518}
1519
1520/*
1521 * ImportKeyTest.RsaKeySizeMismatch
1522 *
1523 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
1524 * correct way.
1525 */
1526TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1527 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1528 ImportKey(AuthorizationSetBuilder()
1529 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
1530 .Digest(Digest::NONE)
1531 .Padding(PaddingMode::NONE),
1532 KeyFormat::PKCS8, rsa_key));
1533}
1534
1535/*
1536 * ImportKeyTest.RsaPublicExponentMismatch
1537 *
1538 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
1539 * fails in the correct way.
1540 */
1541TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
1542 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1543 ImportKey(AuthorizationSetBuilder()
1544 .RsaSigningKey(1024, 3 /* Doesn't match key */)
1545 .Digest(Digest::NONE)
1546 .Padding(PaddingMode::NONE),
1547 KeyFormat::PKCS8, rsa_key));
1548}
1549
1550/*
1551 * ImportKeyTest.EcdsaSuccess
1552 *
1553 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
1554 */
1555TEST_P(ImportKeyTest, EcdsaSuccess) {
1556 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1557 .Authorization(TAG_NO_AUTH_REQUIRED)
1558 .EcdsaSigningKey(256)
1559 .Digest(Digest::SHA_2_256),
1560 KeyFormat::PKCS8, ec_256_key));
1561
1562 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1563 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1564 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1565 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1566
1567 CheckOrigin();
1568
1569 string message(32, 'a');
1570 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1571 string signature = SignMessage(message, params);
1572 VerifyMessage(message, signature, params);
1573}
1574
1575/*
1576 * ImportKeyTest.EcdsaP256RFC5915Success
1577 *
1578 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
1579 * correctly.
1580 */
1581TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
1582 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1583 .Authorization(TAG_NO_AUTH_REQUIRED)
1584 .EcdsaSigningKey(256)
1585 .Digest(Digest::SHA_2_256),
1586 KeyFormat::PKCS8, ec_256_key_rfc5915));
1587
1588 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1589 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1590 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1591 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1592
1593 CheckOrigin();
1594
1595 string message(32, 'a');
1596 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1597 string signature = SignMessage(message, params);
1598 VerifyMessage(message, signature, params);
1599}
1600
1601/*
1602 * ImportKeyTest.EcdsaP256SEC1Success
1603 *
1604 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
1605 */
1606TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
1607 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1608 .Authorization(TAG_NO_AUTH_REQUIRED)
1609 .EcdsaSigningKey(256)
1610 .Digest(Digest::SHA_2_256),
1611 KeyFormat::PKCS8, ec_256_key_sec1));
1612
1613 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1614 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1615 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1616 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1617
1618 CheckOrigin();
1619
1620 string message(32, 'a');
1621 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1622 string signature = SignMessage(message, params);
1623 VerifyMessage(message, signature, params);
1624}
1625
1626/*
1627 * ImportKeyTest.Ecdsa521Success
1628 *
1629 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
1630 */
1631TEST_P(ImportKeyTest, Ecdsa521Success) {
1632 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1633 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1634 .Authorization(TAG_NO_AUTH_REQUIRED)
1635 .EcdsaSigningKey(521)
1636 .Digest(Digest::SHA_2_256),
1637 KeyFormat::PKCS8, ec_521_key));
1638
1639 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1640 CheckCryptoParam(TAG_KEY_SIZE, 521U);
1641 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1642 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
1643 CheckOrigin();
1644
1645 string message(32, 'a');
1646 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1647 string signature = SignMessage(message, params);
1648 VerifyMessage(message, signature, params);
1649}
1650
1651/*
1652 * ImportKeyTest.EcdsaSizeMismatch
1653 *
1654 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
1655 * correct way.
1656 */
1657TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
1658 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1659 ImportKey(AuthorizationSetBuilder()
1660 .EcdsaSigningKey(224 /* Doesn't match key */)
1661 .Digest(Digest::NONE),
1662 KeyFormat::PKCS8, ec_256_key));
1663}
1664
1665/*
1666 * ImportKeyTest.EcdsaCurveMismatch
1667 *
1668 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
1669 * the correct way.
1670 */
1671TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
1672 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1673 ImportKey(AuthorizationSetBuilder()
1674 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
1675 .Digest(Digest::NONE),
1676 KeyFormat::PKCS8, ec_256_key));
1677}
1678
1679/*
1680 * ImportKeyTest.AesSuccess
1681 *
1682 * Verifies that importing and using an AES key works.
1683 */
1684TEST_P(ImportKeyTest, AesSuccess) {
1685 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1686 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1687 .Authorization(TAG_NO_AUTH_REQUIRED)
1688 .AesEncryptionKey(key.size() * 8)
1689 .EcbMode()
1690 .Padding(PaddingMode::PKCS7),
1691 KeyFormat::RAW, key));
1692
1693 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
1694 CheckCryptoParam(TAG_KEY_SIZE, 128U);
1695 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
1696 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
1697 CheckOrigin();
1698
1699 string message = "Hello World!";
1700 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
1701 string ciphertext = EncryptMessage(message, params);
1702 string plaintext = DecryptMessage(ciphertext, params);
1703 EXPECT_EQ(message, plaintext);
1704}
1705
1706/*
1707 * ImportKeyTest.AesSuccess
1708 *
1709 * Verifies that importing and using an HMAC key works.
1710 */
1711TEST_P(ImportKeyTest, HmacKeySuccess) {
1712 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1713 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1714 .Authorization(TAG_NO_AUTH_REQUIRED)
1715 .HmacKey(key.size() * 8)
1716 .Digest(Digest::SHA_2_256)
1717 .Authorization(TAG_MIN_MAC_LENGTH, 256),
1718 KeyFormat::RAW, key));
1719
1720 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
1721 CheckCryptoParam(TAG_KEY_SIZE, 128U);
1722 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1723 CheckOrigin();
1724
1725 string message = "Hello World!";
1726 string signature = MacMessage(message, Digest::SHA_2_256, 256);
1727 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1728}
1729
1730INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
1731
1732auto wrapped_key = hex2str(
1733 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
1734 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
1735 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
1736 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
1737 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
1738 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
1739 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
1740 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
1741 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
1742
1743auto wrapped_key_masked = hex2str(
1744 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
1745 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
1746 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
1747 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
1748 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
1749 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
1750 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
1751 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
1752 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
1753
1754auto wrapping_key = hex2str(
1755 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
1756 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
1757 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
1758 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
1759 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
1760 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
1761 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
1762 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
1763 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
1764 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
1765 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
1766 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
1767 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
1768 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
1769 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
1770 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
1771 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
1772 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
1773 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
1774 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
1775 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
1776 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
1777 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
1778 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
1779 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
1780 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
1781 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
1782 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
1783 "f27ba61be6ad02dfddda8f4e6822");
1784
1785string zero_masking_key =
1786 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
1787string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
1788
1789class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
1790
1791TEST_P(ImportWrappedKeyTest, Success) {
1792 auto wrapping_key_desc = AuthorizationSetBuilder()
1793 .RsaEncryptionKey(2048, 65537)
1794 .Digest(Digest::SHA_2_256)
1795 .Padding(PaddingMode::RSA_OAEP)
1796 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY);
1797
1798 ASSERT_EQ(ErrorCode::OK,
1799 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
1800 AuthorizationSetBuilder()
1801 .Digest(Digest::SHA_2_256)
1802 .Padding(PaddingMode::RSA_OAEP)));
1803
1804 string message = "Hello World!";
1805 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
1806 string ciphertext = EncryptMessage(message, params);
1807 string plaintext = DecryptMessage(ciphertext, params);
1808 EXPECT_EQ(message, plaintext);
1809}
1810
1811TEST_P(ImportWrappedKeyTest, SuccessMasked) {
1812 auto wrapping_key_desc = AuthorizationSetBuilder()
1813 .RsaEncryptionKey(2048, 65537)
1814 .Digest(Digest::SHA_2_256)
1815 .Padding(PaddingMode::RSA_OAEP)
1816 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY);
1817
1818 ASSERT_EQ(ErrorCode::OK,
1819 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
1820 AuthorizationSetBuilder()
1821 .Digest(Digest::SHA_2_256)
1822 .Padding(PaddingMode::RSA_OAEP)));
1823}
1824
1825TEST_P(ImportWrappedKeyTest, WrongMask) {
1826 auto wrapping_key_desc = AuthorizationSetBuilder()
1827 .RsaEncryptionKey(2048, 65537)
1828 .Digest(Digest::SHA_2_256)
1829 .Padding(PaddingMode::RSA_OAEP)
1830 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY);
1831
1832 ASSERT_EQ(
1833 ErrorCode::VERIFICATION_FAILED,
1834 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
1835 AuthorizationSetBuilder()
1836 .Digest(Digest::SHA_2_256)
1837 .Padding(PaddingMode::RSA_OAEP)));
1838}
1839
1840TEST_P(ImportWrappedKeyTest, WrongPurpose) {
1841 auto wrapping_key_desc = AuthorizationSetBuilder()
1842 .RsaEncryptionKey(2048, 65537)
1843 .Digest(Digest::SHA_2_256)
1844 .Padding(PaddingMode::RSA_OAEP);
1845
1846 ASSERT_EQ(
1847 ErrorCode::INCOMPATIBLE_PURPOSE,
1848 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
1849 AuthorizationSetBuilder()
1850 .Digest(Digest::SHA_2_256)
1851 .Padding(PaddingMode::RSA_OAEP)));
1852}
1853
1854INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
1855
1856typedef KeyMintAidlTestBase EncryptionOperationsTest;
1857
1858/*
1859 * EncryptionOperationsTest.RsaNoPaddingSuccess
1860 *
1861 * Verifies that raw RSA encryption works.
1862 */
1863TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
1864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1865 .Authorization(TAG_NO_AUTH_REQUIRED)
1866 .RsaEncryptionKey(2048, 65537)
1867 .Padding(PaddingMode::NONE)));
1868
1869 string message = string(2048 / 8, 'a');
1870 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
1871 string ciphertext1 = EncryptMessage(message, params);
1872 EXPECT_EQ(2048U / 8, ciphertext1.size());
1873
1874 string ciphertext2 = EncryptMessage(message, params);
1875 EXPECT_EQ(2048U / 8, ciphertext2.size());
1876
1877 // Unpadded RSA is deterministic
1878 EXPECT_EQ(ciphertext1, ciphertext2);
1879}
1880
1881/*
1882 * EncryptionOperationsTest.RsaNoPaddingShortMessage
1883 *
1884 * Verifies that raw RSA encryption of short messages works.
1885 */
1886TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
1887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1888 .Authorization(TAG_NO_AUTH_REQUIRED)
1889 .RsaEncryptionKey(2048, 65537)
1890 .Padding(PaddingMode::NONE)));
1891
1892 string message = "1";
1893 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
1894
1895 string ciphertext = EncryptMessage(message, params);
1896 EXPECT_EQ(2048U / 8, ciphertext.size());
1897
1898 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
1899 string plaintext = DecryptMessage(ciphertext, params);
1900
1901 EXPECT_EQ(expected_plaintext, plaintext);
1902
1903 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
1904 message = static_cast<char>(1);
1905 ciphertext = EncryptMessage(message, params);
1906 EXPECT_EQ(2048U / 8, ciphertext.size());
1907 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
1908}
1909
1910/*
1911 * EncryptionOperationsTest.RsaNoPaddingTooLong
1912 *
1913 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
1914 */
1915TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
1916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1917 .Authorization(TAG_NO_AUTH_REQUIRED)
1918 .RsaEncryptionKey(2048, 65537)
1919 .Padding(PaddingMode::NONE)));
1920
1921 string message(2048 / 8 + 1, 'a');
1922
1923 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
1924 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
1925
1926 string result;
1927 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
1928}
1929
1930/*
1931 * EncryptionOperationsTest.RsaNoPaddingTooLarge
1932 *
1933 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
1934 * way.
1935 */
1936// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
1937// version of ExportKey inside generateKey
1938
1939/*
1940 * EncryptionOperationsTest.RsaOaepSuccess
1941 *
1942 * Verifies that RSA-OAEP encryption operations work, with all digests.
1943 */
1944TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
1945 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
1946
1947 size_t key_size = 2048; // Need largish key for SHA-512 test.
1948 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1949 .Authorization(TAG_NO_AUTH_REQUIRED)
1950 .RsaEncryptionKey(key_size, 65537)
1951 .Padding(PaddingMode::RSA_OAEP)
1952 .Digest(digests)));
1953
1954 string message = "Hello";
1955
1956 for (auto digest : digests) {
1957 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
1958 string ciphertext1 = EncryptMessage(message, params);
1959 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
1960 EXPECT_EQ(key_size / 8, ciphertext1.size());
1961
1962 string ciphertext2 = EncryptMessage(message, params);
1963 EXPECT_EQ(key_size / 8, ciphertext2.size());
1964
1965 // OAEP randomizes padding so every result should be different (with astronomically high
1966 // probability).
1967 EXPECT_NE(ciphertext1, ciphertext2);
1968
1969 string plaintext1 = DecryptMessage(ciphertext1, params);
1970 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
1971 string plaintext2 = DecryptMessage(ciphertext2, params);
1972 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
1973
1974 // Decrypting corrupted ciphertext should fail.
1975 size_t offset_to_corrupt = random() % ciphertext1.size();
1976 char corrupt_byte;
1977 do {
1978 corrupt_byte = static_cast<char>(random() % 256);
1979 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
1980 ciphertext1[offset_to_corrupt] = corrupt_byte;
1981
1982 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
1983 string result;
1984 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
1985 EXPECT_EQ(0U, result.size());
1986 }
1987}
1988
1989/*
1990 * EncryptionOperationsTest.RsaOaepInvalidDigest
1991 *
1992 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
1993 * without a digest.
1994 */
1995TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
1996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1997 .Authorization(TAG_NO_AUTH_REQUIRED)
1998 .RsaEncryptionKey(2048, 65537)
1999 .Padding(PaddingMode::RSA_OAEP)
2000 .Digest(Digest::NONE)));
2001 string message = "Hello World!";
2002
2003 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2004 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2005}
2006
2007/*
2008 * EncryptionOperationsTest.RsaOaepInvalidDigest
2009 *
2010 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
2011 * with a different digest than was used to encrypt.
2012 */
2013TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2014 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2015
2016 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2017 .Authorization(TAG_NO_AUTH_REQUIRED)
2018 .RsaEncryptionKey(1024, 65537)
2019 .Padding(PaddingMode::RSA_OAEP)
2020 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)));
2021 string message = "Hello World!";
2022 string ciphertext = EncryptMessage(
2023 message,
2024 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2025
2026 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2027 .Digest(Digest::SHA_2_256)
2028 .Padding(PaddingMode::RSA_OAEP)));
2029 string result;
2030 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2031 EXPECT_EQ(0U, result.size());
2032}
2033
2034/*
2035 * EncryptionOperationsTest.RsaOaepTooLarge
2036 *
2037 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2038 * too-large message.
2039 */
2040TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2042 .Authorization(TAG_NO_AUTH_REQUIRED)
2043 .RsaEncryptionKey(2048, 65537)
2044 .Padding(PaddingMode::RSA_OAEP)
2045 .Digest(Digest::SHA_2_256)));
2046 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
2047 constexpr size_t oaep_overhead = 2 * digest_size + 2;
2048 string message(2048 / 8 - oaep_overhead + 1, 'a');
2049 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2050 .Padding(PaddingMode::RSA_OAEP)
2051 .Digest(Digest::SHA_2_256)));
2052 string result;
2053 ErrorCode error = Finish(message, &result);
2054 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2055 EXPECT_EQ(0U, result.size());
2056}
2057
2058/*
2059 * EncryptionOperationsTest.RsaPkcs1Success
2060 *
2061 * Verifies that RSA PKCS encryption/decrypts works.
2062 */
2063TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2064 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2065 .Authorization(TAG_NO_AUTH_REQUIRED)
2066 .RsaEncryptionKey(2048, 65537)
2067 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2068
2069 string message = "Hello World!";
2070 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2071 string ciphertext1 = EncryptMessage(message, params);
2072 EXPECT_EQ(2048U / 8, ciphertext1.size());
2073
2074 string ciphertext2 = EncryptMessage(message, params);
2075 EXPECT_EQ(2048U / 8, ciphertext2.size());
2076
2077 // PKCS1 v1.5 randomizes padding so every result should be different.
2078 EXPECT_NE(ciphertext1, ciphertext2);
2079
2080 string plaintext = DecryptMessage(ciphertext1, params);
2081 EXPECT_EQ(message, plaintext);
2082
2083 // Decrypting corrupted ciphertext should fail.
2084 size_t offset_to_corrupt = random() % ciphertext1.size();
2085 char corrupt_byte;
2086 do {
2087 corrupt_byte = static_cast<char>(random() % 256);
2088 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2089 ciphertext1[offset_to_corrupt] = corrupt_byte;
2090
2091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2092 string result;
2093 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2094 EXPECT_EQ(0U, result.size());
2095}
2096
2097/*
2098 * EncryptionOperationsTest.RsaPkcs1TooLarge
2099 *
2100 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2101 */
2102TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2104 .Authorization(TAG_NO_AUTH_REQUIRED)
2105 .RsaEncryptionKey(2048, 65537)
2106 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2107 string message(2048 / 8 - 10, 'a');
2108
2109 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2110 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2111 string result;
2112 ErrorCode error = Finish(message, &result);
2113 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2114 EXPECT_EQ(0U, result.size());
2115}
2116
2117/*
2118 * EncryptionOperationsTest.EcdsaEncrypt
2119 *
2120 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2121 */
2122TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2124 .Authorization(TAG_NO_AUTH_REQUIRED)
2125 .EcdsaSigningKey(256)
2126 .Digest(Digest::NONE)));
2127 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2128 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2129 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2130}
2131
2132/*
2133 * EncryptionOperationsTest.HmacEncrypt
2134 *
2135 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2136 */
2137TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2138 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2139 .Authorization(TAG_NO_AUTH_REQUIRED)
2140 .HmacKey(128)
2141 .Digest(Digest::SHA_2_256)
2142 .Padding(PaddingMode::NONE)
2143 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2144 auto params = AuthorizationSetBuilder()
2145 .Digest(Digest::SHA_2_256)
2146 .Padding(PaddingMode::NONE)
2147 .Authorization(TAG_MAC_LENGTH, 128);
2148 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2149 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2150}
2151
2152/*
2153 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2154 *
2155 * Verifies that AES ECB mode works.
2156 */
2157TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2158 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2159 .Authorization(TAG_NO_AUTH_REQUIRED)
2160 .AesEncryptionKey(128)
2161 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2162 .Padding(PaddingMode::NONE)));
2163
2164 ASSERT_GT(key_blob_.size(), 0U);
2165 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2166
2167 // Two-block message.
2168 string message = "12345678901234567890123456789012";
2169 string ciphertext1 = EncryptMessage(message, params);
2170 EXPECT_EQ(message.size(), ciphertext1.size());
2171
2172 string ciphertext2 = EncryptMessage(string(message), params);
2173 EXPECT_EQ(message.size(), ciphertext2.size());
2174
2175 // ECB is deterministic.
2176 EXPECT_EQ(ciphertext1, ciphertext2);
2177
2178 string plaintext = DecryptMessage(ciphertext1, params);
2179 EXPECT_EQ(message, plaintext);
2180}
2181
2182/*
2183 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2184 *
2185 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2186 */
2187TEST_P(EncryptionOperationsTest, AesWrongMode) {
2188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2189 .Authorization(TAG_NO_AUTH_REQUIRED)
2190 .AesEncryptionKey(128)
2191 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2192 .Padding(PaddingMode::NONE)));
2193
2194 ASSERT_GT(key_blob_.size(), 0U);
2195
2196 // Two-block message.
2197 string message = "12345678901234567890123456789012";
2198 EXPECT_EQ(
2199 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2200 Begin(KeyPurpose::ENCRYPT,
2201 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2202}
2203
2204/*
2205 * EncryptionOperationsTest.AesWrongPurpose
2206 *
2207 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
2208 * specified.
2209 */
2210TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
2211 auto err = GenerateKey(AuthorizationSetBuilder()
2212 .Authorization(TAG_NO_AUTH_REQUIRED)
2213 .AesKey(128)
2214 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
2215 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2216 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2217 .Padding(PaddingMode::NONE));
2218 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
2219 ASSERT_GT(key_blob_.size(), 0U);
2220
2221 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2222 .BlockMode(BlockMode::GCM)
2223 .Padding(PaddingMode::NONE)
2224 .Authorization(TAG_MAC_LENGTH, 128));
2225 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2226
2227 CheckedDeleteKey();
2228
2229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2230 .Authorization(TAG_NO_AUTH_REQUIRED)
2231 .AesKey(128)
2232 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
2233 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2234 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2235 .Padding(PaddingMode::NONE)));
2236
2237 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2238 .BlockMode(BlockMode::GCM)
2239 .Padding(PaddingMode::NONE)
2240 .Authorization(TAG_MAC_LENGTH, 128));
2241 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2242}
2243
2244/*
2245 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2246 *
2247 * Verifies that AES encryption fails in the correct way when provided an input that is not a
2248 * multiple of the block size and no padding is specified.
2249 */
2250TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2251 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2252 .Authorization(TAG_NO_AUTH_REQUIRED)
2253 .AesEncryptionKey(128)
2254 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2255 .Padding(PaddingMode::NONE)));
2256 // Message is slightly shorter than two blocks.
2257 string message(16 * 2 - 1, 'a');
2258
2259 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2260 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2261 string ciphertext;
2262 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2263 EXPECT_EQ(0U, ciphertext.size());
2264}
2265
2266/*
2267 * EncryptionOperationsTest.AesEcbPkcs7Padding
2268 *
2269 * Verifies that AES PKCS7 padding works for any message length.
2270 */
2271TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2273 .Authorization(TAG_NO_AUTH_REQUIRED)
2274 .AesEncryptionKey(128)
2275 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2276 .Padding(PaddingMode::PKCS7)));
2277
2278 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2279
2280 // Try various message lengths; all should work.
2281 for (size_t i = 0; i < 32; ++i) {
2282 string message(i, 'a');
2283 string ciphertext = EncryptMessage(message, params);
2284 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2285 string plaintext = DecryptMessage(ciphertext, params);
2286 EXPECT_EQ(message, plaintext);
2287 }
2288}
2289
2290/*
2291 * EncryptionOperationsTest.AesEcbWrongPadding
2292 *
2293 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2294 * specified.
2295 */
2296TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
2297 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2298 .Authorization(TAG_NO_AUTH_REQUIRED)
2299 .AesEncryptionKey(128)
2300 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2301 .Padding(PaddingMode::NONE)));
2302
2303 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2304
2305 // Try various message lengths; all should fail
2306 for (size_t i = 0; i < 32; ++i) {
2307 string message(i, 'a');
2308 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2309 }
2310}
2311
2312/*
2313 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
2314 *
2315 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
2316 */
2317TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2318 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2319 .Authorization(TAG_NO_AUTH_REQUIRED)
2320 .AesEncryptionKey(128)
2321 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2322 .Padding(PaddingMode::PKCS7)));
2323
2324 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2325
2326 string message = "a";
2327 string ciphertext = EncryptMessage(message, params);
2328 EXPECT_EQ(16U, ciphertext.size());
2329 EXPECT_NE(ciphertext, message);
2330 ++ciphertext[ciphertext.size() / 2];
2331
2332 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2333 string plaintext;
2334 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
2335}
2336
2337vector<uint8_t> CopyIv(const AuthorizationSet& set) {
2338 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002339 EXPECT_TRUE(iv);
2340 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07002341}
2342
2343/*
2344 * EncryptionOperationsTest.AesCtrRoundTripSuccess
2345 *
2346 * Verifies that AES CTR mode works.
2347 */
2348TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2350 .Authorization(TAG_NO_AUTH_REQUIRED)
2351 .AesEncryptionKey(128)
2352 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2353 .Padding(PaddingMode::NONE)));
2354
2355 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2356
2357 string message = "123";
2358 AuthorizationSet out_params;
2359 string ciphertext1 = EncryptMessage(message, params, &out_params);
2360 vector<uint8_t> iv1 = CopyIv(out_params);
2361 EXPECT_EQ(16U, iv1.size());
2362
2363 EXPECT_EQ(message.size(), ciphertext1.size());
2364
2365 out_params.Clear();
2366 string ciphertext2 = EncryptMessage(message, params, &out_params);
2367 vector<uint8_t> iv2 = CopyIv(out_params);
2368 EXPECT_EQ(16U, iv2.size());
2369
2370 // IVs should be random, so ciphertexts should differ.
2371 EXPECT_NE(ciphertext1, ciphertext2);
2372
2373 auto params_iv1 =
2374 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
2375 auto params_iv2 =
2376 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
2377
2378 string plaintext = DecryptMessage(ciphertext1, params_iv1);
2379 EXPECT_EQ(message, plaintext);
2380 plaintext = DecryptMessage(ciphertext2, params_iv2);
2381 EXPECT_EQ(message, plaintext);
2382
2383 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
2384 plaintext = DecryptMessage(ciphertext1, params_iv2);
2385 EXPECT_NE(message, plaintext);
2386 plaintext = DecryptMessage(ciphertext2, params_iv1);
2387 EXPECT_NE(message, plaintext);
2388}
2389
2390/*
2391 * EncryptionOperationsTest.AesIncremental
2392 *
2393 * Verifies that AES works, all modes, when provided data in various size increments.
2394 */
2395TEST_P(EncryptionOperationsTest, AesIncremental) {
2396 auto block_modes = {
2397 BlockMode::ECB,
2398 BlockMode::CBC,
2399 BlockMode::CTR,
2400 BlockMode::GCM,
2401 };
2402
2403 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2404 .Authorization(TAG_NO_AUTH_REQUIRED)
2405 .AesEncryptionKey(128)
2406 .BlockMode(block_modes)
2407 .Padding(PaddingMode::NONE)
2408 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2409
2410 for (int increment = 1; increment <= 240; ++increment) {
2411 for (auto block_mode : block_modes) {
2412 string message(240, 'a');
2413 auto params = AuthorizationSetBuilder()
2414 .BlockMode(block_mode)
2415 .Padding(PaddingMode::NONE)
2416 .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
2417
2418 AuthorizationSet output_params;
2419 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
2420
2421 string ciphertext;
2422 int32_t input_consumed;
2423 string to_send;
2424 for (size_t i = 0; i < message.size(); i += increment) {
2425 to_send.append(message.substr(i, increment));
2426 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
2427 EXPECT_EQ(to_send.length(), input_consumed);
2428 to_send = to_send.substr(input_consumed);
2429 EXPECT_EQ(0U, to_send.length());
2430
2431 switch (block_mode) {
2432 case BlockMode::ECB:
2433 case BlockMode::CBC:
2434 // Implementations must take as many blocks as possible, leaving less
2435 // than a block.
2436 EXPECT_LE(to_send.length(), 16U);
2437 break;
2438 case BlockMode::GCM:
2439 case BlockMode::CTR:
2440 // Implementations must always take all the data.
2441 EXPECT_EQ(0U, to_send.length());
2442 break;
2443 }
2444 }
2445 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
2446
2447 switch (block_mode) {
2448 case BlockMode::GCM:
2449 EXPECT_EQ(message.size() + 16, ciphertext.size());
2450 break;
2451 case BlockMode::CTR:
2452 EXPECT_EQ(message.size(), ciphertext.size());
2453 break;
2454 case BlockMode::CBC:
2455 case BlockMode::ECB:
2456 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
2457 break;
2458 }
2459
2460 auto iv = output_params.GetTagValue(TAG_NONCE);
2461 switch (block_mode) {
2462 case BlockMode::CBC:
2463 case BlockMode::GCM:
2464 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002465 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
2466 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
2467 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07002468 break;
2469
2470 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002471 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07002472 break;
2473 }
2474
2475 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
2476 << "Decrypt begin() failed for block mode " << block_mode;
2477
2478 string plaintext;
2479 for (size_t i = 0; i < ciphertext.size(); i += increment) {
2480 to_send.append(ciphertext.substr(i, increment));
2481 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
2482 to_send = to_send.substr(input_consumed);
2483 }
2484 ErrorCode error = Finish(to_send, &plaintext);
2485 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
2486 << " and increment " << increment;
2487 if (error == ErrorCode::OK) {
2488 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
2489 << block_mode << " and increment " << increment;
2490 }
2491 }
2492 }
2493}
2494
2495struct AesCtrSp80038aTestVector {
2496 const char* key;
2497 const char* nonce;
2498 const char* plaintext;
2499 const char* ciphertext;
2500};
2501
2502// These test vectors are taken from
2503// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2504static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2505 // AES-128
2506 {
2507 "2b7e151628aed2a6abf7158809cf4f3c",
2508 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2509 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2510 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2511 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2512 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2513 },
2514 // AES-192
2515 {
2516 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
2517 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2518 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2519 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2520 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
2521 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
2522 },
2523 // AES-256
2524 {
2525 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
2526 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2527 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2528 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2529 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
2530 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
2531 },
2532};
2533
2534/*
2535 * EncryptionOperationsTest.AesCtrSp80038aTestVector
2536 *
2537 * Verifies AES CTR implementation against SP800-38A test vectors.
2538 */
2539TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
2540 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
2541 for (size_t i = 0; i < 3; i++) {
2542 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
2543 const string key = hex2str(test.key);
2544 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
2545 InvalidSizes.end())
2546 continue;
2547 const string nonce = hex2str(test.nonce);
2548 const string plaintext = hex2str(test.plaintext);
2549 const string ciphertext = hex2str(test.ciphertext);
2550 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
2551 }
2552}
2553
2554/*
2555 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
2556 *
2557 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
2558 */
2559TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
2560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2561 .Authorization(TAG_NO_AUTH_REQUIRED)
2562 .AesEncryptionKey(128)
2563 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2564 .Padding(PaddingMode::PKCS7)));
2565 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2566 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2567}
2568
2569/*
2570 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
2571 *
2572 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
2573 */
2574TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
2575 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2576 .Authorization(TAG_NO_AUTH_REQUIRED)
2577 .AesEncryptionKey(128)
2578 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2579 .Authorization(TAG_CALLER_NONCE)
2580 .Padding(PaddingMode::NONE)));
2581
2582 auto params = AuthorizationSetBuilder()
2583 .BlockMode(BlockMode::CTR)
2584 .Padding(PaddingMode::NONE)
2585 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
2586 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
2587
2588 params = AuthorizationSetBuilder()
2589 .BlockMode(BlockMode::CTR)
2590 .Padding(PaddingMode::NONE)
2591 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
2592 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
2593
2594 params = AuthorizationSetBuilder()
2595 .BlockMode(BlockMode::CTR)
2596 .Padding(PaddingMode::NONE)
2597 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
2598 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
2599}
2600
2601/*
2602 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
2603 *
2604 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
2605 */
2606TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
2607 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2608 .Authorization(TAG_NO_AUTH_REQUIRED)
2609 .AesEncryptionKey(128)
2610 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2611 .Padding(PaddingMode::NONE)));
2612 // Two-block message.
2613 string message = "12345678901234567890123456789012";
2614 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
2615 AuthorizationSet out_params;
2616 string ciphertext1 = EncryptMessage(message, params, &out_params);
2617 vector<uint8_t> iv1 = CopyIv(out_params);
2618 EXPECT_EQ(message.size(), ciphertext1.size());
2619
2620 out_params.Clear();
2621
2622 string ciphertext2 = EncryptMessage(message, params, &out_params);
2623 vector<uint8_t> iv2 = CopyIv(out_params);
2624 EXPECT_EQ(message.size(), ciphertext2.size());
2625
2626 // IVs should be random, so ciphertexts should differ.
2627 EXPECT_NE(ciphertext1, ciphertext2);
2628
2629 params.push_back(TAG_NONCE, iv1);
2630 string plaintext = DecryptMessage(ciphertext1, params);
2631 EXPECT_EQ(message, plaintext);
2632}
2633
2634/*
2635 * EncryptionOperationsTest.AesCallerNonce
2636 *
2637 * Verifies that AES caller-provided nonces work correctly.
2638 */
2639TEST_P(EncryptionOperationsTest, AesCallerNonce) {
2640 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2641 .Authorization(TAG_NO_AUTH_REQUIRED)
2642 .AesEncryptionKey(128)
2643 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2644 .Authorization(TAG_CALLER_NONCE)
2645 .Padding(PaddingMode::NONE)));
2646
2647 string message = "12345678901234567890123456789012";
2648
2649 // Don't specify nonce, should get a random one.
2650 AuthorizationSetBuilder params =
2651 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
2652 AuthorizationSet out_params;
2653 string ciphertext = EncryptMessage(message, params, &out_params);
2654 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002655 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07002656
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002657 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07002658 string plaintext = DecryptMessage(ciphertext, params);
2659 EXPECT_EQ(message, plaintext);
2660
2661 // Now specify a nonce, should also work.
2662 params = AuthorizationSetBuilder()
2663 .BlockMode(BlockMode::CBC)
2664 .Padding(PaddingMode::NONE)
2665 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
2666 out_params.Clear();
2667 ciphertext = EncryptMessage(message, params, &out_params);
2668
2669 // Decrypt with correct nonce.
2670 plaintext = DecryptMessage(ciphertext, params);
2671 EXPECT_EQ(message, plaintext);
2672
2673 // Try with wrong nonce.
2674 params = AuthorizationSetBuilder()
2675 .BlockMode(BlockMode::CBC)
2676 .Padding(PaddingMode::NONE)
2677 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
2678 plaintext = DecryptMessage(ciphertext, params);
2679 EXPECT_NE(message, plaintext);
2680}
2681
2682/*
2683 * EncryptionOperationsTest.AesCallerNonceProhibited
2684 *
2685 * Verifies that caller-provided nonces are not permitted when not specified in the key
2686 * authorizations.
2687 */
2688TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
2689 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2690 .Authorization(TAG_NO_AUTH_REQUIRED)
2691 .AesEncryptionKey(128)
2692 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2693 .Padding(PaddingMode::NONE)));
2694
2695 string message = "12345678901234567890123456789012";
2696
2697 // Don't specify nonce, should get a random one.
2698 AuthorizationSetBuilder params =
2699 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
2700 AuthorizationSet out_params;
2701 string ciphertext = EncryptMessage(message, params, &out_params);
2702 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002703 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07002704
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002705 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07002706 string plaintext = DecryptMessage(ciphertext, params);
2707 EXPECT_EQ(message, plaintext);
2708
2709 // Now specify a nonce, should fail
2710 params = AuthorizationSetBuilder()
2711 .BlockMode(BlockMode::CBC)
2712 .Padding(PaddingMode::NONE)
2713 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
2714 out_params.Clear();
2715 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
2716}
2717
2718/*
2719 * EncryptionOperationsTest.AesGcmRoundTripSuccess
2720 *
2721 * Verifies that AES GCM mode works.
2722 */
2723TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
2724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2725 .Authorization(TAG_NO_AUTH_REQUIRED)
2726 .AesEncryptionKey(128)
2727 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2728 .Padding(PaddingMode::NONE)
2729 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2730
2731 string aad = "foobar";
2732 string message = "123456789012345678901234567890123456";
2733
2734 auto begin_params = AuthorizationSetBuilder()
2735 .BlockMode(BlockMode::GCM)
2736 .Padding(PaddingMode::NONE)
2737 .Authorization(TAG_MAC_LENGTH, 128);
2738
2739 auto update_params =
2740 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2741
2742 // Encrypt
2743 AuthorizationSet begin_out_params;
2744 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
2745 << "Begin encrypt";
2746 string ciphertext;
2747 AuthorizationSet update_out_params;
2748 ASSERT_EQ(ErrorCode::OK, Finish(update_params, message, "", &update_out_params, &ciphertext));
2749
2750 ASSERT_EQ(ciphertext.length(), message.length() + 16);
2751
2752 // Grab nonce
2753 begin_params.push_back(begin_out_params);
2754
2755 // Decrypt.
2756 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
2757 string plaintext;
2758 int32_t input_consumed;
2759 ASSERT_EQ(ErrorCode::OK,
2760 Update(update_params, ciphertext, &update_out_params, &plaintext, &input_consumed));
2761 EXPECT_EQ(ciphertext.size(), input_consumed);
2762 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
2763 EXPECT_EQ(message.length(), plaintext.length());
2764 EXPECT_EQ(message, plaintext);
2765}
2766
2767/*
2768 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
2769 *
2770 * Verifies that AES GCM mode works, even when there's a long delay
2771 * between operations.
2772 */
2773TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
2774 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2775 .Authorization(TAG_NO_AUTH_REQUIRED)
2776 .AesEncryptionKey(128)
2777 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2778 .Padding(PaddingMode::NONE)
2779 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2780
2781 string aad = "foobar";
2782 string message = "123456789012345678901234567890123456";
2783
2784 auto begin_params = AuthorizationSetBuilder()
2785 .BlockMode(BlockMode::GCM)
2786 .Padding(PaddingMode::NONE)
2787 .Authorization(TAG_MAC_LENGTH, 128);
2788
2789 auto update_params =
2790 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2791
2792 // Encrypt
2793 AuthorizationSet begin_out_params;
2794 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
2795 << "Begin encrypt";
2796 string ciphertext;
2797 AuthorizationSet update_out_params;
2798 sleep(5);
2799 ASSERT_EQ(ErrorCode::OK, Finish(update_params, message, "", &update_out_params, &ciphertext));
2800
2801 ASSERT_EQ(ciphertext.length(), message.length() + 16);
2802
2803 // Grab nonce
2804 begin_params.push_back(begin_out_params);
2805
2806 // Decrypt.
2807 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
2808 string plaintext;
2809 int32_t input_consumed;
2810 sleep(5);
2811 ASSERT_EQ(ErrorCode::OK,
2812 Update(update_params, ciphertext, &update_out_params, &plaintext, &input_consumed));
2813 EXPECT_EQ(ciphertext.size(), input_consumed);
2814 sleep(5);
2815 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
2816 EXPECT_EQ(message.length(), plaintext.length());
2817 EXPECT_EQ(message, plaintext);
2818}
2819
2820/*
2821 * EncryptionOperationsTest.AesGcmDifferentNonces
2822 *
2823 * Verifies that encrypting the same data with different nonces produces different outputs.
2824 */
2825TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
2826 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2827 .Authorization(TAG_NO_AUTH_REQUIRED)
2828 .AesEncryptionKey(128)
2829 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2830 .Padding(PaddingMode::NONE)
2831 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2832 .Authorization(TAG_CALLER_NONCE)));
2833
2834 string aad = "foobar";
2835 string message = "123456789012345678901234567890123456";
2836 string nonce1 = "000000000000";
2837 string nonce2 = "111111111111";
2838 string nonce3 = "222222222222";
2839
2840 string ciphertext1 =
2841 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
2842 string ciphertext2 =
2843 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
2844 string ciphertext3 =
2845 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
2846
2847 ASSERT_NE(ciphertext1, ciphertext2);
2848 ASSERT_NE(ciphertext1, ciphertext3);
2849 ASSERT_NE(ciphertext2, ciphertext3);
2850}
2851
2852/*
2853 * EncryptionOperationsTest.AesGcmTooShortTag
2854 *
2855 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
2856 */
2857TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
2858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2859 .Authorization(TAG_NO_AUTH_REQUIRED)
2860 .AesEncryptionKey(128)
2861 .BlockMode(BlockMode::GCM)
2862 .Padding(PaddingMode::NONE)
2863 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2864 string message = "123456789012345678901234567890123456";
2865 auto params = AuthorizationSetBuilder()
2866 .BlockMode(BlockMode::GCM)
2867 .Padding(PaddingMode::NONE)
2868 .Authorization(TAG_MAC_LENGTH, 96);
2869
2870 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
2871}
2872
2873/*
2874 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
2875 *
2876 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
2877 */
2878TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
2879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2880 .Authorization(TAG_NO_AUTH_REQUIRED)
2881 .AesEncryptionKey(128)
2882 .BlockMode(BlockMode::GCM)
2883 .Padding(PaddingMode::NONE)
2884 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2885 string aad = "foobar";
2886 string message = "123456789012345678901234567890123456";
2887 auto params = AuthorizationSetBuilder()
2888 .BlockMode(BlockMode::GCM)
2889 .Padding(PaddingMode::NONE)
2890 .Authorization(TAG_MAC_LENGTH, 128);
2891
2892 auto finish_params =
2893 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2894
2895 // Encrypt
2896 AuthorizationSet begin_out_params;
2897 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
2898 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002899 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07002900
2901 AuthorizationSet finish_out_params;
2902 string ciphertext;
2903 EXPECT_EQ(ErrorCode::OK,
2904 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
2905
2906 params = AuthorizationSetBuilder()
2907 .Authorizations(begin_out_params)
2908 .BlockMode(BlockMode::GCM)
2909 .Padding(PaddingMode::NONE)
2910 .Authorization(TAG_MAC_LENGTH, 96);
2911
2912 // Decrypt.
2913 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
2914}
2915
2916/*
2917 * EncryptionOperationsTest.AesGcmCorruptKey
2918 *
2919 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
2920 */
2921TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
2922 const uint8_t nonce_bytes[] = {
2923 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
2924 };
2925 string nonce = make_string(nonce_bytes);
2926 const uint8_t ciphertext_bytes[] = {
2927 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
2928 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
2929 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
2930 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
2931 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
2932 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
2933 };
2934 string ciphertext = make_string(ciphertext_bytes);
2935
2936 auto params = AuthorizationSetBuilder()
2937 .BlockMode(BlockMode::GCM)
2938 .Padding(PaddingMode::NONE)
2939 .Authorization(TAG_MAC_LENGTH, 128)
2940 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
2941
2942 auto import_params = AuthorizationSetBuilder()
2943 .Authorization(TAG_NO_AUTH_REQUIRED)
2944 .AesEncryptionKey(128)
2945 .BlockMode(BlockMode::GCM)
2946 .Padding(PaddingMode::NONE)
2947 .Authorization(TAG_CALLER_NONCE)
2948 .Authorization(TAG_MIN_MAC_LENGTH, 128);
2949
2950 // Import correct key and decrypt
2951 const uint8_t key_bytes[] = {
2952 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
2953 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
2954 };
2955 string key = make_string(key_bytes);
2956 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
2957 string plaintext = DecryptMessage(ciphertext, params);
2958 CheckedDeleteKey();
2959
2960 // Corrupt key and attempt to decrypt
2961 key[0] = 0;
2962 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
2963 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2964 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
2965 CheckedDeleteKey();
2966}
2967
2968/*
2969 * EncryptionOperationsTest.AesGcmAadNoData
2970 *
2971 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
2972 * encrypt.
2973 */
2974TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
2975 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2976 .Authorization(TAG_NO_AUTH_REQUIRED)
2977 .AesEncryptionKey(128)
2978 .BlockMode(BlockMode::GCM)
2979 .Padding(PaddingMode::NONE)
2980 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2981
2982 string aad = "1234567890123456";
2983 auto params = AuthorizationSetBuilder()
2984 .BlockMode(BlockMode::GCM)
2985 .Padding(PaddingMode::NONE)
2986 .Authorization(TAG_MAC_LENGTH, 128);
2987
2988 auto finish_params =
2989 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2990
2991 // Encrypt
2992 AuthorizationSet begin_out_params;
2993 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
2994 string ciphertext;
2995 AuthorizationSet finish_out_params;
2996 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, "" /* input */, "" /* signature */,
2997 &finish_out_params, &ciphertext));
2998 EXPECT_TRUE(finish_out_params.empty());
2999
3000 // Grab nonce
3001 params.push_back(begin_out_params);
3002
3003 // Decrypt.
3004 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3005 string plaintext;
3006 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, ciphertext, "" /* signature */,
3007 &finish_out_params, &plaintext));
3008
3009 EXPECT_TRUE(finish_out_params.empty());
3010
3011 EXPECT_EQ("", plaintext);
3012}
3013
3014/*
3015 * EncryptionOperationsTest.AesGcmMultiPartAad
3016 *
3017 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
3018 * chunks.
3019 */
3020TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3021 const size_t tag_bits = 128;
3022 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3023 .Authorization(TAG_NO_AUTH_REQUIRED)
3024 .AesEncryptionKey(128)
3025 .BlockMode(BlockMode::GCM)
3026 .Padding(PaddingMode::NONE)
3027 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3028
3029 string message = "123456789012345678901234567890123456";
3030 auto begin_params = AuthorizationSetBuilder()
3031 .BlockMode(BlockMode::GCM)
3032 .Padding(PaddingMode::NONE)
3033 .Authorization(TAG_MAC_LENGTH, tag_bits);
3034 AuthorizationSet begin_out_params;
3035
3036 auto update_params =
3037 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3038
3039 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3040
3041 // No data, AAD only.
3042 string ciphertext;
3043 int32_t input_consumed;
3044 AuthorizationSet update_out_params;
3045 EXPECT_EQ(ErrorCode::OK, Update(update_params, "" /* input */, &update_out_params, &ciphertext,
3046 &input_consumed));
3047 EXPECT_EQ(0U, input_consumed);
3048 EXPECT_EQ(0U, ciphertext.size());
3049 EXPECT_TRUE(update_out_params.empty());
3050
3051 // AAD and data.
3052 EXPECT_EQ(ErrorCode::OK,
3053 Update(update_params, message, &update_out_params, &ciphertext, &input_consumed));
3054 EXPECT_EQ(message.size(), input_consumed);
3055 EXPECT_TRUE(update_out_params.empty());
3056
3057 EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext));
3058 // Expect 128-bit (16-byte) tag appended to ciphertext.
3059 EXPECT_EQ(message.size() + (tag_bits >> 3), ciphertext.size());
3060
3061 // Grab nonce.
3062 begin_params.push_back(begin_out_params);
3063
3064 // Decrypt
3065 update_params =
3066 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6);
3067
3068 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3069 string plaintext;
3070 EXPECT_EQ(ErrorCode::OK, Finish(update_params, ciphertext, "" /* signature */,
3071 &update_out_params, &plaintext));
3072 EXPECT_TRUE(update_out_params.empty());
3073 EXPECT_EQ(message, plaintext);
3074}
3075
3076/*
3077 * EncryptionOperationsTest.AesGcmAadOutOfOrder
3078 *
3079 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3080 */
3081TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3082 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3083 .Authorization(TAG_NO_AUTH_REQUIRED)
3084 .AesEncryptionKey(128)
3085 .BlockMode(BlockMode::GCM)
3086 .Padding(PaddingMode::NONE)
3087 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3088
3089 string message = "123456789012345678901234567890123456";
3090 auto begin_params = AuthorizationSetBuilder()
3091 .BlockMode(BlockMode::GCM)
3092 .Padding(PaddingMode::NONE)
3093 .Authorization(TAG_MAC_LENGTH, 128);
3094 AuthorizationSet begin_out_params;
3095
3096 auto update_params =
3097 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3098
3099 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3100
3101 // No data, AAD only.
3102 string ciphertext;
3103 int32_t input_consumed;
3104 AuthorizationSet update_out_params;
3105 EXPECT_EQ(ErrorCode::OK, Update(update_params, "" /* input */, &update_out_params, &ciphertext,
3106 &input_consumed));
3107 EXPECT_EQ(0U, input_consumed);
3108 EXPECT_EQ(0U, ciphertext.size());
3109 EXPECT_TRUE(update_out_params.empty());
3110
3111 // AAD and data.
3112 EXPECT_EQ(ErrorCode::OK,
3113 Update(update_params, message, &update_out_params, &ciphertext, &input_consumed));
3114 EXPECT_EQ(message.size(), input_consumed);
3115 EXPECT_TRUE(update_out_params.empty());
3116
3117 // More AAD
3118 EXPECT_EQ(ErrorCode::INVALID_TAG,
3119 Update(update_params, "", &update_out_params, &ciphertext, &input_consumed));
3120
Janis Danisevskis24c04702020-12-16 18:28:39 -08003121 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003122}
3123
3124/*
3125 * EncryptionOperationsTest.AesGcmBadAad
3126 *
3127 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3128 */
3129TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3130 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3131 .Authorization(TAG_NO_AUTH_REQUIRED)
3132 .AesEncryptionKey(128)
3133 .BlockMode(BlockMode::GCM)
3134 .Padding(PaddingMode::NONE)
3135 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3136
3137 string message = "12345678901234567890123456789012";
3138 auto begin_params = AuthorizationSetBuilder()
3139 .BlockMode(BlockMode::GCM)
3140 .Padding(PaddingMode::NONE)
3141 .Authorization(TAG_MAC_LENGTH, 128);
3142
3143 auto finish_params =
3144 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3145
3146 // Encrypt
3147 AuthorizationSet begin_out_params;
3148 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3149 string ciphertext;
3150 AuthorizationSet finish_out_params;
3151 EXPECT_EQ(ErrorCode::OK,
3152 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3153
3154 // Grab nonce
3155 begin_params.push_back(begin_out_params);
3156
3157 finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA,
3158 "barfoo" /* Wrong AAD */, (size_t)6);
3159
3160 // Decrypt.
3161 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3162 string plaintext;
3163 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(finish_params, ciphertext, "" /* signature */,
3164 &finish_out_params, &plaintext));
3165}
3166
3167/*
3168 * EncryptionOperationsTest.AesGcmWrongNonce
3169 *
3170 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3171 */
3172TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3173 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3174 .Authorization(TAG_NO_AUTH_REQUIRED)
3175 .AesEncryptionKey(128)
3176 .BlockMode(BlockMode::GCM)
3177 .Padding(PaddingMode::NONE)
3178 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3179
3180 string message = "12345678901234567890123456789012";
3181 auto begin_params = AuthorizationSetBuilder()
3182 .BlockMode(BlockMode::GCM)
3183 .Padding(PaddingMode::NONE)
3184 .Authorization(TAG_MAC_LENGTH, 128);
3185
3186 auto finish_params =
3187 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3188
3189 // Encrypt
3190 AuthorizationSet begin_out_params;
3191 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3192 string ciphertext;
3193 AuthorizationSet finish_out_params;
3194 EXPECT_EQ(ErrorCode::OK,
3195 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3196
3197 // Wrong nonce
3198 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
3199
3200 // Decrypt.
3201 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3202 string plaintext;
3203 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(finish_params, ciphertext, "" /* signature */,
3204 &finish_out_params, &plaintext));
3205
3206 // With wrong nonce, should have gotten garbage plaintext (or none).
3207 EXPECT_NE(message, plaintext);
3208}
3209
3210/*
3211 * EncryptionOperationsTest.AesGcmCorruptTag
3212 *
3213 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3214 */
3215TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3216 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3217 .Authorization(TAG_NO_AUTH_REQUIRED)
3218 .AesEncryptionKey(128)
3219 .BlockMode(BlockMode::GCM)
3220 .Padding(PaddingMode::NONE)
3221 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3222
3223 string aad = "1234567890123456";
3224 string message = "123456789012345678901234567890123456";
3225
3226 auto params = AuthorizationSetBuilder()
3227 .BlockMode(BlockMode::GCM)
3228 .Padding(PaddingMode::NONE)
3229 .Authorization(TAG_MAC_LENGTH, 128);
3230
3231 auto finish_params =
3232 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3233
3234 // Encrypt
3235 AuthorizationSet begin_out_params;
3236 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3237 string ciphertext;
3238 AuthorizationSet finish_out_params;
3239 EXPECT_EQ(ErrorCode::OK,
3240 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3241 EXPECT_TRUE(finish_out_params.empty());
3242
3243 // Corrupt tag
3244 ++(*ciphertext.rbegin());
3245
3246 // Grab nonce
3247 params.push_back(begin_out_params);
3248
3249 // Decrypt.
3250 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3251 string plaintext;
3252 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(finish_params, ciphertext, "" /* signature */,
3253 &finish_out_params, &plaintext));
3254 EXPECT_TRUE(finish_out_params.empty());
3255}
3256
3257/*
3258 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
3259 *
3260 * Verifies that 3DES is basically functional.
3261 */
3262TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
3263 auto auths = AuthorizationSetBuilder()
3264 .TripleDesEncryptionKey(168)
3265 .BlockMode(BlockMode::ECB)
3266 .Authorization(TAG_NO_AUTH_REQUIRED)
3267 .Padding(PaddingMode::NONE);
3268
3269 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
3270 // Two-block message.
3271 string message = "1234567890123456";
3272 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3273 string ciphertext1 = EncryptMessage(message, inParams);
3274 EXPECT_EQ(message.size(), ciphertext1.size());
3275
3276 string ciphertext2 = EncryptMessage(string(message), inParams);
3277 EXPECT_EQ(message.size(), ciphertext2.size());
3278
3279 // ECB is deterministic.
3280 EXPECT_EQ(ciphertext1, ciphertext2);
3281
3282 string plaintext = DecryptMessage(ciphertext1, inParams);
3283 EXPECT_EQ(message, plaintext);
3284}
3285
3286/*
3287 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
3288 *
3289 * Verifies that CBC keys reject ECB usage.
3290 */
3291TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
3292 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3293 .TripleDesEncryptionKey(168)
3294 .BlockMode(BlockMode::CBC)
3295 .Authorization(TAG_NO_AUTH_REQUIRED)
3296 .Padding(PaddingMode::NONE)));
3297
3298 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3299 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3300}
3301
3302/*
3303 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
3304 *
3305 * Tests ECB mode with PKCS#7 padding, various message sizes.
3306 */
3307TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
3308 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3309 .TripleDesEncryptionKey(168)
3310 .BlockMode(BlockMode::ECB)
3311 .Authorization(TAG_NO_AUTH_REQUIRED)
3312 .Padding(PaddingMode::PKCS7)));
3313
3314 for (size_t i = 0; i < 32; ++i) {
3315 string message(i, 'a');
3316 auto inParams =
3317 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3318 string ciphertext = EncryptMessage(message, inParams);
3319 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3320 string plaintext = DecryptMessage(ciphertext, inParams);
3321 EXPECT_EQ(message, plaintext);
3322 }
3323}
3324
3325/*
3326 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
3327 *
3328 * Verifies that keys configured for no padding reject PKCS7 padding
3329 */
3330TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
3331 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3332 .TripleDesEncryptionKey(168)
3333 .BlockMode(BlockMode::ECB)
3334 .Authorization(TAG_NO_AUTH_REQUIRED)
3335 .Padding(PaddingMode::NONE)));
3336 for (size_t i = 0; i < 32; ++i) {
3337 auto inParams =
3338 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3339 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3340 }
3341}
3342
3343/*
3344 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
3345 *
3346 * Verifies that corrupted padding is detected.
3347 */
3348TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
3349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3350 .TripleDesEncryptionKey(168)
3351 .BlockMode(BlockMode::ECB)
3352 .Authorization(TAG_NO_AUTH_REQUIRED)
3353 .Padding(PaddingMode::PKCS7)));
3354
3355 string message = "a";
3356 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
3357 EXPECT_EQ(8U, ciphertext.size());
3358 EXPECT_NE(ciphertext, message);
3359 ++ciphertext[ciphertext.size() / 2];
3360
3361 AuthorizationSetBuilder begin_params;
3362 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
3363 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
3364 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3365 string plaintext;
3366 int32_t input_consumed;
3367 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext, &input_consumed));
3368 EXPECT_EQ(ciphertext.size(), input_consumed);
3369 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
3370}
3371
3372struct TripleDesTestVector {
3373 const char* name;
3374 const KeyPurpose purpose;
3375 const BlockMode block_mode;
3376 const PaddingMode padding_mode;
3377 const char* key;
3378 const char* iv;
3379 const char* input;
3380 const char* output;
3381};
3382
3383// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
3384// of the NIST vectors are multiples of the block size.
3385static const TripleDesTestVector kTripleDesTestVectors[] = {
3386 {
3387 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3388 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
3389 "", // IV
3390 "329d86bdf1bc5af4", // input
3391 "d946c2756d78633f", // output
3392 },
3393 {
3394 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3395 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
3396 "", // IV
3397 "6b1540781b01ce1997adae102dbf3c5b", // input
3398 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
3399 },
3400 {
3401 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3402 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
3403 "", // IV
3404 "6daad94ce08acfe7", // input
3405 "660e7d32dcc90e79", // output
3406 },
3407 {
3408 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3409 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
3410 "", // IV
3411 "e9653a0a1f05d31b9acd12d73aa9879d", // input
3412 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
3413 },
3414 {
3415 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3416 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
3417 "43f791134c5647ba", // IV
3418 "dcc153cef81d6f24", // input
3419 "92538bd8af18d3ba", // output
3420 },
3421 {
3422 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3423 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3424 "c2e999cb6249023c", // IV
3425 "c689aee38a301bb316da75db36f110b5", // input
3426 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
3427 },
3428 {
3429 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
3430 PaddingMode::PKCS7,
3431 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3432 "c2e999cb6249023c", // IV
3433 "c689aee38a301bb316da75db36f110b500", // input
3434 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
3435 },
3436 {
3437 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
3438 PaddingMode::PKCS7,
3439 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3440 "c2e999cb6249023c", // IV
3441 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
3442 "c689aee38a301bb316da75db36f110b500", // output
3443 },
3444 {
3445 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3446 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
3447 "41746c7e442d3681", // IV
3448 "c53a7b0ec40600fe", // input
3449 "d4f00eb455de1034", // output
3450 },
3451 {
3452 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3453 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
3454 "3982bc02c3727d45", // IV
3455 "6006f10adef52991fcc777a1238bbb65", // input
3456 "edae09288e9e3bc05746d872b48e3b29", // output
3457 },
3458};
3459
3460/*
3461 * EncryptionOperationsTest.TripleDesTestVector
3462 *
3463 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
3464 */
3465TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
3466 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
3467 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
3468 SCOPED_TRACE(test->name);
3469 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
3470 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
3471 hex2str(test->output));
3472 }
3473}
3474
3475/*
3476 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
3477 *
3478 * Validates CBC mode functionality.
3479 */
3480TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
3481 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3482 .TripleDesEncryptionKey(168)
3483 .BlockMode(BlockMode::CBC)
3484 .Authorization(TAG_NO_AUTH_REQUIRED)
3485 .Padding(PaddingMode::NONE)));
3486
3487 ASSERT_GT(key_blob_.size(), 0U);
3488
3489 // Two-block message.
3490 string message = "1234567890123456";
3491 vector<uint8_t> iv1;
3492 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
3493 EXPECT_EQ(message.size(), ciphertext1.size());
3494
3495 vector<uint8_t> iv2;
3496 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
3497 EXPECT_EQ(message.size(), ciphertext2.size());
3498
3499 // IVs should be random, so ciphertexts should differ.
3500 EXPECT_NE(iv1, iv2);
3501 EXPECT_NE(ciphertext1, ciphertext2);
3502
3503 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
3504 EXPECT_EQ(message, plaintext);
3505}
3506
3507/*
3508 * EncryptionOperationsTest.TripleDesCallerIv
3509 *
3510 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
3511 */
3512TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
3513 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3514 .TripleDesEncryptionKey(168)
3515 .BlockMode(BlockMode::CBC)
3516 .Authorization(TAG_NO_AUTH_REQUIRED)
3517 .Authorization(TAG_CALLER_NONCE)
3518 .Padding(PaddingMode::NONE)));
3519 string message = "1234567890123456";
3520 vector<uint8_t> iv;
3521 // Don't specify IV, should get a random one.
3522 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
3523 EXPECT_EQ(message.size(), ciphertext1.size());
3524 EXPECT_EQ(8U, iv.size());
3525
3526 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
3527 EXPECT_EQ(message, plaintext);
3528
3529 // Now specify an IV, should also work.
3530 iv = AidlBuf("abcdefgh");
3531 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
3532
3533 // Decrypt with correct IV.
3534 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
3535 EXPECT_EQ(message, plaintext);
3536
3537 // Now try with wrong IV.
3538 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
3539 EXPECT_NE(message, plaintext);
3540}
3541
3542/*
3543 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
3544 *
3545 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
3546 */
3547TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
3548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3549 .TripleDesEncryptionKey(168)
3550 .BlockMode(BlockMode::CBC)
3551 .Authorization(TAG_NO_AUTH_REQUIRED)
3552 .Padding(PaddingMode::NONE)));
3553
3554 string message = "12345678901234567890123456789012";
3555 vector<uint8_t> iv;
3556 // Don't specify nonce, should get a random one.
3557 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
3558 EXPECT_EQ(message.size(), ciphertext1.size());
3559 EXPECT_EQ(8U, iv.size());
3560
3561 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
3562 EXPECT_EQ(message, plaintext);
3563
3564 // Now specify a nonce, should fail.
3565 auto input_params = AuthorizationSetBuilder()
3566 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
3567 .BlockMode(BlockMode::CBC)
3568 .Padding(PaddingMode::NONE);
3569 AuthorizationSet output_params;
3570 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
3571 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
3572}
3573
3574/*
3575 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
3576 *
3577 * Verifies that 3DES ECB-only keys do not allow CBC usage.
3578 */
3579TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
3580 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3581 .TripleDesEncryptionKey(168)
3582 .BlockMode(BlockMode::ECB)
3583 .Authorization(TAG_NO_AUTH_REQUIRED)
3584 .Padding(PaddingMode::NONE)));
3585 // Two-block message.
3586 string message = "1234567890123456";
3587 auto begin_params =
3588 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3589 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
3590}
3591
3592/*
3593 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
3594 *
3595 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
3596 */
3597TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
3598 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3599 .TripleDesEncryptionKey(168)
3600 .BlockMode(BlockMode::CBC)
3601 .Authorization(TAG_NO_AUTH_REQUIRED)
3602 .Padding(PaddingMode::NONE)));
3603 // Message is slightly shorter than two blocks.
3604 string message = "123456789012345";
3605
3606 auto begin_params =
3607 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3608 AuthorizationSet output_params;
3609 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
3610 string ciphertext;
3611 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
3612}
3613
3614/*
3615 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
3616 *
3617 * Verifies that PKCS7 padding works correctly in CBC mode.
3618 */
3619TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
3620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3621 .TripleDesEncryptionKey(168)
3622 .BlockMode(BlockMode::CBC)
3623 .Authorization(TAG_NO_AUTH_REQUIRED)
3624 .Padding(PaddingMode::PKCS7)));
3625
3626 // Try various message lengths; all should work.
3627 for (size_t i = 0; i < 32; ++i) {
3628 string message(i, 'a');
3629 vector<uint8_t> iv;
3630 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
3631 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3632 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
3633 EXPECT_EQ(message, plaintext);
3634 }
3635}
3636
3637/*
3638 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
3639 *
3640 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
3641 */
3642TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
3643 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3644 .TripleDesEncryptionKey(168)
3645 .BlockMode(BlockMode::CBC)
3646 .Authorization(TAG_NO_AUTH_REQUIRED)
3647 .Padding(PaddingMode::NONE)));
3648
3649 // Try various message lengths; all should fail.
3650 for (size_t i = 0; i < 32; ++i) {
3651 auto begin_params =
3652 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
3653 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
3654 }
3655}
3656
3657/*
3658 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
3659 *
3660 * Verifies that corrupted PKCS7 padding is rejected during decryption.
3661 */
3662TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
3663 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3664 .TripleDesEncryptionKey(168)
3665 .BlockMode(BlockMode::CBC)
3666 .Authorization(TAG_NO_AUTH_REQUIRED)
3667 .Padding(PaddingMode::PKCS7)));
3668
3669 string message = "a";
3670 vector<uint8_t> iv;
3671 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
3672 EXPECT_EQ(8U, ciphertext.size());
3673 EXPECT_NE(ciphertext, message);
3674 ++ciphertext[ciphertext.size() / 2];
3675
3676 auto begin_params = AuthorizationSetBuilder()
3677 .BlockMode(BlockMode::CBC)
3678 .Padding(PaddingMode::PKCS7)
3679 .Authorization(TAG_NONCE, iv);
3680 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3681 string plaintext;
3682 int32_t input_consumed;
3683 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext, &input_consumed));
3684 EXPECT_EQ(ciphertext.size(), input_consumed);
3685 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
3686}
3687
3688/*
3689 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
3690 *
3691 * Verifies that 3DES CBC works with many different input sizes.
3692 */
3693TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
3694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3695 .TripleDesEncryptionKey(168)
3696 .BlockMode(BlockMode::CBC)
3697 .Authorization(TAG_NO_AUTH_REQUIRED)
3698 .Padding(PaddingMode::NONE)));
3699
3700 int increment = 7;
3701 string message(240, 'a');
3702 AuthorizationSet input_params =
3703 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3704 AuthorizationSet output_params;
3705 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
3706
3707 string ciphertext;
3708 int32_t input_consumed;
3709 for (size_t i = 0; i < message.size(); i += increment)
3710 EXPECT_EQ(ErrorCode::OK,
3711 Update(message.substr(i, increment), &ciphertext, &input_consumed));
3712 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
3713 EXPECT_EQ(message.size(), ciphertext.size());
3714
3715 // Move TAG_NONCE into input_params
3716 input_params = output_params;
3717 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
3718 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
3719 output_params.Clear();
3720
3721 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
3722 string plaintext;
3723 for (size_t i = 0; i < ciphertext.size(); i += increment)
3724 EXPECT_EQ(ErrorCode::OK,
3725 Update(ciphertext.substr(i, increment), &plaintext, &input_consumed));
3726 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
3727 EXPECT_EQ(ciphertext.size(), plaintext.size());
3728 EXPECT_EQ(message, plaintext);
3729}
3730
3731INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
3732
3733typedef KeyMintAidlTestBase MaxOperationsTest;
3734
3735/*
3736 * MaxOperationsTest.TestLimitAes
3737 *
3738 * Verifies that the max uses per boot tag works correctly with AES keys.
3739 */
3740TEST_P(MaxOperationsTest, TestLimitAes) {
3741 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3742
3743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3744 .Authorization(TAG_NO_AUTH_REQUIRED)
3745 .AesEncryptionKey(128)
3746 .EcbMode()
3747 .Padding(PaddingMode::NONE)
3748 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3749
3750 string message = "1234567890123456";
3751
3752 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
3753
3754 EncryptMessage(message, params);
3755 EncryptMessage(message, params);
3756 EncryptMessage(message, params);
3757
3758 // Fourth time should fail.
3759 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
3760}
3761
3762/*
3763 * MaxOperationsTest.TestLimitAes
3764 *
3765 * Verifies that the max uses per boot tag works correctly with RSA keys.
3766 */
3767TEST_P(MaxOperationsTest, TestLimitRsa) {
3768 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3769
3770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3771 .Authorization(TAG_NO_AUTH_REQUIRED)
3772 .RsaSigningKey(1024, 65537)
3773 .NoDigestOrPadding()
3774 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3775
3776 string message = "1234567890123456";
3777
3778 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
3779
3780 SignMessage(message, params);
3781 SignMessage(message, params);
3782 SignMessage(message, params);
3783
3784 // Fourth time should fail.
3785 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
3786}
3787
3788INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
3789
3790typedef KeyMintAidlTestBase AddEntropyTest;
3791
3792/*
3793 * AddEntropyTest.AddEntropy
3794 *
3795 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
3796 * is actually added.
3797 */
3798TEST_P(AddEntropyTest, AddEntropy) {
3799 string data = "foo";
3800 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
3801}
3802
3803/*
3804 * AddEntropyTest.AddEmptyEntropy
3805 *
3806 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
3807 */
3808TEST_P(AddEntropyTest, AddEmptyEntropy) {
3809 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
3810}
3811
3812/*
3813 * AddEntropyTest.AddLargeEntropy
3814 *
3815 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
3816 */
3817TEST_P(AddEntropyTest, AddLargeEntropy) {
3818 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
3819}
3820
3821INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
3822
3823typedef KeyMintAidlTestBase AttestationTest;
3824
3825/*
3826 * AttestationTest.RsaAttestation
3827 *
3828 * Verifies that attesting to RSA keys works and generates the expected output.
3829 */
3830// TODO(seleneh) add attestation tests back after decided on the new attestation
3831// behavior under generateKey and importKey
3832
3833typedef KeyMintAidlTestBase KeyDeletionTest;
3834
3835/**
3836 * KeyDeletionTest.DeleteKey
3837 *
3838 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
3839 * valid key blob.
3840 */
3841TEST_P(KeyDeletionTest, DeleteKey) {
3842 auto error = GenerateKey(AuthorizationSetBuilder()
3843 .RsaSigningKey(2048, 65537)
3844 .Digest(Digest::NONE)
3845 .Padding(PaddingMode::NONE)
3846 .Authorization(TAG_NO_AUTH_REQUIRED)
3847 .Authorization(TAG_ROLLBACK_RESISTANCE));
3848 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
3849
3850 // Delete must work if rollback protection is implemented
3851 if (error == ErrorCode::OK) {
3852 AuthorizationSet hardwareEnforced(key_characteristics_.hardwareEnforced);
3853 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
3854
3855 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
3856
3857 string message = "12345678901234567890123456789012";
3858 AuthorizationSet begin_out_params;
3859 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3860 Begin(KeyPurpose::SIGN, key_blob_,
3861 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
3862 &begin_out_params));
3863 AbortIfNeeded();
3864 key_blob_ = AidlBuf();
3865 }
3866}
3867
3868/**
3869 * KeyDeletionTest.DeleteInvalidKey
3870 *
3871 * This test checks that the HAL excepts invalid key blobs..
3872 */
3873TEST_P(KeyDeletionTest, DeleteInvalidKey) {
3874 // Generate key just to check if rollback protection is implemented
3875 auto error = GenerateKey(AuthorizationSetBuilder()
3876 .RsaSigningKey(2048, 65537)
3877 .Digest(Digest::NONE)
3878 .Padding(PaddingMode::NONE)
3879 .Authorization(TAG_NO_AUTH_REQUIRED)
3880 .Authorization(TAG_ROLLBACK_RESISTANCE));
3881 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
3882
3883 // Delete must work if rollback protection is implemented
3884 if (error == ErrorCode::OK) {
3885 AuthorizationSet hardwareEnforced(key_characteristics_.hardwareEnforced);
3886 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
3887
3888 // Delete the key we don't care about the result at this point.
3889 DeleteKey();
3890
3891 // Now create an invalid key blob and delete it.
3892 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
3893
3894 ASSERT_EQ(ErrorCode::OK, DeleteKey());
3895 }
3896}
3897
3898/**
3899 * KeyDeletionTest.DeleteAllKeys
3900 *
3901 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
3902 *
3903 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
3904 * FBE/FDE encryption keys, which means that the device will not even boot until after the
3905 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
3906 * been provisioned. Use this test only on dedicated testing devices that have no valuable
3907 * credentials stored in Keystore/Keymint.
3908 */
3909TEST_P(KeyDeletionTest, DeleteAllKeys) {
3910 if (!arm_deleteAllKeys) return;
3911 auto error = GenerateKey(AuthorizationSetBuilder()
3912 .RsaSigningKey(2048, 65537)
3913 .Digest(Digest::NONE)
3914 .Padding(PaddingMode::NONE)
3915 .Authorization(TAG_NO_AUTH_REQUIRED)
3916 .Authorization(TAG_ROLLBACK_RESISTANCE));
3917 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
3918
3919 // Delete must work if rollback protection is implemented
3920 if (error == ErrorCode::OK) {
3921 AuthorizationSet hardwareEnforced(key_characteristics_.hardwareEnforced);
3922 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
3923
3924 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
3925
3926 string message = "12345678901234567890123456789012";
3927 AuthorizationSet begin_out_params;
3928
3929 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3930 Begin(KeyPurpose::SIGN, key_blob_,
3931 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
3932 &begin_out_params));
3933 AbortIfNeeded();
3934 key_blob_ = AidlBuf();
3935 }
3936}
3937
3938INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
3939
3940using UpgradeKeyTest = KeyMintAidlTestBase;
3941
3942/*
3943 * UpgradeKeyTest.UpgradeKey
3944 *
3945 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
3946 */
3947TEST_P(UpgradeKeyTest, UpgradeKey) {
3948 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3949 .AesEncryptionKey(128)
3950 .Padding(PaddingMode::NONE)
3951 .Authorization(TAG_NO_AUTH_REQUIRED)));
3952
3953 auto result = UpgradeKey(key_blob_);
3954
3955 // Key doesn't need upgrading. Should get okay, but no new key blob.
3956 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
3957}
3958
3959INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
3960
3961using ClearOperationsTest = KeyMintAidlTestBase;
3962
3963/*
3964 * ClearSlotsTest.TooManyOperations
3965 *
3966 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
3967 * operations are started without being finished or aborted. Also verifies
3968 * that aborting the operations clears the operations.
3969 *
3970 */
3971TEST_P(ClearOperationsTest, TooManyOperations) {
3972 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3973 .Authorization(TAG_NO_AUTH_REQUIRED)
3974 .RsaEncryptionKey(2048, 65537)
3975 .Padding(PaddingMode::NONE)));
3976
3977 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3978 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08003979 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07003980 AuthorizationSet out_params;
3981 ErrorCode result;
3982 size_t i;
3983
3984 for (i = 0; i < max_operations; i++) {
3985 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
3986 if (ErrorCode::OK != result) {
3987 break;
3988 }
3989 }
3990 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
3991 // Try again just in case there's a weird overflow bug
3992 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
3993 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
3994 for (size_t j = 0; j < i; j++) {
3995 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
3996 << "Aboort failed for i = " << j << std::endl;
3997 }
3998 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
3999 AbortIfNeeded();
4000}
4001
4002INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
4003
4004typedef KeyMintAidlTestBase TransportLimitTest;
4005
4006/*
4007 * TransportLimitTest.FinishInput
4008 *
4009 * Verifies that passing input data to finish succeeds as expected.
4010 */
4011TEST_P(TransportLimitTest, LargeFinishInput) {
4012 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4013 .Authorization(TAG_NO_AUTH_REQUIRED)
4014 .AesEncryptionKey(128)
4015 .BlockMode(BlockMode::ECB)
4016 .Padding(PaddingMode::NONE)));
4017
4018 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
4019 auto cipher_params =
4020 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4021
4022 AuthorizationSet out_params;
4023 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
4024
4025 string plain_message = std::string(1 << msg_size, 'x');
4026 string encrypted_message;
4027 auto rc = Finish(plain_message, &encrypted_message);
4028
4029 EXPECT_EQ(ErrorCode::OK, rc);
4030 EXPECT_EQ(plain_message.size(), encrypted_message.size())
4031 << "Encrypt finish returned OK, but did not consume all of the given input";
4032 cipher_params.push_back(out_params);
4033
4034 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
4035
4036 string decrypted_message;
4037 rc = Finish(encrypted_message, &decrypted_message);
4038 EXPECT_EQ(ErrorCode::OK, rc);
4039 EXPECT_EQ(plain_message.size(), decrypted_message.size())
4040 << "Decrypt finish returned OK, did not consume all of the given input";
4041 }
4042}
4043
4044INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
4045
Janis Danisevskis24c04702020-12-16 18:28:39 -08004046} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07004047
4048int main(int argc, char** argv) {
4049 ::testing::InitGoogleTest(&argc, argv);
4050 for (int i = 1; i < argc; ++i) {
4051 if (argv[i][0] == '-') {
4052 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
4053 arm_deleteAllKeys = true;
4054 }
4055 if (std::string(argv[i]) == "--dump_attestations") {
4056 dump_Attestations = true;
4057 }
4058 }
4059 }
Shawn Willden08a7e432020-12-11 13:05:27 +00004060 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07004061}