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