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