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