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