blob: 71aae90f30728b495414d485890c05cb05705b0d [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
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
21#include <iostream>
22
David Zeuthene0c40892021-01-08 12:54:11 -050023#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070024#include <openssl/evp.h>
25#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027
28#include <cutils/properties.h>
29
Janis Danisevskis24c04702020-12-16 18:28:39 -080030#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070031
Shawn Willden08a7e432020-12-11 13:05:27 +000032#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
Janis Danisevskis24c04702020-12-16 18:28:39 -080037using aidl::android::hardware::security::keymint::AuthorizationSet;
38using aidl::android::hardware::security::keymint::KeyCharacteristics;
39using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070040
Selene Huang31ab4042020-04-29 04:22:39 -070041namespace std {
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070044
45template <>
46struct std::equal_to<KeyCharacteristics> {
47 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070048 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070049
Shawn Willden7f424372021-01-10 18:06:50 -070050 // this isn't very efficient. Oh, well.
51 AuthorizationSet a_auths(a.authorizations);
52 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070053
Shawn Willden7f424372021-01-10 18:06:50 -070054 a_auths.Sort();
55 b_auths.Sort();
56
57 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070058 }
59};
60
61} // namespace std
62
Janis Danisevskis24c04702020-12-16 18:28:39 -080063namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000064
Selene Huang31ab4042020-04-29 04:22:39 -070065namespace {
66
67template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000068bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
69 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070070 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080071 if (auto p = authorizationValue(ttag, param)) {
72 return *p == expected_value;
73 }
74 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070075 });
76 return (it != set.end());
77}
78
79template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000080bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070081 auto it = std::find_if(set.begin(), set.end(),
82 [&](const KeyParameter& param) { return param.tag == tag; });
83 return (it != set.end());
84}
85
86constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
87 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
88 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
89 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
90 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
91 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
92 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
93 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
96 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
97 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
102
103string hex2str(string a) {
104 string b;
105 size_t num = a.size() / 2;
106 b.resize(num);
107 for (size_t i = 0; i < num; i++) {
108 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
109 }
110 return b;
111}
112
113string rsa_key =
114 hex2str("30820275020100300d06092a864886f70d01010105000482025f3082025b"
115 "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
116 "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
117 "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
118 "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
119 "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
120 "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
121 "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
122 "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
123 "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
124 "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
125 "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
126 "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
127 "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
128 "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
129 "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
130 "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
131 "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
132 "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
133 "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
134 "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
135 "3492d6");
136
137string ec_256_key =
138 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
139 "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
140 "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
141 "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
142 "1c6eb00083cf3376d11fd44949e0b2183bfe");
143
144string ec_521_key =
145 hex2str("3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
146 "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
147 "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
148 "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
149 "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
150 "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
151 "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
152 "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
153 "D9");
154
155string ec_256_key_rfc5915 =
156 hex2str("308193020100301306072a8648ce3d020106082a8648ce3d030107047930"
157 "770201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
158 "8e8d21c9fa750c1da00a06082a8648ce3d030107a14403420004e2cc561e"
159 "e701da0ad0ef0d176bb0c919d42e79c393fdc1bd6c4010d85cf2cf8e68c9"
160 "05464666f98dad4f01573ba81078b3428570a439ba3229fbc026c550682f");
161
162string ec_256_key_sec1 =
163 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
164 "6b0201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
165 "8e8d21c9fa750c1da14403420004e2cc561ee701da0ad0ef0d176bb0c919"
166 "d42e79c393fdc1bd6c4010d85cf2cf8e68c905464666f98dad4f01573ba8"
167 "1078b3428570a439ba3229fbc026c550682f");
168
169struct RSA_Delete {
170 void operator()(RSA* p) { RSA_free(p); }
171};
172
Selene Huang31ab4042020-04-29 04:22:39 -0700173std::string make_string(const uint8_t* data, size_t length) {
174 return std::string(reinterpret_cast<const char*>(data), length);
175}
176
177template <size_t N>
178std::string make_string(const uint8_t (&a)[N]) {
179 return make_string(a, N);
180}
181
182class AidlBuf : public vector<uint8_t> {
183 typedef vector<uint8_t> super;
184
185 public:
186 AidlBuf() {}
187 AidlBuf(const super& other) : super(other) {}
188 AidlBuf(super&& other) : super(std::move(other)) {}
189 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
190
191 AidlBuf& operator=(const super& other) {
192 super::operator=(other);
193 return *this;
194 }
195
196 AidlBuf& operator=(super&& other) {
197 super::operator=(std::move(other));
198 return *this;
199 }
200
201 AidlBuf& operator=(const string& other) {
202 resize(other.size());
203 for (size_t i = 0; i < other.size(); ++i) {
204 (*this)[i] = static_cast<uint8_t>(other[i]);
205 }
206 return *this;
207 }
208
209 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
210};
211
212} // namespace
213
214class NewKeyGenerationTest : public KeyMintAidlTestBase {
215 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700216 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700217 // TODO(swillden): Distinguish which params should be in which auth list.
218
Shawn Willden7f424372021-01-10 18:06:50 -0700219 AuthorizationSet auths;
220 for (auto& entry : keyCharacteristics) {
221 auths.push_back(AuthorizationSet(entry.authorizations));
222 }
Selene Huang31ab4042020-04-29 04:22:39 -0700223
224 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
225 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
226 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
227
Shawn Willden7f424372021-01-10 18:06:50 -0700228 // Verify that App data and ROT are NOT included.
Selene Huang31ab4042020-04-29 04:22:39 -0700229 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
Selene Huang31ab4042020-04-29 04:22:39 -0700230 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
231
232 // Check that some unexpected tags/values are NOT present.
233 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
234 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
235 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
236
Shawn Willden7f424372021-01-10 18:06:50 -0700237 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
238 ASSERT_TRUE(os_ver);
239 EXPECT_EQ(*os_ver, os_version());
Selene Huang31ab4042020-04-29 04:22:39 -0700240
Shawn Willden7f424372021-01-10 18:06:50 -0700241 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
242 ASSERT_TRUE(os_pl);
243 EXPECT_EQ(*os_pl, os_patch_level());
Selene Huang31ab4042020-04-29 04:22:39 -0700244 }
245};
246
247/*
248 * NewKeyGenerationTest.Rsa
249 *
250 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
251 * have correct characteristics.
252 */
253TEST_P(NewKeyGenerationTest, Rsa) {
254 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
255 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700256 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700257 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
258 .RsaSigningKey(key_size, 65537)
259 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800260 .Padding(PaddingMode::NONE)
261 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700262 &key_blob, &key_characteristics));
263
264 ASSERT_GT(key_blob.size(), 0U);
265 CheckBaseParams(key_characteristics);
266
Shawn Willden7f424372021-01-10 18:06:50 -0700267 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700268
269 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
270 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
271 << "Key size " << key_size << "missing";
272 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
273
274 CheckedDeleteKey(&key_blob);
275 }
276}
277
278/*
Qi Wud22ec842020-11-26 13:27:53 +0800279 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700280 *
281 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
282 * have correct characteristics.
283 */
284TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
285 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
286 auto challenge = "hello";
287 auto app_id = "foo";
288
289 vector<uint8_t> key_blob;
290 vector<KeyCharacteristics> key_characteristics;
291 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
292 .RsaSigningKey(key_size, 65537)
293 .Digest(Digest::NONE)
294 .Padding(PaddingMode::NONE)
295 .AttestationChallenge(challenge)
296 .AttestationApplicationId(app_id)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800297 .Authorization(TAG_NO_AUTH_REQUIRED)
298 .SetDefaultValidity(),
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700299 &key_blob, &key_characteristics));
300
301 ASSERT_GT(key_blob.size(), 0U);
302 CheckBaseParams(key_characteristics);
303
304 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
305
306 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
307 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
308 << "Key size " << key_size << "missing";
309 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
310
Shawn Willden7c130392020-12-21 09:58:22 -0700311 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700312 ASSERT_GT(cert_chain_.size(), 0);
313
314 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
315 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
316 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
317 sw_enforced, hw_enforced, SecLevel(),
318 cert_chain_[0].encodedCertificate));
319
320 CheckedDeleteKey(&key_blob);
321 }
322}
323
324/*
Qi Wud22ec842020-11-26 13:27:53 +0800325 * NewKeyGenerationTest.LimitedUsageRsa
326 *
327 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
328 * resulting keys have correct characteristics.
329 */
330TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
331 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
332 vector<uint8_t> key_blob;
333 vector<KeyCharacteristics> key_characteristics;
334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
335 .RsaSigningKey(key_size, 65537)
336 .Digest(Digest::NONE)
337 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800338 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
339 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800340 &key_blob, &key_characteristics));
341
342 ASSERT_GT(key_blob.size(), 0U);
343 CheckBaseParams(key_characteristics);
344
345 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
346
347 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
348 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
349 << "Key size " << key_size << "missing";
350 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
351
352 // Check the usage count limit tag appears in the authorizations.
353 AuthorizationSet auths;
354 for (auto& entry : key_characteristics) {
355 auths.push_back(AuthorizationSet(entry.authorizations));
356 }
357 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
358 << "key usage count limit " << 1U << " missing";
359
360 CheckedDeleteKey(&key_blob);
361 }
362}
363
364/*
Qi Wubeefae42021-01-28 23:16:37 +0800365 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
366 *
367 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
368 * resulting keys have correct characteristics and attestation.
369 */
370TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
371 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
372 auto challenge = "hello";
373 auto app_id = "foo";
374
375 vector<uint8_t> key_blob;
376 vector<KeyCharacteristics> key_characteristics;
377 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
378 .RsaSigningKey(key_size, 65537)
379 .Digest(Digest::NONE)
380 .Padding(PaddingMode::NONE)
381 .AttestationChallenge(challenge)
382 .AttestationApplicationId(app_id)
383 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800384 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
385 .SetDefaultValidity(),
Qi Wubeefae42021-01-28 23:16:37 +0800386 &key_blob, &key_characteristics));
387
388 ASSERT_GT(key_blob.size(), 0U);
389 CheckBaseParams(key_characteristics);
390
391 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
392
393 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
394 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
395 << "Key size " << key_size << "missing";
396 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
397
398 // Check the usage count limit tag appears in the authorizations.
399 AuthorizationSet auths;
400 for (auto& entry : key_characteristics) {
401 auths.push_back(AuthorizationSet(entry.authorizations));
402 }
403 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
404 << "key usage count limit " << 1U << " missing";
405
406 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -0700407 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +0800408 ASSERT_GT(cert_chain_.size(), 0);
409
410 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
411 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
412 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
413 sw_enforced, hw_enforced, SecLevel(),
414 cert_chain_[0].encodedCertificate));
415
416 CheckedDeleteKey(&key_blob);
417 }
418}
419
420/*
Selene Huang31ab4042020-04-29 04:22:39 -0700421 * NewKeyGenerationTest.NoInvalidRsaSizes
422 *
423 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
424 */
425TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
426 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
427 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700428 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700429 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
430 GenerateKey(AuthorizationSetBuilder()
431 .RsaSigningKey(key_size, 65537)
432 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800433 .Padding(PaddingMode::NONE)
434 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700435 &key_blob, &key_characteristics));
436 }
437}
438
439/*
440 * NewKeyGenerationTest.RsaNoDefaultSize
441 *
442 * Verifies that failing to specify a key size for RSA key generation returns
443 * UNSUPPORTED_KEY_SIZE.
444 */
445TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
446 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
447 GenerateKey(AuthorizationSetBuilder()
448 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
449 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800450 .SigningKey()
451 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700452}
453
454/*
455 * NewKeyGenerationTest.Ecdsa
456 *
457 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
458 * have correct characteristics.
459 */
460TEST_P(NewKeyGenerationTest, Ecdsa) {
461 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
462 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700463 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800464 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
465 .EcdsaSigningKey(key_size)
466 .Digest(Digest::NONE)
467 .SetDefaultValidity(),
468 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -0700469 ASSERT_GT(key_blob.size(), 0U);
470 CheckBaseParams(key_characteristics);
471
Shawn Willden7f424372021-01-10 18:06:50 -0700472 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700473
474 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
475 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
476 << "Key size " << key_size << "missing";
477
478 CheckedDeleteKey(&key_blob);
479 }
480}
481
482/*
Qi Wud22ec842020-11-26 13:27:53 +0800483 * NewKeyGenerationTest.LimitedUsageEcdsa
484 *
485 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
486 * resulting keys have correct characteristics.
487 */
488TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
489 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
490 vector<uint8_t> key_blob;
491 vector<KeyCharacteristics> key_characteristics;
492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
493 .EcdsaSigningKey(key_size)
494 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800495 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
496 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800497 &key_blob, &key_characteristics));
498
499 ASSERT_GT(key_blob.size(), 0U);
500 CheckBaseParams(key_characteristics);
501
502 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
503
504 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
505 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
506 << "Key size " << key_size << "missing";
507
508 // Check the usage count limit tag appears in the authorizations.
509 AuthorizationSet auths;
510 for (auto& entry : key_characteristics) {
511 auths.push_back(AuthorizationSet(entry.authorizations));
512 }
513 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
514 << "key usage count limit " << 1U << " missing";
515
516 CheckedDeleteKey(&key_blob);
517 }
518}
519
520/*
Selene Huang31ab4042020-04-29 04:22:39 -0700521 * NewKeyGenerationTest.EcdsaDefaultSize
522 *
523 * Verifies that failing to specify a key size for EC key generation returns
524 * UNSUPPORTED_KEY_SIZE.
525 */
526TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
527 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
528 GenerateKey(AuthorizationSetBuilder()
529 .Authorization(TAG_ALGORITHM, Algorithm::EC)
530 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -0800531 .Digest(Digest::NONE)
532 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700533}
534
535/*
536 * NewKeyGenerationTest.EcdsaInvalidSize
537 *
538 * Verifies that specifying an invalid key size for EC key generation returns
539 * UNSUPPORTED_KEY_SIZE.
540 */
541TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
542 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
543 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700544 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800545 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
546 .EcdsaSigningKey(key_size)
547 .Digest(Digest::NONE)
548 .SetDefaultValidity(),
549 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -0700550 }
551
Janis Danisevskis164bb872021-02-09 11:30:25 -0800552 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
553 .EcdsaSigningKey(190)
554 .Digest(Digest::NONE)
555 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700556}
557
558/*
559 * NewKeyGenerationTest.EcdsaMismatchKeySize
560 *
561 * Verifies that specifying mismatched key size and curve for EC key generation returns
562 * INVALID_ARGUMENT.
563 */
564TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
565 if (SecLevel() == SecurityLevel::STRONGBOX) return;
566
567 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
568 GenerateKey(AuthorizationSetBuilder()
569 .EcdsaSigningKey(224)
570 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800571 .Digest(Digest::NONE)
572 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700573}
574
575/*
576 * NewKeyGenerationTest.EcdsaAllValidSizes
577 *
578 * Verifies that keymint supports all required EC key sizes.
579 */
580TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
581 auto valid_sizes = ValidKeySizes(Algorithm::EC);
582 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -0800583 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
584 .EcdsaSigningKey(size)
585 .Digest(Digest::NONE)
586 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -0700587 << "Failed to generate size: " << size;
588 CheckedDeleteKey();
589 }
590}
591
592/*
593 * NewKeyGenerationTest.EcdsaInvalidCurves
594 *
595 * Verifies that keymint does not support any curve designated as unsupported.
596 */
597TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
598 Digest digest;
599 if (SecLevel() == SecurityLevel::STRONGBOX) {
600 digest = Digest::SHA_2_256;
601 } else {
602 digest = Digest::SHA_2_512;
603 }
604 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -0800605 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
606 .EcdsaSigningKey(curve)
607 .Digest(digest)
608 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -0700609 << "Failed to generate key on curve: " << curve;
610 CheckedDeleteKey();
611 }
612}
613
614/*
615 * NewKeyGenerationTest.Hmac
616 *
617 * Verifies that keymint supports all required digests, and that the resulting keys have correct
618 * characteristics.
619 */
620TEST_P(NewKeyGenerationTest, Hmac) {
621 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
622 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700623 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700624 constexpr size_t key_size = 128;
625 ASSERT_EQ(ErrorCode::OK,
626 GenerateKey(
627 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
628 TAG_MIN_MAC_LENGTH, 128),
629 &key_blob, &key_characteristics));
630
631 ASSERT_GT(key_blob.size(), 0U);
632 CheckBaseParams(key_characteristics);
633
Shawn Willden7f424372021-01-10 18:06:50 -0700634 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
635 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
636 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
637 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -0700638
639 CheckedDeleteKey(&key_blob);
640 }
641}
642
643/*
Qi Wud22ec842020-11-26 13:27:53 +0800644 * NewKeyGenerationTest.LimitedUsageHmac
645 *
646 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
647 * resulting keys have correct characteristics.
648 */
649TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
650 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
651 vector<uint8_t> key_blob;
652 vector<KeyCharacteristics> key_characteristics;
653 constexpr size_t key_size = 128;
654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
655 .HmacKey(key_size)
656 .Digest(digest)
657 .Authorization(TAG_MIN_MAC_LENGTH, 128)
658 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
659 &key_blob, &key_characteristics));
660
661 ASSERT_GT(key_blob.size(), 0U);
662 CheckBaseParams(key_characteristics);
663
664 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
665 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
666 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
667 << "Key size " << key_size << "missing";
668
669 // Check the usage count limit tag appears in the authorizations.
670 AuthorizationSet auths;
671 for (auto& entry : key_characteristics) {
672 auths.push_back(AuthorizationSet(entry.authorizations));
673 }
674 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
675 << "key usage count limit " << 1U << " missing";
676
677 CheckedDeleteKey(&key_blob);
678 }
679}
680
681/*
Selene Huang31ab4042020-04-29 04:22:39 -0700682 * NewKeyGenerationTest.HmacCheckKeySizes
683 *
684 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
685 */
686TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
687 for (size_t key_size = 0; key_size <= 512; ++key_size) {
688 if (key_size < 64 || key_size % 8 != 0) {
689 // To keep this test from being very slow, we only test a random fraction of
690 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
691 // them, we expect to run ~40 of them in each run.
692 if (key_size % 8 == 0 || random() % 10 == 0) {
693 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
694 GenerateKey(AuthorizationSetBuilder()
695 .HmacKey(key_size)
696 .Digest(Digest::SHA_2_256)
697 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
698 << "HMAC key size " << key_size << " invalid";
699 }
700 } else {
701 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
702 .HmacKey(key_size)
703 .Digest(Digest::SHA_2_256)
704 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
705 << "Failed to generate HMAC key of size " << key_size;
706 CheckedDeleteKey();
707 }
708 }
709}
710
711/*
712 * NewKeyGenerationTest.HmacCheckMinMacLengths
713 *
714 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
715 * test is probabilistic in order to keep the runtime down, but any failure prints out the
716 * specific MAC length that failed, so reproducing a failed run will be easy.
717 */
718TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
719 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
720 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
721 // To keep this test from being very long, we only test a random fraction of
722 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
723 // we expect to run ~17 of them in each run.
724 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
725 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
726 GenerateKey(AuthorizationSetBuilder()
727 .HmacKey(128)
728 .Digest(Digest::SHA_2_256)
729 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
730 << "HMAC min mac length " << min_mac_length << " invalid.";
731 }
732 } else {
733 EXPECT_EQ(ErrorCode::OK,
734 GenerateKey(AuthorizationSetBuilder()
735 .HmacKey(128)
736 .Digest(Digest::SHA_2_256)
737 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
738 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
739 CheckedDeleteKey();
740 }
741 }
742}
743
744/*
745 * NewKeyGenerationTest.HmacMultipleDigests
746 *
747 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
748 */
749TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
750 if (SecLevel() == SecurityLevel::STRONGBOX) return;
751
752 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
753 GenerateKey(AuthorizationSetBuilder()
754 .HmacKey(128)
755 .Digest(Digest::SHA1)
756 .Digest(Digest::SHA_2_256)
757 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
758}
759
760/*
761 * NewKeyGenerationTest.HmacDigestNone
762 *
763 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
764 */
765TEST_P(NewKeyGenerationTest, HmacDigestNone) {
766 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
767 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
768 128)));
769
770 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
771 GenerateKey(AuthorizationSetBuilder()
772 .HmacKey(128)
773 .Digest(Digest::NONE)
774 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
775}
776
777INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
778
779typedef KeyMintAidlTestBase SigningOperationsTest;
780
781/*
782 * SigningOperationsTest.RsaSuccess
783 *
784 * Verifies that raw RSA signature operations succeed.
785 */
786TEST_P(SigningOperationsTest, RsaSuccess) {
787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
788 .RsaSigningKey(2048, 65537)
789 .Digest(Digest::NONE)
790 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800791 .Authorization(TAG_NO_AUTH_REQUIRED)
792 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700793 string message = "12345678901234567890123456789012";
794 string signature = SignMessage(
795 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
796}
797
798/*
799 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
800 *
Shawn Willden7f424372021-01-10 18:06:50 -0700801 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -0700802 */
803TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
805 .Authorization(TAG_NO_AUTH_REQUIRED)
806 .RsaSigningKey(2048, 65537)
807 .Digest(Digest::NONE)
808 .Padding(PaddingMode::NONE)
809 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -0800810 .Authorization(TAG_APPLICATION_DATA, "appdata")
811 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700812 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
813 Begin(KeyPurpose::SIGN,
814 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
815 AbortIfNeeded();
816 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
817 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
818 .Digest(Digest::NONE)
819 .Padding(PaddingMode::NONE)
820 .Authorization(TAG_APPLICATION_ID, "clientid")));
821 AbortIfNeeded();
822 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
823 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
824 .Digest(Digest::NONE)
825 .Padding(PaddingMode::NONE)
826 .Authorization(TAG_APPLICATION_DATA, "appdata")));
827 AbortIfNeeded();
828 EXPECT_EQ(ErrorCode::OK,
829 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
830 .Digest(Digest::NONE)
831 .Padding(PaddingMode::NONE)
832 .Authorization(TAG_APPLICATION_DATA, "appdata")
833 .Authorization(TAG_APPLICATION_ID, "clientid")));
834 AbortIfNeeded();
835}
836
837/*
838 * SigningOperationsTest.RsaPssSha256Success
839 *
840 * Verifies that RSA-PSS signature operations succeed.
841 */
842TEST_P(SigningOperationsTest, RsaPssSha256Success) {
843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
844 .RsaSigningKey(2048, 65537)
845 .Digest(Digest::SHA_2_256)
846 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800847 .Authorization(TAG_NO_AUTH_REQUIRED)
848 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700849 // Use large message, which won't work without digesting.
850 string message(1024, 'a');
851 string signature = SignMessage(
852 message,
853 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
854}
855
856/*
857 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
858 *
859 * Verifies that keymint rejects signature operations that specify a padding mode when the key
860 * supports only unpadded operations.
861 */
862TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
863 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
864 .RsaSigningKey(2048, 65537)
865 .Digest(Digest::NONE)
866 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800867 .Padding(PaddingMode::NONE)
868 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700869 string message = "12345678901234567890123456789012";
870 string signature;
871
872 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
873 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
874 .Digest(Digest::NONE)
875 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
876}
877
878/*
879 * SigningOperationsTest.NoUserConfirmation
880 *
881 * Verifies that keymint rejects signing operations for keys with
882 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
883 * presented.
884 */
885TEST_P(SigningOperationsTest, NoUserConfirmation) {
886 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
888 .RsaSigningKey(1024, 65537)
889 .Digest(Digest::NONE)
890 .Padding(PaddingMode::NONE)
891 .Authorization(TAG_NO_AUTH_REQUIRED)
892 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
893 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700894
895 const string message = "12345678901234567890123456789012";
896 EXPECT_EQ(ErrorCode::OK,
897 Begin(KeyPurpose::SIGN,
898 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
899 string signature;
900 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
901}
902
903/*
904 * SigningOperationsTest.RsaPkcs1Sha256Success
905 *
906 * Verifies that digested RSA-PKCS1 signature operations succeed.
907 */
908TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
909 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
910 .RsaSigningKey(2048, 65537)
911 .Digest(Digest::SHA_2_256)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800913 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
914 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700915 string message(1024, 'a');
916 string signature = SignMessage(message, AuthorizationSetBuilder()
917 .Digest(Digest::SHA_2_256)
918 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
919}
920
921/*
922 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
923 *
924 * Verifies that undigested RSA-PKCS1 signature operations succeed.
925 */
926TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
928 .RsaSigningKey(2048, 65537)
929 .Digest(Digest::NONE)
930 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800931 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
932 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700933 string message(53, 'a');
934 string signature = SignMessage(message, AuthorizationSetBuilder()
935 .Digest(Digest::NONE)
936 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
937}
938
939/*
940 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
941 *
942 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
943 * given a too-long message.
944 */
945TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
946 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
947 .RsaSigningKey(2048, 65537)
948 .Digest(Digest::NONE)
949 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800950 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
951 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700952 string message(257, 'a');
953
954 EXPECT_EQ(ErrorCode::OK,
955 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
956 .Digest(Digest::NONE)
957 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
958 string signature;
959 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
960}
961
962/*
963 * SigningOperationsTest.RsaPssSha512TooSmallKey
964 *
965 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
966 * used with a key that is too small for the message.
967 *
968 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
969 * keymint specification requires that salt_size == digest_size, so the message will be
970 * digest_size * 2 +
971 * 16. Such a message can only be signed by a given key if the key is at least that size. This
972 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
973 * for a 1024-bit key.
974 */
975TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
976 if (SecLevel() == SecurityLevel::STRONGBOX) return;
977 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
978 .RsaSigningKey(1024, 65537)
979 .Digest(Digest::SHA_2_512)
980 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800981 .Padding(PaddingMode::RSA_PSS)
982 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700983 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
984 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
985 .Digest(Digest::SHA_2_512)
986 .Padding(PaddingMode::RSA_PSS)));
987}
988
989/*
990 * SigningOperationsTest.RsaNoPaddingTooLong
991 *
992 * Verifies that raw RSA signature operations fail with the correct error code when
993 * given a too-long message.
994 */
995TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
997 .RsaSigningKey(2048, 65537)
998 .Digest(Digest::NONE)
999 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001000 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1001 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001002 // One byte too long
1003 string message(2048 / 8 + 1, 'a');
1004 ASSERT_EQ(ErrorCode::OK,
1005 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1006 .Digest(Digest::NONE)
1007 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1008 string result;
1009 ErrorCode finish_error_code = Finish(message, &result);
1010 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1011 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1012
1013 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1014 message = string(128 * 1024, 'a');
1015 ASSERT_EQ(ErrorCode::OK,
1016 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1017 .Digest(Digest::NONE)
1018 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1019 finish_error_code = Finish(message, &result);
1020 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1021 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1022}
1023
1024/*
1025 * SigningOperationsTest.RsaAbort
1026 *
1027 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1028 * test, but the behavior should be algorithm and purpose-independent.
1029 */
1030TEST_P(SigningOperationsTest, RsaAbort) {
1031 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1032 .RsaSigningKey(2048, 65537)
1033 .Digest(Digest::NONE)
1034 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001035 .Padding(PaddingMode::NONE)
1036 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001037
1038 ASSERT_EQ(ErrorCode::OK,
1039 Begin(KeyPurpose::SIGN,
1040 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1041 EXPECT_EQ(ErrorCode::OK, Abort());
1042
1043 // Another abort should fail
1044 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1045
1046 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001047 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001048}
1049
1050/*
1051 * SigningOperationsTest.RsaUnsupportedPadding
1052 *
1053 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1054 * with a padding mode inappropriate for RSA.
1055 */
1056TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1058 .RsaSigningKey(2048, 65537)
1059 .Authorization(TAG_NO_AUTH_REQUIRED)
1060 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001061 .Padding(PaddingMode::PKCS7)
1062 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001063 ASSERT_EQ(
1064 ErrorCode::UNSUPPORTED_PADDING_MODE,
1065 Begin(KeyPurpose::SIGN,
1066 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1067}
1068
1069/*
1070 * SigningOperationsTest.RsaPssNoDigest
1071 *
1072 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
1073 */
1074TEST_P(SigningOperationsTest, RsaNoDigest) {
1075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1076 .RsaSigningKey(2048, 65537)
1077 .Authorization(TAG_NO_AUTH_REQUIRED)
1078 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001079 .Padding(PaddingMode::RSA_PSS)
1080 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001081 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1082 Begin(KeyPurpose::SIGN,
1083 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1084
1085 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1086 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1087}
1088
1089/*
1090 * SigningOperationsTest.RsaPssNoDigest
1091 *
1092 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
1093 * supported in some cases (as validated in other tests), but a mode must be specified.
1094 */
1095TEST_P(SigningOperationsTest, RsaNoPadding) {
1096 // Padding must be specified
1097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1098 .RsaKey(2048, 65537)
1099 .Authorization(TAG_NO_AUTH_REQUIRED)
1100 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001101 .Digest(Digest::NONE)
1102 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001103 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1104 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1105}
1106
1107/*
1108 * SigningOperationsTest.RsaShortMessage
1109 *
1110 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1111 */
1112TEST_P(SigningOperationsTest, RsaTooShortMessage) {
1113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1114 .Authorization(TAG_NO_AUTH_REQUIRED)
1115 .RsaSigningKey(2048, 65537)
1116 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001117 .Padding(PaddingMode::NONE)
1118 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001119
1120 // Barely shorter
1121 string message(2048 / 8 - 1, 'a');
1122 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1123
1124 // Much shorter
1125 message = "a";
1126 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1127}
1128
1129/*
1130 * SigningOperationsTest.RsaSignWithEncryptionKey
1131 *
1132 * Verifies that RSA encryption keys cannot be used to sign.
1133 */
1134TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
1135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1136 .Authorization(TAG_NO_AUTH_REQUIRED)
1137 .RsaEncryptionKey(2048, 65537)
1138 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001139 .Padding(PaddingMode::NONE)
1140 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001141 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1142 Begin(KeyPurpose::SIGN,
1143 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1144}
1145
1146/*
1147 * SigningOperationsTest.RsaSignTooLargeMessage
1148 *
1149 * Verifies that attempting a raw signature of a message which is the same length as the key,
1150 * but numerically larger than the public modulus, fails with the correct error.
1151 */
1152TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
1153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1154 .Authorization(TAG_NO_AUTH_REQUIRED)
1155 .RsaSigningKey(2048, 65537)
1156 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001157 .Padding(PaddingMode::NONE)
1158 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001159
1160 // Largest possible message will always be larger than the public modulus.
1161 string message(2048 / 8, static_cast<char>(0xff));
1162 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1163 .Authorization(TAG_NO_AUTH_REQUIRED)
1164 .Digest(Digest::NONE)
1165 .Padding(PaddingMode::NONE)));
1166 string signature;
1167 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1168}
1169
1170/*
1171 * SigningOperationsTest.EcdsaAllSizesAndHashes
1172 *
1173 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1174 */
1175TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1176 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1177 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1178 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1179 .Authorization(TAG_NO_AUTH_REQUIRED)
1180 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001181 .Digest(digest)
1182 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001183 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1184 << " and digest " << digest;
1185 if (error != ErrorCode::OK) continue;
1186
1187 string message(1024, 'a');
1188 if (digest == Digest::NONE) message.resize(key_size / 8);
1189 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1190 CheckedDeleteKey();
1191 }
1192 }
1193}
1194
1195/*
1196 * SigningOperationsTest.EcdsaAllCurves
1197 *
1198 * Verifies that ECDSA operations succeed with all possible curves.
1199 */
1200TEST_P(SigningOperationsTest, EcdsaAllCurves) {
1201 for (auto curve : ValidCurves()) {
1202 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1203 .Authorization(TAG_NO_AUTH_REQUIRED)
1204 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001205 .Digest(Digest::SHA_2_256)
1206 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001207 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1208 if (error != ErrorCode::OK) continue;
1209
1210 string message(1024, 'a');
1211 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1212 CheckedDeleteKey();
1213 }
1214}
1215
1216/*
1217 * SigningOperationsTest.EcdsaNoDigestHugeData
1218 *
1219 * Verifies that ECDSA operations support very large messages, even without digesting. This
1220 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
1221 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
1222 * the framework.
1223 */
1224TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
1225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1226 .Authorization(TAG_NO_AUTH_REQUIRED)
1227 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001228 .Digest(Digest::NONE)
1229 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001230 string message(1 * 1024, 'a');
1231 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1232}
1233
1234/*
1235 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
1236 *
1237 * Verifies that using an EC key requires the correct app ID/data.
1238 */
1239TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
1240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1241 .Authorization(TAG_NO_AUTH_REQUIRED)
1242 .EcdsaSigningKey(256)
1243 .Digest(Digest::NONE)
1244 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001245 .Authorization(TAG_APPLICATION_DATA, "appdata")
1246 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001247 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1248 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1249 AbortIfNeeded();
1250 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1251 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1252 .Digest(Digest::NONE)
1253 .Authorization(TAG_APPLICATION_ID, "clientid")));
1254 AbortIfNeeded();
1255 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1256 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1257 .Digest(Digest::NONE)
1258 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1259 AbortIfNeeded();
1260 EXPECT_EQ(ErrorCode::OK,
1261 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1262 .Digest(Digest::NONE)
1263 .Authorization(TAG_APPLICATION_DATA, "appdata")
1264 .Authorization(TAG_APPLICATION_ID, "clientid")));
1265 AbortIfNeeded();
1266}
1267
1268/*
1269 * SigningOperationsTest.AesEcbSign
1270 *
1271 * Verifies that attempts to use AES keys to sign fail in the correct way.
1272 */
1273TEST_P(SigningOperationsTest, AesEcbSign) {
1274 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1275 .Authorization(TAG_NO_AUTH_REQUIRED)
1276 .SigningKey()
1277 .AesEncryptionKey(128)
1278 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
1279
1280 AuthorizationSet out_params;
1281 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1282 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
1283 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1284 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
1285}
1286
1287/*
1288 * SigningOperationsTest.HmacAllDigests
1289 *
1290 * Verifies that HMAC works with all digests.
1291 */
1292TEST_P(SigningOperationsTest, HmacAllDigests) {
1293 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1295 .Authorization(TAG_NO_AUTH_REQUIRED)
1296 .HmacKey(128)
1297 .Digest(digest)
1298 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1299 << "Failed to create HMAC key with digest " << digest;
1300 string message = "12345678901234567890123456789012";
1301 string signature = MacMessage(message, digest, 160);
1302 EXPECT_EQ(160U / 8U, signature.size())
1303 << "Failed to sign with HMAC key with digest " << digest;
1304 CheckedDeleteKey();
1305 }
1306}
1307
1308/*
1309 * SigningOperationsTest.HmacSha256TooLargeMacLength
1310 *
1311 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
1312 * digest size.
1313 */
1314TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1316 .Authorization(TAG_NO_AUTH_REQUIRED)
1317 .HmacKey(128)
1318 .Digest(Digest::SHA_2_256)
1319 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1320 AuthorizationSet output_params;
1321 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1322 AuthorizationSetBuilder()
1323 .Digest(Digest::SHA_2_256)
1324 .Authorization(TAG_MAC_LENGTH, 264),
1325 &output_params));
1326}
1327
1328/*
1329 * SigningOperationsTest.HmacSha256TooSmallMacLength
1330 *
1331 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1332 * specified minimum MAC length.
1333 */
1334TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1335 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1336 .Authorization(TAG_NO_AUTH_REQUIRED)
1337 .HmacKey(128)
1338 .Digest(Digest::SHA_2_256)
1339 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1340 AuthorizationSet output_params;
1341 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1342 AuthorizationSetBuilder()
1343 .Digest(Digest::SHA_2_256)
1344 .Authorization(TAG_MAC_LENGTH, 120),
1345 &output_params));
1346}
1347
1348/*
1349 * SigningOperationsTest.HmacRfc4231TestCase3
1350 *
1351 * Validates against the test vectors from RFC 4231 test case 3.
1352 */
1353TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1354 string key(20, 0xaa);
1355 string message(50, 0xdd);
1356 uint8_t sha_224_expected[] = {
1357 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1358 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1359 };
1360 uint8_t sha_256_expected[] = {
1361 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1362 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1363 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1364 };
1365 uint8_t sha_384_expected[] = {
1366 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1367 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1368 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1369 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1370 };
1371 uint8_t sha_512_expected[] = {
1372 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1373 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1374 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1375 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1376 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1377 };
1378
1379 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1380 if (SecLevel() != SecurityLevel::STRONGBOX) {
1381 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1382 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1383 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1384 }
1385}
1386
1387/*
1388 * SigningOperationsTest.HmacRfc4231TestCase5
1389 *
1390 * Validates against the test vectors from RFC 4231 test case 5.
1391 */
1392TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
1393 string key(20, 0x0c);
1394 string message = "Test With Truncation";
1395
1396 uint8_t sha_224_expected[] = {
1397 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1398 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1399 };
1400 uint8_t sha_256_expected[] = {
1401 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1402 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1403 };
1404 uint8_t sha_384_expected[] = {
1405 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1406 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1407 };
1408 uint8_t sha_512_expected[] = {
1409 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1410 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1411 };
1412
1413 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1414 if (SecLevel() != SecurityLevel::STRONGBOX) {
1415 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1416 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1417 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1418 }
1419}
1420
1421INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
1422
1423typedef KeyMintAidlTestBase VerificationOperationsTest;
1424
1425/*
1426 * VerificationOperationsTest.RsaSuccess
1427 *
1428 * Verifies that a simple RSA signature/verification sequence succeeds.
1429 */
1430TEST_P(VerificationOperationsTest, RsaSuccess) {
1431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1432 .Authorization(TAG_NO_AUTH_REQUIRED)
1433 .RsaSigningKey(2048, 65537)
1434 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001435 .Padding(PaddingMode::NONE)
1436 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001437 string message = "12345678901234567890123456789012";
1438 string signature = SignMessage(
1439 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1440 VerifyMessage(message, signature,
1441 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1442}
1443
1444/*
1445 * VerificationOperationsTest.RsaSuccess
1446 *
1447 * Verifies RSA signature/verification for all padding modes and digests.
1448 */
1449TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
1450 auto authorizations = AuthorizationSetBuilder()
1451 .Authorization(TAG_NO_AUTH_REQUIRED)
1452 .RsaSigningKey(2048, 65537)
1453 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
1454 .Padding(PaddingMode::NONE)
1455 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001456 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1457 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07001458
1459 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
1460
1461 string message(128, 'a');
1462 string corrupt_message(message);
1463 ++corrupt_message[corrupt_message.size() / 2];
1464
1465 for (auto padding :
1466 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
1467 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
1468 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
1469 // Digesting only makes sense with padding.
1470 continue;
1471 }
1472
1473 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
1474 // PSS requires digesting.
1475 continue;
1476 }
1477
1478 string signature =
1479 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
1480 VerifyMessage(message, signature,
1481 AuthorizationSetBuilder().Digest(digest).Padding(padding));
1482
1483 /* TODO(seleneh) add exportkey tests back later when we have decided on
1484 * the new api.
1485 if (digest != Digest::NONE) {
1486 // Verify with OpenSSL.
1487 vector<uint8_t> pubkey;
1488 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
1489
1490 const uint8_t* p = pubkey.data();
1491 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
1492 ASSERT_TRUE(pkey.get());
1493
1494 EVP_MD_CTX digest_ctx;
1495 EVP_MD_CTX_init(&digest_ctx);
1496 EVP_PKEY_CTX* pkey_ctx;
1497 const EVP_MD* md = openssl_digest(digest);
1498 ASSERT_NE(md, nullptr);
1499 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
1500 nullptr, pkey.get()));
1501
1502 switch (padding) {
1503 case PaddingMode::RSA_PSS:
1504 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
1505 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
1506 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
1507 // PKCS1 is the default; don't need to set anything.
1508 break;
1509 default:
1510 FAIL();
1511 break;
1512 }
1513
1514 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
1515 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1516 reinterpret_cast<const
1517 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
1518 }
1519 */
1520
1521 // Corrupt signature shouldn't verify.
1522 string corrupt_signature(signature);
1523 ++corrupt_signature[corrupt_signature.size() / 2];
1524
1525 EXPECT_EQ(ErrorCode::OK,
1526 Begin(KeyPurpose::VERIFY,
1527 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1528 string result;
1529 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
1530
1531 // Corrupt message shouldn't verify
1532 EXPECT_EQ(ErrorCode::OK,
1533 Begin(KeyPurpose::VERIFY,
1534 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1535 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
1536 }
1537 }
1538}
1539
1540/*
1541 * VerificationOperationsTest.RsaSuccess
1542 *
1543 * Verifies ECDSA signature/verification for all digests and curves.
1544 */
1545TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
1546 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
1547
1548 string message = "1234567890";
1549 string corrupt_message = "2234567890";
1550 for (auto curve : ValidCurves()) {
1551 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1552 .Authorization(TAG_NO_AUTH_REQUIRED)
1553 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001554 .Digest(digests)
1555 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001556 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
1557 if (error != ErrorCode::OK) {
1558 continue;
1559 }
1560
1561 for (auto digest : digests) {
1562 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1563 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
1564
1565 /* TODO(seleneh) add exportkey tests back later when we have decided on
1566 * the new api.
1567
1568 // Verify with OpenSSL
1569 if (digest != Digest::NONE) {
1570 vector<uint8_t> pubkey;
1571 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
1572 << curve << ' ' << digest;
1573
1574 const uint8_t* p = pubkey.data();
1575 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
1576 ASSERT_TRUE(pkey.get());
1577
1578 EVP_MD_CTX digest_ctx;
1579 EVP_MD_CTX_init(&digest_ctx);
1580 EVP_PKEY_CTX* pkey_ctx;
1581 const EVP_MD* md = openssl_digest(digest);
1582
1583 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
1584 nullptr, pkey.get()))
1585 << curve << ' ' << digest;
1586
1587 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
1588 message.size()))
1589 << curve << ' ' << digest;
1590
1591 EXPECT_EQ(1,
1592 EVP_DigestVerifyFinal(&digest_ctx,
1593 reinterpret_cast<const
1594 uint8_t*>(signature.data()), signature.size()))
1595 << curve << ' ' << digest;
1596
1597 EVP_MD_CTX_cleanup(&digest_ctx);
1598 }
1599 */
1600 // Corrupt signature shouldn't verify.
1601 string corrupt_signature(signature);
1602 ++corrupt_signature[corrupt_signature.size() / 2];
1603
1604 EXPECT_EQ(ErrorCode::OK,
1605 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1606 << curve << ' ' << digest;
1607
1608 string result;
1609 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
1610 << curve << ' ' << digest;
1611
1612 // Corrupt message shouldn't verify
1613 EXPECT_EQ(ErrorCode::OK,
1614 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1615 << curve << ' ' << digest;
1616
1617 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
1618 << curve << ' ' << digest;
1619 }
1620
1621 auto rc = DeleteKey();
1622 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
1623 }
1624}
1625
1626/*
1627 * VerificationOperationsTest.HmacSigningKeyCannotVerify
1628 *
1629 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
1630 */
1631TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
1632 string key_material = "HelloThisIsAKey";
1633
1634 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07001635 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07001636 EXPECT_EQ(ErrorCode::OK,
1637 ImportKey(AuthorizationSetBuilder()
1638 .Authorization(TAG_NO_AUTH_REQUIRED)
1639 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1640 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
1641 .Digest(Digest::SHA_2_256)
1642 .Authorization(TAG_MIN_MAC_LENGTH, 160),
1643 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
1644 EXPECT_EQ(ErrorCode::OK,
1645 ImportKey(AuthorizationSetBuilder()
1646 .Authorization(TAG_NO_AUTH_REQUIRED)
1647 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1648 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
1649 .Digest(Digest::SHA_2_256)
1650 .Authorization(TAG_MIN_MAC_LENGTH, 160),
1651 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
1652
1653 string message = "This is a message.";
1654 string signature = SignMessage(
1655 signing_key, message,
1656 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
1657
1658 // Signing key should not work.
1659 AuthorizationSet out_params;
1660 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1661 Begin(KeyPurpose::VERIFY, signing_key,
1662 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
1663
1664 // Verification key should work.
1665 VerifyMessage(verification_key, message, signature,
1666 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1667
1668 CheckedDeleteKey(&signing_key);
1669 CheckedDeleteKey(&verification_key);
1670}
1671
1672INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
1673
1674typedef KeyMintAidlTestBase ExportKeyTest;
1675
1676/*
1677 * ExportKeyTest.RsaUnsupportedKeyFormat
1678 *
1679 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
1680 */
1681// TODO(seleneh) add ExportKey to GenerateKey
1682// check result
1683
1684class ImportKeyTest : public KeyMintAidlTestBase {
1685 public:
1686 template <TagType tag_type, Tag tag, typename ValueT>
1687 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
1688 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07001689 for (auto& entry : key_characteristics_) {
1690 if (entry.securityLevel == SecLevel()) {
1691 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
1692 << "Tag " << tag << " with value " << expected
1693 << " not found at security level" << entry.securityLevel;
1694 } else {
1695 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
1696 << "Tag " << tag << " found at security level " << entry.securityLevel;
1697 }
Selene Huang31ab4042020-04-29 04:22:39 -07001698 }
1699 }
1700
1701 void CheckOrigin() {
1702 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07001703 // Origin isn't a crypto param, but it always lives with them.
1704 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07001705 }
1706};
1707
1708/*
1709 * ImportKeyTest.RsaSuccess
1710 *
1711 * Verifies that importing and using an RSA key pair works correctly.
1712 */
1713TEST_P(ImportKeyTest, RsaSuccess) {
1714 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1715 .Authorization(TAG_NO_AUTH_REQUIRED)
1716 .RsaSigningKey(1024, 65537)
1717 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001718 .Padding(PaddingMode::RSA_PSS)
1719 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001720 KeyFormat::PKCS8, rsa_key));
1721
1722 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
1723 CheckCryptoParam(TAG_KEY_SIZE, 1024U);
1724 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
1725 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1726 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
1727 CheckOrigin();
1728
1729 string message(1024 / 8, 'a');
1730 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
1731 string signature = SignMessage(message, params);
1732 VerifyMessage(message, signature, params);
1733}
1734
1735/*
1736 * ImportKeyTest.RsaKeySizeMismatch
1737 *
1738 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
1739 * correct way.
1740 */
1741TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1742 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1743 ImportKey(AuthorizationSetBuilder()
1744 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
1745 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001746 .Padding(PaddingMode::NONE)
1747 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001748 KeyFormat::PKCS8, rsa_key));
1749}
1750
1751/*
1752 * ImportKeyTest.RsaPublicExponentMismatch
1753 *
1754 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
1755 * fails in the correct way.
1756 */
1757TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
1758 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1759 ImportKey(AuthorizationSetBuilder()
1760 .RsaSigningKey(1024, 3 /* Doesn't match key */)
1761 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001762 .Padding(PaddingMode::NONE)
1763 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001764 KeyFormat::PKCS8, rsa_key));
1765}
1766
1767/*
1768 * ImportKeyTest.EcdsaSuccess
1769 *
1770 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
1771 */
1772TEST_P(ImportKeyTest, EcdsaSuccess) {
1773 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1774 .Authorization(TAG_NO_AUTH_REQUIRED)
1775 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001776 .Digest(Digest::SHA_2_256)
1777 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001778 KeyFormat::PKCS8, ec_256_key));
1779
1780 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1781 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1782 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1783 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1784
1785 CheckOrigin();
1786
1787 string message(32, 'a');
1788 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1789 string signature = SignMessage(message, params);
1790 VerifyMessage(message, signature, params);
1791}
1792
1793/*
1794 * ImportKeyTest.EcdsaP256RFC5915Success
1795 *
1796 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
1797 * correctly.
1798 */
1799TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
1800 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1801 .Authorization(TAG_NO_AUTH_REQUIRED)
1802 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001803 .Digest(Digest::SHA_2_256)
1804 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001805 KeyFormat::PKCS8, ec_256_key_rfc5915));
1806
1807 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1808 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1809 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1810 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1811
1812 CheckOrigin();
1813
1814 string message(32, 'a');
1815 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1816 string signature = SignMessage(message, params);
1817 VerifyMessage(message, signature, params);
1818}
1819
1820/*
1821 * ImportKeyTest.EcdsaP256SEC1Success
1822 *
1823 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
1824 */
1825TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
1826 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1827 .Authorization(TAG_NO_AUTH_REQUIRED)
1828 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001829 .Digest(Digest::SHA_2_256)
1830 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001831 KeyFormat::PKCS8, ec_256_key_sec1));
1832
1833 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1834 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1835 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1836 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1837
1838 CheckOrigin();
1839
1840 string message(32, 'a');
1841 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1842 string signature = SignMessage(message, params);
1843 VerifyMessage(message, signature, params);
1844}
1845
1846/*
1847 * ImportKeyTest.Ecdsa521Success
1848 *
1849 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
1850 */
1851TEST_P(ImportKeyTest, Ecdsa521Success) {
1852 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1853 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1854 .Authorization(TAG_NO_AUTH_REQUIRED)
1855 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001856 .Digest(Digest::SHA_2_256)
1857 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001858 KeyFormat::PKCS8, ec_521_key));
1859
1860 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1861 CheckCryptoParam(TAG_KEY_SIZE, 521U);
1862 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1863 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
1864 CheckOrigin();
1865
1866 string message(32, 'a');
1867 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1868 string signature = SignMessage(message, params);
1869 VerifyMessage(message, signature, params);
1870}
1871
1872/*
1873 * ImportKeyTest.EcdsaSizeMismatch
1874 *
1875 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
1876 * correct way.
1877 */
1878TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
1879 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1880 ImportKey(AuthorizationSetBuilder()
1881 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001882 .Digest(Digest::NONE)
1883 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001884 KeyFormat::PKCS8, ec_256_key));
1885}
1886
1887/*
1888 * ImportKeyTest.EcdsaCurveMismatch
1889 *
1890 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
1891 * the correct way.
1892 */
1893TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
1894 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1895 ImportKey(AuthorizationSetBuilder()
1896 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001897 .Digest(Digest::NONE)
1898 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001899 KeyFormat::PKCS8, ec_256_key));
1900}
1901
1902/*
1903 * ImportKeyTest.AesSuccess
1904 *
1905 * Verifies that importing and using an AES key works.
1906 */
1907TEST_P(ImportKeyTest, AesSuccess) {
1908 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1909 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1910 .Authorization(TAG_NO_AUTH_REQUIRED)
1911 .AesEncryptionKey(key.size() * 8)
1912 .EcbMode()
1913 .Padding(PaddingMode::PKCS7),
1914 KeyFormat::RAW, key));
1915
1916 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
1917 CheckCryptoParam(TAG_KEY_SIZE, 128U);
1918 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
1919 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
1920 CheckOrigin();
1921
1922 string message = "Hello World!";
1923 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
1924 string ciphertext = EncryptMessage(message, params);
1925 string plaintext = DecryptMessage(ciphertext, params);
1926 EXPECT_EQ(message, plaintext);
1927}
1928
1929/*
1930 * ImportKeyTest.AesSuccess
1931 *
1932 * Verifies that importing and using an HMAC key works.
1933 */
1934TEST_P(ImportKeyTest, HmacKeySuccess) {
1935 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1936 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1937 .Authorization(TAG_NO_AUTH_REQUIRED)
1938 .HmacKey(key.size() * 8)
1939 .Digest(Digest::SHA_2_256)
1940 .Authorization(TAG_MIN_MAC_LENGTH, 256),
1941 KeyFormat::RAW, key));
1942
1943 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
1944 CheckCryptoParam(TAG_KEY_SIZE, 128U);
1945 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1946 CheckOrigin();
1947
1948 string message = "Hello World!";
1949 string signature = MacMessage(message, Digest::SHA_2_256, 256);
1950 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1951}
1952
1953INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
1954
1955auto wrapped_key = hex2str(
1956 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
1957 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
1958 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
1959 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
1960 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
1961 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
1962 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
1963 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
1964 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
1965
1966auto wrapped_key_masked = hex2str(
1967 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
1968 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
1969 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
1970 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
1971 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
1972 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
1973 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
1974 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
1975 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
1976
1977auto wrapping_key = hex2str(
1978 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
1979 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
1980 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
1981 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
1982 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
1983 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
1984 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
1985 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
1986 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
1987 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
1988 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
1989 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
1990 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
1991 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
1992 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
1993 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
1994 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
1995 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
1996 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
1997 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
1998 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
1999 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
2000 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
2001 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
2002 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
2003 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
2004 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
2005 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
2006 "f27ba61be6ad02dfddda8f4e6822");
2007
2008string zero_masking_key =
2009 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
2010string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
2011
2012class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
2013
2014TEST_P(ImportWrappedKeyTest, Success) {
2015 auto wrapping_key_desc = AuthorizationSetBuilder()
2016 .RsaEncryptionKey(2048, 65537)
2017 .Digest(Digest::SHA_2_256)
2018 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002019 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2020 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002021
2022 ASSERT_EQ(ErrorCode::OK,
2023 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
2024 AuthorizationSetBuilder()
2025 .Digest(Digest::SHA_2_256)
2026 .Padding(PaddingMode::RSA_OAEP)));
2027
2028 string message = "Hello World!";
2029 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2030 string ciphertext = EncryptMessage(message, params);
2031 string plaintext = DecryptMessage(ciphertext, params);
2032 EXPECT_EQ(message, plaintext);
2033}
2034
2035TEST_P(ImportWrappedKeyTest, SuccessMasked) {
2036 auto wrapping_key_desc = AuthorizationSetBuilder()
2037 .RsaEncryptionKey(2048, 65537)
2038 .Digest(Digest::SHA_2_256)
2039 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002040 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2041 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002042
2043 ASSERT_EQ(ErrorCode::OK,
2044 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
2045 AuthorizationSetBuilder()
2046 .Digest(Digest::SHA_2_256)
2047 .Padding(PaddingMode::RSA_OAEP)));
2048}
2049
2050TEST_P(ImportWrappedKeyTest, WrongMask) {
2051 auto wrapping_key_desc = AuthorizationSetBuilder()
2052 .RsaEncryptionKey(2048, 65537)
2053 .Digest(Digest::SHA_2_256)
2054 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002055 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2056 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002057
2058 ASSERT_EQ(
2059 ErrorCode::VERIFICATION_FAILED,
2060 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2061 AuthorizationSetBuilder()
2062 .Digest(Digest::SHA_2_256)
2063 .Padding(PaddingMode::RSA_OAEP)));
2064}
2065
2066TEST_P(ImportWrappedKeyTest, WrongPurpose) {
2067 auto wrapping_key_desc = AuthorizationSetBuilder()
2068 .RsaEncryptionKey(2048, 65537)
2069 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002070 .Padding(PaddingMode::RSA_OAEP)
2071 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002072
2073 ASSERT_EQ(
2074 ErrorCode::INCOMPATIBLE_PURPOSE,
2075 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2076 AuthorizationSetBuilder()
2077 .Digest(Digest::SHA_2_256)
2078 .Padding(PaddingMode::RSA_OAEP)));
2079}
2080
2081INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
2082
2083typedef KeyMintAidlTestBase EncryptionOperationsTest;
2084
2085/*
2086 * EncryptionOperationsTest.RsaNoPaddingSuccess
2087 *
2088 * Verifies that raw RSA encryption works.
2089 */
2090TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2092 .Authorization(TAG_NO_AUTH_REQUIRED)
2093 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002094 .Padding(PaddingMode::NONE)
2095 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002096
2097 string message = string(2048 / 8, 'a');
2098 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2099 string ciphertext1 = EncryptMessage(message, params);
2100 EXPECT_EQ(2048U / 8, ciphertext1.size());
2101
2102 string ciphertext2 = EncryptMessage(message, params);
2103 EXPECT_EQ(2048U / 8, ciphertext2.size());
2104
2105 // Unpadded RSA is deterministic
2106 EXPECT_EQ(ciphertext1, ciphertext2);
2107}
2108
2109/*
2110 * EncryptionOperationsTest.RsaNoPaddingShortMessage
2111 *
2112 * Verifies that raw RSA encryption of short messages works.
2113 */
2114TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2115 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2116 .Authorization(TAG_NO_AUTH_REQUIRED)
2117 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002118 .Padding(PaddingMode::NONE)
2119 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002120
2121 string message = "1";
2122 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2123
2124 string ciphertext = EncryptMessage(message, params);
2125 EXPECT_EQ(2048U / 8, ciphertext.size());
2126
2127 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
2128 string plaintext = DecryptMessage(ciphertext, params);
2129
2130 EXPECT_EQ(expected_plaintext, plaintext);
2131
2132 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2133 message = static_cast<char>(1);
2134 ciphertext = EncryptMessage(message, params);
2135 EXPECT_EQ(2048U / 8, ciphertext.size());
2136 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
2137}
2138
2139/*
2140 * EncryptionOperationsTest.RsaNoPaddingTooLong
2141 *
2142 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2143 */
2144TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2145 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2146 .Authorization(TAG_NO_AUTH_REQUIRED)
2147 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002148 .Padding(PaddingMode::NONE)
2149 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002150
2151 string message(2048 / 8 + 1, 'a');
2152
2153 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2154 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2155
2156 string result;
2157 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2158}
2159
2160/*
2161 * EncryptionOperationsTest.RsaNoPaddingTooLarge
2162 *
2163 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
2164 * way.
2165 */
2166// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
2167// version of ExportKey inside generateKey
2168
2169/*
2170 * EncryptionOperationsTest.RsaOaepSuccess
2171 *
2172 * Verifies that RSA-OAEP encryption operations work, with all digests.
2173 */
2174TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2175 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2176
2177 size_t key_size = 2048; // Need largish key for SHA-512 test.
2178 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2179 .Authorization(TAG_NO_AUTH_REQUIRED)
2180 .RsaEncryptionKey(key_size, 65537)
2181 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002182 .Digest(digests)
2183 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002184
2185 string message = "Hello";
2186
2187 for (auto digest : digests) {
2188 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2189 string ciphertext1 = EncryptMessage(message, params);
2190 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2191 EXPECT_EQ(key_size / 8, ciphertext1.size());
2192
2193 string ciphertext2 = EncryptMessage(message, params);
2194 EXPECT_EQ(key_size / 8, ciphertext2.size());
2195
2196 // OAEP randomizes padding so every result should be different (with astronomically high
2197 // probability).
2198 EXPECT_NE(ciphertext1, ciphertext2);
2199
2200 string plaintext1 = DecryptMessage(ciphertext1, params);
2201 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2202 string plaintext2 = DecryptMessage(ciphertext2, params);
2203 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2204
2205 // Decrypting corrupted ciphertext should fail.
2206 size_t offset_to_corrupt = random() % ciphertext1.size();
2207 char corrupt_byte;
2208 do {
2209 corrupt_byte = static_cast<char>(random() % 256);
2210 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2211 ciphertext1[offset_to_corrupt] = corrupt_byte;
2212
2213 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2214 string result;
2215 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2216 EXPECT_EQ(0U, result.size());
2217 }
2218}
2219
2220/*
2221 * EncryptionOperationsTest.RsaOaepInvalidDigest
2222 *
2223 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2224 * without a digest.
2225 */
2226TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2227 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2228 .Authorization(TAG_NO_AUTH_REQUIRED)
2229 .RsaEncryptionKey(2048, 65537)
2230 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002231 .Digest(Digest::NONE)
2232 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002233 string message = "Hello World!";
2234
2235 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2236 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2237}
2238
2239/*
2240 * EncryptionOperationsTest.RsaOaepInvalidDigest
2241 *
2242 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
2243 * with a different digest than was used to encrypt.
2244 */
2245TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2246 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2247
2248 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2249 .Authorization(TAG_NO_AUTH_REQUIRED)
2250 .RsaEncryptionKey(1024, 65537)
2251 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002252 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
2253 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002254 string message = "Hello World!";
2255 string ciphertext = EncryptMessage(
2256 message,
2257 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2258
2259 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2260 .Digest(Digest::SHA_2_256)
2261 .Padding(PaddingMode::RSA_OAEP)));
2262 string result;
2263 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2264 EXPECT_EQ(0U, result.size());
2265}
2266
2267/*
2268 * EncryptionOperationsTest.RsaOaepTooLarge
2269 *
2270 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2271 * too-large message.
2272 */
2273TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2274 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2275 .Authorization(TAG_NO_AUTH_REQUIRED)
2276 .RsaEncryptionKey(2048, 65537)
2277 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002278 .Digest(Digest::SHA_2_256)
2279 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002280 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
2281 constexpr size_t oaep_overhead = 2 * digest_size + 2;
2282 string message(2048 / 8 - oaep_overhead + 1, 'a');
2283 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2284 .Padding(PaddingMode::RSA_OAEP)
2285 .Digest(Digest::SHA_2_256)));
2286 string result;
2287 ErrorCode error = Finish(message, &result);
2288 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2289 EXPECT_EQ(0U, result.size());
2290}
2291
2292/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002293 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
2294 *
2295 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
2296 * digests.
2297 */
2298TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
2299 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2300
2301 size_t key_size = 2048; // Need largish key for SHA-512 test.
2302 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2303 .OaepMGFDigest(digests)
2304 .Authorization(TAG_NO_AUTH_REQUIRED)
2305 .RsaEncryptionKey(key_size, 65537)
2306 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002307 .Digest(Digest::SHA_2_256)
2308 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002309
2310 string message = "Hello";
2311
2312 for (auto digest : digests) {
2313 auto params = AuthorizationSetBuilder()
2314 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
2315 .Digest(Digest::SHA_2_256)
2316 .Padding(PaddingMode::RSA_OAEP);
2317 string ciphertext1 = EncryptMessage(message, params);
2318 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2319 EXPECT_EQ(key_size / 8, ciphertext1.size());
2320
2321 string ciphertext2 = EncryptMessage(message, params);
2322 EXPECT_EQ(key_size / 8, ciphertext2.size());
2323
2324 // OAEP randomizes padding so every result should be different (with astronomically high
2325 // probability).
2326 EXPECT_NE(ciphertext1, ciphertext2);
2327
2328 string plaintext1 = DecryptMessage(ciphertext1, params);
2329 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2330 string plaintext2 = DecryptMessage(ciphertext2, params);
2331 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2332
2333 // Decrypting corrupted ciphertext should fail.
2334 size_t offset_to_corrupt = random() % ciphertext1.size();
2335 char corrupt_byte;
2336 do {
2337 corrupt_byte = static_cast<char>(random() % 256);
2338 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2339 ciphertext1[offset_to_corrupt] = corrupt_byte;
2340
2341 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2342 string result;
2343 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2344 EXPECT_EQ(0U, result.size());
2345 }
2346}
2347
2348/*
2349 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
2350 *
2351 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2352 * with incompatible MGF digest.
2353 */
2354TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
2355 ASSERT_EQ(ErrorCode::OK,
2356 GenerateKey(AuthorizationSetBuilder()
2357 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
2358 .Authorization(TAG_NO_AUTH_REQUIRED)
2359 .RsaEncryptionKey(2048, 65537)
2360 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002361 .Digest(Digest::SHA_2_256)
2362 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002363 string message = "Hello World!";
2364
2365 auto params = AuthorizationSetBuilder()
2366 .Padding(PaddingMode::RSA_OAEP)
2367 .Digest(Digest::SHA_2_256)
2368 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
2369 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2370}
2371
2372/*
2373 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
2374 *
2375 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2376 * with unsupported MGF digest.
2377 */
2378TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
2379 ASSERT_EQ(ErrorCode::OK,
2380 GenerateKey(AuthorizationSetBuilder()
2381 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
2382 .Authorization(TAG_NO_AUTH_REQUIRED)
2383 .RsaEncryptionKey(2048, 65537)
2384 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002385 .Digest(Digest::SHA_2_256)
2386 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002387 string message = "Hello World!";
2388
2389 auto params = AuthorizationSetBuilder()
2390 .Padding(PaddingMode::RSA_OAEP)
2391 .Digest(Digest::SHA_2_256)
2392 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
2393 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2394}
2395
2396/*
Selene Huang31ab4042020-04-29 04:22:39 -07002397 * EncryptionOperationsTest.RsaPkcs1Success
2398 *
2399 * Verifies that RSA PKCS encryption/decrypts works.
2400 */
2401TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2402 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2403 .Authorization(TAG_NO_AUTH_REQUIRED)
2404 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002405 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
2406 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002407
2408 string message = "Hello World!";
2409 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2410 string ciphertext1 = EncryptMessage(message, params);
2411 EXPECT_EQ(2048U / 8, ciphertext1.size());
2412
2413 string ciphertext2 = EncryptMessage(message, params);
2414 EXPECT_EQ(2048U / 8, ciphertext2.size());
2415
2416 // PKCS1 v1.5 randomizes padding so every result should be different.
2417 EXPECT_NE(ciphertext1, ciphertext2);
2418
2419 string plaintext = DecryptMessage(ciphertext1, params);
2420 EXPECT_EQ(message, plaintext);
2421
2422 // Decrypting corrupted ciphertext should fail.
2423 size_t offset_to_corrupt = random() % ciphertext1.size();
2424 char corrupt_byte;
2425 do {
2426 corrupt_byte = static_cast<char>(random() % 256);
2427 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2428 ciphertext1[offset_to_corrupt] = corrupt_byte;
2429
2430 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2431 string result;
2432 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2433 EXPECT_EQ(0U, result.size());
2434}
2435
2436/*
2437 * EncryptionOperationsTest.RsaPkcs1TooLarge
2438 *
2439 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2440 */
2441TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2443 .Authorization(TAG_NO_AUTH_REQUIRED)
2444 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002445 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
2446 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002447 string message(2048 / 8 - 10, 'a');
2448
2449 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2450 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2451 string result;
2452 ErrorCode error = Finish(message, &result);
2453 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2454 EXPECT_EQ(0U, result.size());
2455}
2456
2457/*
2458 * EncryptionOperationsTest.EcdsaEncrypt
2459 *
2460 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2461 */
2462TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2464 .Authorization(TAG_NO_AUTH_REQUIRED)
2465 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002466 .Digest(Digest::NONE)
2467 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002468 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2469 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2470 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2471}
2472
2473/*
2474 * EncryptionOperationsTest.HmacEncrypt
2475 *
2476 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2477 */
2478TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2480 .Authorization(TAG_NO_AUTH_REQUIRED)
2481 .HmacKey(128)
2482 .Digest(Digest::SHA_2_256)
2483 .Padding(PaddingMode::NONE)
2484 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2485 auto params = AuthorizationSetBuilder()
2486 .Digest(Digest::SHA_2_256)
2487 .Padding(PaddingMode::NONE)
2488 .Authorization(TAG_MAC_LENGTH, 128);
2489 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2490 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2491}
2492
2493/*
2494 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2495 *
2496 * Verifies that AES ECB mode works.
2497 */
2498TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2500 .Authorization(TAG_NO_AUTH_REQUIRED)
2501 .AesEncryptionKey(128)
2502 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2503 .Padding(PaddingMode::NONE)));
2504
2505 ASSERT_GT(key_blob_.size(), 0U);
2506 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2507
2508 // Two-block message.
2509 string message = "12345678901234567890123456789012";
2510 string ciphertext1 = EncryptMessage(message, params);
2511 EXPECT_EQ(message.size(), ciphertext1.size());
2512
2513 string ciphertext2 = EncryptMessage(string(message), params);
2514 EXPECT_EQ(message.size(), ciphertext2.size());
2515
2516 // ECB is deterministic.
2517 EXPECT_EQ(ciphertext1, ciphertext2);
2518
2519 string plaintext = DecryptMessage(ciphertext1, params);
2520 EXPECT_EQ(message, plaintext);
2521}
2522
2523/*
2524 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2525 *
2526 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2527 */
2528TEST_P(EncryptionOperationsTest, AesWrongMode) {
2529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2530 .Authorization(TAG_NO_AUTH_REQUIRED)
2531 .AesEncryptionKey(128)
2532 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2533 .Padding(PaddingMode::NONE)));
2534
2535 ASSERT_GT(key_blob_.size(), 0U);
2536
2537 // Two-block message.
2538 string message = "12345678901234567890123456789012";
2539 EXPECT_EQ(
2540 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2541 Begin(KeyPurpose::ENCRYPT,
2542 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2543}
2544
2545/*
2546 * EncryptionOperationsTest.AesWrongPurpose
2547 *
2548 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
2549 * specified.
2550 */
2551TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
2552 auto err = GenerateKey(AuthorizationSetBuilder()
2553 .Authorization(TAG_NO_AUTH_REQUIRED)
2554 .AesKey(128)
2555 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
2556 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2557 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2558 .Padding(PaddingMode::NONE));
2559 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
2560 ASSERT_GT(key_blob_.size(), 0U);
2561
2562 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2563 .BlockMode(BlockMode::GCM)
2564 .Padding(PaddingMode::NONE)
2565 .Authorization(TAG_MAC_LENGTH, 128));
2566 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2567
2568 CheckedDeleteKey();
2569
2570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2571 .Authorization(TAG_NO_AUTH_REQUIRED)
2572 .AesKey(128)
2573 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
2574 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2575 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2576 .Padding(PaddingMode::NONE)));
2577
2578 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2579 .BlockMode(BlockMode::GCM)
2580 .Padding(PaddingMode::NONE)
2581 .Authorization(TAG_MAC_LENGTH, 128));
2582 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2583}
2584
2585/*
2586 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2587 *
2588 * Verifies that AES encryption fails in the correct way when provided an input that is not a
2589 * multiple of the block size and no padding is specified.
2590 */
2591TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2592 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2593 .Authorization(TAG_NO_AUTH_REQUIRED)
2594 .AesEncryptionKey(128)
2595 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2596 .Padding(PaddingMode::NONE)));
2597 // Message is slightly shorter than two blocks.
2598 string message(16 * 2 - 1, 'a');
2599
2600 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2601 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2602 string ciphertext;
2603 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2604 EXPECT_EQ(0U, ciphertext.size());
2605}
2606
2607/*
2608 * EncryptionOperationsTest.AesEcbPkcs7Padding
2609 *
2610 * Verifies that AES PKCS7 padding works for any message length.
2611 */
2612TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2613 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2614 .Authorization(TAG_NO_AUTH_REQUIRED)
2615 .AesEncryptionKey(128)
2616 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2617 .Padding(PaddingMode::PKCS7)));
2618
2619 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2620
2621 // Try various message lengths; all should work.
2622 for (size_t i = 0; i < 32; ++i) {
2623 string message(i, 'a');
2624 string ciphertext = EncryptMessage(message, params);
2625 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2626 string plaintext = DecryptMessage(ciphertext, params);
2627 EXPECT_EQ(message, plaintext);
2628 }
2629}
2630
2631/*
2632 * EncryptionOperationsTest.AesEcbWrongPadding
2633 *
2634 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2635 * specified.
2636 */
2637TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
2638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2639 .Authorization(TAG_NO_AUTH_REQUIRED)
2640 .AesEncryptionKey(128)
2641 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2642 .Padding(PaddingMode::NONE)));
2643
2644 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2645
2646 // Try various message lengths; all should fail
2647 for (size_t i = 0; i < 32; ++i) {
2648 string message(i, 'a');
2649 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2650 }
2651}
2652
2653/*
2654 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
2655 *
2656 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
2657 */
2658TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2659 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2660 .Authorization(TAG_NO_AUTH_REQUIRED)
2661 .AesEncryptionKey(128)
2662 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2663 .Padding(PaddingMode::PKCS7)));
2664
2665 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2666
2667 string message = "a";
2668 string ciphertext = EncryptMessage(message, params);
2669 EXPECT_EQ(16U, ciphertext.size());
2670 EXPECT_NE(ciphertext, message);
2671 ++ciphertext[ciphertext.size() / 2];
2672
2673 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2674 string plaintext;
2675 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
2676}
2677
2678vector<uint8_t> CopyIv(const AuthorizationSet& set) {
2679 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002680 EXPECT_TRUE(iv);
2681 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07002682}
2683
2684/*
2685 * EncryptionOperationsTest.AesCtrRoundTripSuccess
2686 *
2687 * Verifies that AES CTR mode works.
2688 */
2689TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2691 .Authorization(TAG_NO_AUTH_REQUIRED)
2692 .AesEncryptionKey(128)
2693 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2694 .Padding(PaddingMode::NONE)));
2695
2696 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2697
2698 string message = "123";
2699 AuthorizationSet out_params;
2700 string ciphertext1 = EncryptMessage(message, params, &out_params);
2701 vector<uint8_t> iv1 = CopyIv(out_params);
2702 EXPECT_EQ(16U, iv1.size());
2703
2704 EXPECT_EQ(message.size(), ciphertext1.size());
2705
2706 out_params.Clear();
2707 string ciphertext2 = EncryptMessage(message, params, &out_params);
2708 vector<uint8_t> iv2 = CopyIv(out_params);
2709 EXPECT_EQ(16U, iv2.size());
2710
2711 // IVs should be random, so ciphertexts should differ.
2712 EXPECT_NE(ciphertext1, ciphertext2);
2713
2714 auto params_iv1 =
2715 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
2716 auto params_iv2 =
2717 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
2718
2719 string plaintext = DecryptMessage(ciphertext1, params_iv1);
2720 EXPECT_EQ(message, plaintext);
2721 plaintext = DecryptMessage(ciphertext2, params_iv2);
2722 EXPECT_EQ(message, plaintext);
2723
2724 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
2725 plaintext = DecryptMessage(ciphertext1, params_iv2);
2726 EXPECT_NE(message, plaintext);
2727 plaintext = DecryptMessage(ciphertext2, params_iv1);
2728 EXPECT_NE(message, plaintext);
2729}
2730
2731/*
2732 * EncryptionOperationsTest.AesIncremental
2733 *
2734 * Verifies that AES works, all modes, when provided data in various size increments.
2735 */
2736TEST_P(EncryptionOperationsTest, AesIncremental) {
2737 auto block_modes = {
2738 BlockMode::ECB,
2739 BlockMode::CBC,
2740 BlockMode::CTR,
2741 BlockMode::GCM,
2742 };
2743
2744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2745 .Authorization(TAG_NO_AUTH_REQUIRED)
2746 .AesEncryptionKey(128)
2747 .BlockMode(block_modes)
2748 .Padding(PaddingMode::NONE)
2749 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2750
2751 for (int increment = 1; increment <= 240; ++increment) {
2752 for (auto block_mode : block_modes) {
2753 string message(240, 'a');
2754 auto params = AuthorizationSetBuilder()
2755 .BlockMode(block_mode)
2756 .Padding(PaddingMode::NONE)
2757 .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
2758
2759 AuthorizationSet output_params;
2760 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
2761
2762 string ciphertext;
2763 int32_t input_consumed;
2764 string to_send;
2765 for (size_t i = 0; i < message.size(); i += increment) {
2766 to_send.append(message.substr(i, increment));
2767 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
2768 EXPECT_EQ(to_send.length(), input_consumed);
2769 to_send = to_send.substr(input_consumed);
2770 EXPECT_EQ(0U, to_send.length());
2771
2772 switch (block_mode) {
2773 case BlockMode::ECB:
2774 case BlockMode::CBC:
2775 // Implementations must take as many blocks as possible, leaving less
2776 // than a block.
2777 EXPECT_LE(to_send.length(), 16U);
2778 break;
2779 case BlockMode::GCM:
2780 case BlockMode::CTR:
2781 // Implementations must always take all the data.
2782 EXPECT_EQ(0U, to_send.length());
2783 break;
2784 }
2785 }
2786 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
2787
2788 switch (block_mode) {
2789 case BlockMode::GCM:
2790 EXPECT_EQ(message.size() + 16, ciphertext.size());
2791 break;
2792 case BlockMode::CTR:
2793 EXPECT_EQ(message.size(), ciphertext.size());
2794 break;
2795 case BlockMode::CBC:
2796 case BlockMode::ECB:
2797 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
2798 break;
2799 }
2800
2801 auto iv = output_params.GetTagValue(TAG_NONCE);
2802 switch (block_mode) {
2803 case BlockMode::CBC:
2804 case BlockMode::GCM:
2805 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002806 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
2807 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
2808 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07002809 break;
2810
2811 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002812 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07002813 break;
2814 }
2815
2816 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
2817 << "Decrypt begin() failed for block mode " << block_mode;
2818
2819 string plaintext;
2820 for (size_t i = 0; i < ciphertext.size(); i += increment) {
2821 to_send.append(ciphertext.substr(i, increment));
2822 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
2823 to_send = to_send.substr(input_consumed);
2824 }
2825 ErrorCode error = Finish(to_send, &plaintext);
2826 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
2827 << " and increment " << increment;
2828 if (error == ErrorCode::OK) {
2829 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
2830 << block_mode << " and increment " << increment;
2831 }
2832 }
2833 }
2834}
2835
2836struct AesCtrSp80038aTestVector {
2837 const char* key;
2838 const char* nonce;
2839 const char* plaintext;
2840 const char* ciphertext;
2841};
2842
2843// These test vectors are taken from
2844// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2845static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2846 // AES-128
2847 {
2848 "2b7e151628aed2a6abf7158809cf4f3c",
2849 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2850 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2851 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2852 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2853 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2854 },
2855 // AES-192
2856 {
2857 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
2858 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2859 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2860 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2861 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
2862 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
2863 },
2864 // AES-256
2865 {
2866 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
2867 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2868 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2869 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2870 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
2871 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
2872 },
2873};
2874
2875/*
2876 * EncryptionOperationsTest.AesCtrSp80038aTestVector
2877 *
2878 * Verifies AES CTR implementation against SP800-38A test vectors.
2879 */
2880TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
2881 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
2882 for (size_t i = 0; i < 3; i++) {
2883 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
2884 const string key = hex2str(test.key);
2885 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
2886 InvalidSizes.end())
2887 continue;
2888 const string nonce = hex2str(test.nonce);
2889 const string plaintext = hex2str(test.plaintext);
2890 const string ciphertext = hex2str(test.ciphertext);
2891 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
2892 }
2893}
2894
2895/*
2896 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
2897 *
2898 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
2899 */
2900TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
2901 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2902 .Authorization(TAG_NO_AUTH_REQUIRED)
2903 .AesEncryptionKey(128)
2904 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2905 .Padding(PaddingMode::PKCS7)));
2906 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2907 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2908}
2909
2910/*
2911 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
2912 *
2913 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
2914 */
2915TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
2916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2917 .Authorization(TAG_NO_AUTH_REQUIRED)
2918 .AesEncryptionKey(128)
2919 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2920 .Authorization(TAG_CALLER_NONCE)
2921 .Padding(PaddingMode::NONE)));
2922
2923 auto params = AuthorizationSetBuilder()
2924 .BlockMode(BlockMode::CTR)
2925 .Padding(PaddingMode::NONE)
2926 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
2927 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
2928
2929 params = AuthorizationSetBuilder()
2930 .BlockMode(BlockMode::CTR)
2931 .Padding(PaddingMode::NONE)
2932 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
2933 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
2934
2935 params = AuthorizationSetBuilder()
2936 .BlockMode(BlockMode::CTR)
2937 .Padding(PaddingMode::NONE)
2938 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
2939 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
2940}
2941
2942/*
2943 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
2944 *
2945 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
2946 */
2947TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
2948 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2949 .Authorization(TAG_NO_AUTH_REQUIRED)
2950 .AesEncryptionKey(128)
2951 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2952 .Padding(PaddingMode::NONE)));
2953 // Two-block message.
2954 string message = "12345678901234567890123456789012";
2955 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
2956 AuthorizationSet out_params;
2957 string ciphertext1 = EncryptMessage(message, params, &out_params);
2958 vector<uint8_t> iv1 = CopyIv(out_params);
2959 EXPECT_EQ(message.size(), ciphertext1.size());
2960
2961 out_params.Clear();
2962
2963 string ciphertext2 = EncryptMessage(message, params, &out_params);
2964 vector<uint8_t> iv2 = CopyIv(out_params);
2965 EXPECT_EQ(message.size(), ciphertext2.size());
2966
2967 // IVs should be random, so ciphertexts should differ.
2968 EXPECT_NE(ciphertext1, ciphertext2);
2969
2970 params.push_back(TAG_NONCE, iv1);
2971 string plaintext = DecryptMessage(ciphertext1, params);
2972 EXPECT_EQ(message, plaintext);
2973}
2974
2975/*
2976 * EncryptionOperationsTest.AesCallerNonce
2977 *
2978 * Verifies that AES caller-provided nonces work correctly.
2979 */
2980TEST_P(EncryptionOperationsTest, AesCallerNonce) {
2981 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2982 .Authorization(TAG_NO_AUTH_REQUIRED)
2983 .AesEncryptionKey(128)
2984 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2985 .Authorization(TAG_CALLER_NONCE)
2986 .Padding(PaddingMode::NONE)));
2987
2988 string message = "12345678901234567890123456789012";
2989
2990 // Don't specify nonce, should get a random one.
2991 AuthorizationSetBuilder params =
2992 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
2993 AuthorizationSet out_params;
2994 string ciphertext = EncryptMessage(message, params, &out_params);
2995 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002996 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07002997
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002998 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07002999 string plaintext = DecryptMessage(ciphertext, params);
3000 EXPECT_EQ(message, plaintext);
3001
3002 // Now specify a nonce, should also work.
3003 params = AuthorizationSetBuilder()
3004 .BlockMode(BlockMode::CBC)
3005 .Padding(PaddingMode::NONE)
3006 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3007 out_params.Clear();
3008 ciphertext = EncryptMessage(message, params, &out_params);
3009
3010 // Decrypt with correct nonce.
3011 plaintext = DecryptMessage(ciphertext, params);
3012 EXPECT_EQ(message, plaintext);
3013
3014 // Try with wrong nonce.
3015 params = AuthorizationSetBuilder()
3016 .BlockMode(BlockMode::CBC)
3017 .Padding(PaddingMode::NONE)
3018 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
3019 plaintext = DecryptMessage(ciphertext, params);
3020 EXPECT_NE(message, plaintext);
3021}
3022
3023/*
3024 * EncryptionOperationsTest.AesCallerNonceProhibited
3025 *
3026 * Verifies that caller-provided nonces are not permitted when not specified in the key
3027 * authorizations.
3028 */
3029TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
3030 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3031 .Authorization(TAG_NO_AUTH_REQUIRED)
3032 .AesEncryptionKey(128)
3033 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3034 .Padding(PaddingMode::NONE)));
3035
3036 string message = "12345678901234567890123456789012";
3037
3038 // Don't specify nonce, should get a random one.
3039 AuthorizationSetBuilder params =
3040 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3041 AuthorizationSet out_params;
3042 string ciphertext = EncryptMessage(message, params, &out_params);
3043 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003044 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003045
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003046 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003047 string plaintext = DecryptMessage(ciphertext, params);
3048 EXPECT_EQ(message, plaintext);
3049
3050 // Now specify a nonce, should fail
3051 params = AuthorizationSetBuilder()
3052 .BlockMode(BlockMode::CBC)
3053 .Padding(PaddingMode::NONE)
3054 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3055 out_params.Clear();
3056 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3057}
3058
3059/*
3060 * EncryptionOperationsTest.AesGcmRoundTripSuccess
3061 *
3062 * Verifies that AES GCM mode works.
3063 */
3064TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3066 .Authorization(TAG_NO_AUTH_REQUIRED)
3067 .AesEncryptionKey(128)
3068 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3069 .Padding(PaddingMode::NONE)
3070 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3071
3072 string aad = "foobar";
3073 string message = "123456789012345678901234567890123456";
3074
3075 auto begin_params = AuthorizationSetBuilder()
3076 .BlockMode(BlockMode::GCM)
3077 .Padding(PaddingMode::NONE)
3078 .Authorization(TAG_MAC_LENGTH, 128);
3079
3080 auto update_params =
3081 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3082
3083 // Encrypt
3084 AuthorizationSet begin_out_params;
3085 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3086 << "Begin encrypt";
3087 string ciphertext;
3088 AuthorizationSet update_out_params;
3089 ASSERT_EQ(ErrorCode::OK, Finish(update_params, message, "", &update_out_params, &ciphertext));
3090
3091 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3092
3093 // Grab nonce
3094 begin_params.push_back(begin_out_params);
3095
3096 // Decrypt.
3097 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3098 string plaintext;
3099 int32_t input_consumed;
3100 ASSERT_EQ(ErrorCode::OK,
3101 Update(update_params, ciphertext, &update_out_params, &plaintext, &input_consumed));
3102 EXPECT_EQ(ciphertext.size(), input_consumed);
3103 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3104 EXPECT_EQ(message.length(), plaintext.length());
3105 EXPECT_EQ(message, plaintext);
3106}
3107
3108/*
3109 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
3110 *
3111 * Verifies that AES GCM mode works, even when there's a long delay
3112 * between operations.
3113 */
3114TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
3115 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3116 .Authorization(TAG_NO_AUTH_REQUIRED)
3117 .AesEncryptionKey(128)
3118 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3119 .Padding(PaddingMode::NONE)
3120 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3121
3122 string aad = "foobar";
3123 string message = "123456789012345678901234567890123456";
3124
3125 auto begin_params = AuthorizationSetBuilder()
3126 .BlockMode(BlockMode::GCM)
3127 .Padding(PaddingMode::NONE)
3128 .Authorization(TAG_MAC_LENGTH, 128);
3129
3130 auto update_params =
3131 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3132
3133 // Encrypt
3134 AuthorizationSet begin_out_params;
3135 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3136 << "Begin encrypt";
3137 string ciphertext;
3138 AuthorizationSet update_out_params;
3139 sleep(5);
3140 ASSERT_EQ(ErrorCode::OK, Finish(update_params, message, "", &update_out_params, &ciphertext));
3141
3142 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3143
3144 // Grab nonce
3145 begin_params.push_back(begin_out_params);
3146
3147 // Decrypt.
3148 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3149 string plaintext;
3150 int32_t input_consumed;
3151 sleep(5);
3152 ASSERT_EQ(ErrorCode::OK,
3153 Update(update_params, ciphertext, &update_out_params, &plaintext, &input_consumed));
3154 EXPECT_EQ(ciphertext.size(), input_consumed);
3155 sleep(5);
3156 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3157 EXPECT_EQ(message.length(), plaintext.length());
3158 EXPECT_EQ(message, plaintext);
3159}
3160
3161/*
3162 * EncryptionOperationsTest.AesGcmDifferentNonces
3163 *
3164 * Verifies that encrypting the same data with different nonces produces different outputs.
3165 */
3166TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
3167 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3168 .Authorization(TAG_NO_AUTH_REQUIRED)
3169 .AesEncryptionKey(128)
3170 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3171 .Padding(PaddingMode::NONE)
3172 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3173 .Authorization(TAG_CALLER_NONCE)));
3174
3175 string aad = "foobar";
3176 string message = "123456789012345678901234567890123456";
3177 string nonce1 = "000000000000";
3178 string nonce2 = "111111111111";
3179 string nonce3 = "222222222222";
3180
3181 string ciphertext1 =
3182 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
3183 string ciphertext2 =
3184 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
3185 string ciphertext3 =
3186 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
3187
3188 ASSERT_NE(ciphertext1, ciphertext2);
3189 ASSERT_NE(ciphertext1, ciphertext3);
3190 ASSERT_NE(ciphertext2, ciphertext3);
3191}
3192
3193/*
3194 * EncryptionOperationsTest.AesGcmTooShortTag
3195 *
3196 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3197 */
3198TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
3199 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3200 .Authorization(TAG_NO_AUTH_REQUIRED)
3201 .AesEncryptionKey(128)
3202 .BlockMode(BlockMode::GCM)
3203 .Padding(PaddingMode::NONE)
3204 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3205 string message = "123456789012345678901234567890123456";
3206 auto params = AuthorizationSetBuilder()
3207 .BlockMode(BlockMode::GCM)
3208 .Padding(PaddingMode::NONE)
3209 .Authorization(TAG_MAC_LENGTH, 96);
3210
3211 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3212}
3213
3214/*
3215 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3216 *
3217 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3218 */
3219TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3221 .Authorization(TAG_NO_AUTH_REQUIRED)
3222 .AesEncryptionKey(128)
3223 .BlockMode(BlockMode::GCM)
3224 .Padding(PaddingMode::NONE)
3225 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3226 string aad = "foobar";
3227 string message = "123456789012345678901234567890123456";
3228 auto params = AuthorizationSetBuilder()
3229 .BlockMode(BlockMode::GCM)
3230 .Padding(PaddingMode::NONE)
3231 .Authorization(TAG_MAC_LENGTH, 128);
3232
3233 auto finish_params =
3234 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3235
3236 // Encrypt
3237 AuthorizationSet begin_out_params;
3238 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3239 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003240 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07003241
3242 AuthorizationSet finish_out_params;
3243 string ciphertext;
3244 EXPECT_EQ(ErrorCode::OK,
3245 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3246
3247 params = AuthorizationSetBuilder()
3248 .Authorizations(begin_out_params)
3249 .BlockMode(BlockMode::GCM)
3250 .Padding(PaddingMode::NONE)
3251 .Authorization(TAG_MAC_LENGTH, 96);
3252
3253 // Decrypt.
3254 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3255}
3256
3257/*
3258 * EncryptionOperationsTest.AesGcmCorruptKey
3259 *
3260 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3261 */
3262TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3263 const uint8_t nonce_bytes[] = {
3264 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3265 };
3266 string nonce = make_string(nonce_bytes);
3267 const uint8_t ciphertext_bytes[] = {
3268 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
3269 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
3270 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
3271 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
3272 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3273 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3274 };
3275 string ciphertext = make_string(ciphertext_bytes);
3276
3277 auto params = AuthorizationSetBuilder()
3278 .BlockMode(BlockMode::GCM)
3279 .Padding(PaddingMode::NONE)
3280 .Authorization(TAG_MAC_LENGTH, 128)
3281 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3282
3283 auto import_params = AuthorizationSetBuilder()
3284 .Authorization(TAG_NO_AUTH_REQUIRED)
3285 .AesEncryptionKey(128)
3286 .BlockMode(BlockMode::GCM)
3287 .Padding(PaddingMode::NONE)
3288 .Authorization(TAG_CALLER_NONCE)
3289 .Authorization(TAG_MIN_MAC_LENGTH, 128);
3290
3291 // Import correct key and decrypt
3292 const uint8_t key_bytes[] = {
3293 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3294 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3295 };
3296 string key = make_string(key_bytes);
3297 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3298 string plaintext = DecryptMessage(ciphertext, params);
3299 CheckedDeleteKey();
3300
3301 // Corrupt key and attempt to decrypt
3302 key[0] = 0;
3303 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3304 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3305 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3306 CheckedDeleteKey();
3307}
3308
3309/*
3310 * EncryptionOperationsTest.AesGcmAadNoData
3311 *
3312 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3313 * encrypt.
3314 */
3315TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3317 .Authorization(TAG_NO_AUTH_REQUIRED)
3318 .AesEncryptionKey(128)
3319 .BlockMode(BlockMode::GCM)
3320 .Padding(PaddingMode::NONE)
3321 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3322
3323 string aad = "1234567890123456";
3324 auto params = AuthorizationSetBuilder()
3325 .BlockMode(BlockMode::GCM)
3326 .Padding(PaddingMode::NONE)
3327 .Authorization(TAG_MAC_LENGTH, 128);
3328
3329 auto finish_params =
3330 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3331
3332 // Encrypt
3333 AuthorizationSet begin_out_params;
3334 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3335 string ciphertext;
3336 AuthorizationSet finish_out_params;
3337 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, "" /* input */, "" /* signature */,
3338 &finish_out_params, &ciphertext));
3339 EXPECT_TRUE(finish_out_params.empty());
3340
3341 // Grab nonce
3342 params.push_back(begin_out_params);
3343
3344 // Decrypt.
3345 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3346 string plaintext;
3347 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, ciphertext, "" /* signature */,
3348 &finish_out_params, &plaintext));
3349
3350 EXPECT_TRUE(finish_out_params.empty());
3351
3352 EXPECT_EQ("", plaintext);
3353}
3354
3355/*
3356 * EncryptionOperationsTest.AesGcmMultiPartAad
3357 *
3358 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
3359 * chunks.
3360 */
3361TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3362 const size_t tag_bits = 128;
3363 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3364 .Authorization(TAG_NO_AUTH_REQUIRED)
3365 .AesEncryptionKey(128)
3366 .BlockMode(BlockMode::GCM)
3367 .Padding(PaddingMode::NONE)
3368 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3369
3370 string message = "123456789012345678901234567890123456";
3371 auto begin_params = AuthorizationSetBuilder()
3372 .BlockMode(BlockMode::GCM)
3373 .Padding(PaddingMode::NONE)
3374 .Authorization(TAG_MAC_LENGTH, tag_bits);
3375 AuthorizationSet begin_out_params;
3376
3377 auto update_params =
3378 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3379
3380 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3381
3382 // No data, AAD only.
3383 string ciphertext;
3384 int32_t input_consumed;
3385 AuthorizationSet update_out_params;
3386 EXPECT_EQ(ErrorCode::OK, Update(update_params, "" /* input */, &update_out_params, &ciphertext,
3387 &input_consumed));
3388 EXPECT_EQ(0U, input_consumed);
3389 EXPECT_EQ(0U, ciphertext.size());
3390 EXPECT_TRUE(update_out_params.empty());
3391
3392 // AAD and data.
3393 EXPECT_EQ(ErrorCode::OK,
3394 Update(update_params, message, &update_out_params, &ciphertext, &input_consumed));
3395 EXPECT_EQ(message.size(), input_consumed);
3396 EXPECT_TRUE(update_out_params.empty());
3397
3398 EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext));
3399 // Expect 128-bit (16-byte) tag appended to ciphertext.
3400 EXPECT_EQ(message.size() + (tag_bits >> 3), ciphertext.size());
3401
3402 // Grab nonce.
3403 begin_params.push_back(begin_out_params);
3404
3405 // Decrypt
3406 update_params =
3407 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6);
3408
3409 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3410 string plaintext;
3411 EXPECT_EQ(ErrorCode::OK, Finish(update_params, ciphertext, "" /* signature */,
3412 &update_out_params, &plaintext));
3413 EXPECT_TRUE(update_out_params.empty());
3414 EXPECT_EQ(message, plaintext);
3415}
3416
3417/*
3418 * EncryptionOperationsTest.AesGcmAadOutOfOrder
3419 *
3420 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3421 */
3422TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3423 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3424 .Authorization(TAG_NO_AUTH_REQUIRED)
3425 .AesEncryptionKey(128)
3426 .BlockMode(BlockMode::GCM)
3427 .Padding(PaddingMode::NONE)
3428 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3429
3430 string message = "123456789012345678901234567890123456";
3431 auto begin_params = AuthorizationSetBuilder()
3432 .BlockMode(BlockMode::GCM)
3433 .Padding(PaddingMode::NONE)
3434 .Authorization(TAG_MAC_LENGTH, 128);
3435 AuthorizationSet begin_out_params;
3436
3437 auto update_params =
3438 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3439
3440 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3441
3442 // No data, AAD only.
3443 string ciphertext;
3444 int32_t input_consumed;
3445 AuthorizationSet update_out_params;
3446 EXPECT_EQ(ErrorCode::OK, Update(update_params, "" /* input */, &update_out_params, &ciphertext,
3447 &input_consumed));
3448 EXPECT_EQ(0U, input_consumed);
3449 EXPECT_EQ(0U, ciphertext.size());
3450 EXPECT_TRUE(update_out_params.empty());
3451
3452 // AAD and data.
3453 EXPECT_EQ(ErrorCode::OK,
3454 Update(update_params, message, &update_out_params, &ciphertext, &input_consumed));
3455 EXPECT_EQ(message.size(), input_consumed);
3456 EXPECT_TRUE(update_out_params.empty());
3457
3458 // More AAD
3459 EXPECT_EQ(ErrorCode::INVALID_TAG,
3460 Update(update_params, "", &update_out_params, &ciphertext, &input_consumed));
3461
Janis Danisevskis24c04702020-12-16 18:28:39 -08003462 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003463}
3464
3465/*
3466 * EncryptionOperationsTest.AesGcmBadAad
3467 *
3468 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3469 */
3470TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3471 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3472 .Authorization(TAG_NO_AUTH_REQUIRED)
3473 .AesEncryptionKey(128)
3474 .BlockMode(BlockMode::GCM)
3475 .Padding(PaddingMode::NONE)
3476 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3477
3478 string message = "12345678901234567890123456789012";
3479 auto begin_params = AuthorizationSetBuilder()
3480 .BlockMode(BlockMode::GCM)
3481 .Padding(PaddingMode::NONE)
3482 .Authorization(TAG_MAC_LENGTH, 128);
3483
3484 auto finish_params =
3485 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3486
3487 // Encrypt
3488 AuthorizationSet begin_out_params;
3489 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3490 string ciphertext;
3491 AuthorizationSet finish_out_params;
3492 EXPECT_EQ(ErrorCode::OK,
3493 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3494
3495 // Grab nonce
3496 begin_params.push_back(begin_out_params);
3497
3498 finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA,
3499 "barfoo" /* Wrong AAD */, (size_t)6);
3500
3501 // Decrypt.
3502 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3503 string plaintext;
3504 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(finish_params, ciphertext, "" /* signature */,
3505 &finish_out_params, &plaintext));
3506}
3507
3508/*
3509 * EncryptionOperationsTest.AesGcmWrongNonce
3510 *
3511 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3512 */
3513TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3515 .Authorization(TAG_NO_AUTH_REQUIRED)
3516 .AesEncryptionKey(128)
3517 .BlockMode(BlockMode::GCM)
3518 .Padding(PaddingMode::NONE)
3519 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3520
3521 string message = "12345678901234567890123456789012";
3522 auto begin_params = AuthorizationSetBuilder()
3523 .BlockMode(BlockMode::GCM)
3524 .Padding(PaddingMode::NONE)
3525 .Authorization(TAG_MAC_LENGTH, 128);
3526
3527 auto finish_params =
3528 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3529
3530 // Encrypt
3531 AuthorizationSet begin_out_params;
3532 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3533 string ciphertext;
3534 AuthorizationSet finish_out_params;
3535 EXPECT_EQ(ErrorCode::OK,
3536 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3537
3538 // Wrong nonce
3539 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
3540
3541 // Decrypt.
3542 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3543 string plaintext;
3544 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(finish_params, ciphertext, "" /* signature */,
3545 &finish_out_params, &plaintext));
3546
3547 // With wrong nonce, should have gotten garbage plaintext (or none).
3548 EXPECT_NE(message, plaintext);
3549}
3550
3551/*
3552 * EncryptionOperationsTest.AesGcmCorruptTag
3553 *
3554 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3555 */
3556TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3558 .Authorization(TAG_NO_AUTH_REQUIRED)
3559 .AesEncryptionKey(128)
3560 .BlockMode(BlockMode::GCM)
3561 .Padding(PaddingMode::NONE)
3562 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3563
3564 string aad = "1234567890123456";
3565 string message = "123456789012345678901234567890123456";
3566
3567 auto params = AuthorizationSetBuilder()
3568 .BlockMode(BlockMode::GCM)
3569 .Padding(PaddingMode::NONE)
3570 .Authorization(TAG_MAC_LENGTH, 128);
3571
3572 auto finish_params =
3573 AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3574
3575 // Encrypt
3576 AuthorizationSet begin_out_params;
3577 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3578 string ciphertext;
3579 AuthorizationSet finish_out_params;
3580 EXPECT_EQ(ErrorCode::OK,
3581 Finish(finish_params, message, "" /* signature */, &finish_out_params, &ciphertext));
3582 EXPECT_TRUE(finish_out_params.empty());
3583
3584 // Corrupt tag
3585 ++(*ciphertext.rbegin());
3586
3587 // Grab nonce
3588 params.push_back(begin_out_params);
3589
3590 // Decrypt.
3591 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3592 string plaintext;
3593 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(finish_params, ciphertext, "" /* signature */,
3594 &finish_out_params, &plaintext));
3595 EXPECT_TRUE(finish_out_params.empty());
3596}
3597
3598/*
3599 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
3600 *
3601 * Verifies that 3DES is basically functional.
3602 */
3603TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
3604 auto auths = AuthorizationSetBuilder()
3605 .TripleDesEncryptionKey(168)
3606 .BlockMode(BlockMode::ECB)
3607 .Authorization(TAG_NO_AUTH_REQUIRED)
3608 .Padding(PaddingMode::NONE);
3609
3610 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
3611 // Two-block message.
3612 string message = "1234567890123456";
3613 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3614 string ciphertext1 = EncryptMessage(message, inParams);
3615 EXPECT_EQ(message.size(), ciphertext1.size());
3616
3617 string ciphertext2 = EncryptMessage(string(message), inParams);
3618 EXPECT_EQ(message.size(), ciphertext2.size());
3619
3620 // ECB is deterministic.
3621 EXPECT_EQ(ciphertext1, ciphertext2);
3622
3623 string plaintext = DecryptMessage(ciphertext1, inParams);
3624 EXPECT_EQ(message, plaintext);
3625}
3626
3627/*
3628 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
3629 *
3630 * Verifies that CBC keys reject ECB usage.
3631 */
3632TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
3633 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3634 .TripleDesEncryptionKey(168)
3635 .BlockMode(BlockMode::CBC)
3636 .Authorization(TAG_NO_AUTH_REQUIRED)
3637 .Padding(PaddingMode::NONE)));
3638
3639 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3640 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3641}
3642
3643/*
3644 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
3645 *
3646 * Tests ECB mode with PKCS#7 padding, various message sizes.
3647 */
3648TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
3649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3650 .TripleDesEncryptionKey(168)
3651 .BlockMode(BlockMode::ECB)
3652 .Authorization(TAG_NO_AUTH_REQUIRED)
3653 .Padding(PaddingMode::PKCS7)));
3654
3655 for (size_t i = 0; i < 32; ++i) {
3656 string message(i, 'a');
3657 auto inParams =
3658 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3659 string ciphertext = EncryptMessage(message, inParams);
3660 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3661 string plaintext = DecryptMessage(ciphertext, inParams);
3662 EXPECT_EQ(message, plaintext);
3663 }
3664}
3665
3666/*
3667 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
3668 *
3669 * Verifies that keys configured for no padding reject PKCS7 padding
3670 */
3671TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
3672 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3673 .TripleDesEncryptionKey(168)
3674 .BlockMode(BlockMode::ECB)
3675 .Authorization(TAG_NO_AUTH_REQUIRED)
3676 .Padding(PaddingMode::NONE)));
3677 for (size_t i = 0; i < 32; ++i) {
3678 auto inParams =
3679 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3680 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3681 }
3682}
3683
3684/*
3685 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
3686 *
3687 * Verifies that corrupted padding is detected.
3688 */
3689TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
3690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3691 .TripleDesEncryptionKey(168)
3692 .BlockMode(BlockMode::ECB)
3693 .Authorization(TAG_NO_AUTH_REQUIRED)
3694 .Padding(PaddingMode::PKCS7)));
3695
3696 string message = "a";
3697 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
3698 EXPECT_EQ(8U, ciphertext.size());
3699 EXPECT_NE(ciphertext, message);
3700 ++ciphertext[ciphertext.size() / 2];
3701
3702 AuthorizationSetBuilder begin_params;
3703 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
3704 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
3705 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3706 string plaintext;
3707 int32_t input_consumed;
3708 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext, &input_consumed));
3709 EXPECT_EQ(ciphertext.size(), input_consumed);
3710 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
3711}
3712
3713struct TripleDesTestVector {
3714 const char* name;
3715 const KeyPurpose purpose;
3716 const BlockMode block_mode;
3717 const PaddingMode padding_mode;
3718 const char* key;
3719 const char* iv;
3720 const char* input;
3721 const char* output;
3722};
3723
3724// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
3725// of the NIST vectors are multiples of the block size.
3726static const TripleDesTestVector kTripleDesTestVectors[] = {
3727 {
3728 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3729 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
3730 "", // IV
3731 "329d86bdf1bc5af4", // input
3732 "d946c2756d78633f", // output
3733 },
3734 {
3735 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3736 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
3737 "", // IV
3738 "6b1540781b01ce1997adae102dbf3c5b", // input
3739 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
3740 },
3741 {
3742 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3743 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
3744 "", // IV
3745 "6daad94ce08acfe7", // input
3746 "660e7d32dcc90e79", // output
3747 },
3748 {
3749 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3750 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
3751 "", // IV
3752 "e9653a0a1f05d31b9acd12d73aa9879d", // input
3753 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
3754 },
3755 {
3756 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3757 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
3758 "43f791134c5647ba", // IV
3759 "dcc153cef81d6f24", // input
3760 "92538bd8af18d3ba", // output
3761 },
3762 {
3763 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3764 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3765 "c2e999cb6249023c", // IV
3766 "c689aee38a301bb316da75db36f110b5", // input
3767 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
3768 },
3769 {
3770 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
3771 PaddingMode::PKCS7,
3772 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3773 "c2e999cb6249023c", // IV
3774 "c689aee38a301bb316da75db36f110b500", // input
3775 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
3776 },
3777 {
3778 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
3779 PaddingMode::PKCS7,
3780 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3781 "c2e999cb6249023c", // IV
3782 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
3783 "c689aee38a301bb316da75db36f110b500", // output
3784 },
3785 {
3786 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3787 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
3788 "41746c7e442d3681", // IV
3789 "c53a7b0ec40600fe", // input
3790 "d4f00eb455de1034", // output
3791 },
3792 {
3793 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3794 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
3795 "3982bc02c3727d45", // IV
3796 "6006f10adef52991fcc777a1238bbb65", // input
3797 "edae09288e9e3bc05746d872b48e3b29", // output
3798 },
3799};
3800
3801/*
3802 * EncryptionOperationsTest.TripleDesTestVector
3803 *
3804 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
3805 */
3806TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
3807 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
3808 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
3809 SCOPED_TRACE(test->name);
3810 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
3811 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
3812 hex2str(test->output));
3813 }
3814}
3815
3816/*
3817 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
3818 *
3819 * Validates CBC mode functionality.
3820 */
3821TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
3822 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3823 .TripleDesEncryptionKey(168)
3824 .BlockMode(BlockMode::CBC)
3825 .Authorization(TAG_NO_AUTH_REQUIRED)
3826 .Padding(PaddingMode::NONE)));
3827
3828 ASSERT_GT(key_blob_.size(), 0U);
3829
3830 // Two-block message.
3831 string message = "1234567890123456";
3832 vector<uint8_t> iv1;
3833 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
3834 EXPECT_EQ(message.size(), ciphertext1.size());
3835
3836 vector<uint8_t> iv2;
3837 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
3838 EXPECT_EQ(message.size(), ciphertext2.size());
3839
3840 // IVs should be random, so ciphertexts should differ.
3841 EXPECT_NE(iv1, iv2);
3842 EXPECT_NE(ciphertext1, ciphertext2);
3843
3844 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
3845 EXPECT_EQ(message, plaintext);
3846}
3847
3848/*
3849 * EncryptionOperationsTest.TripleDesCallerIv
3850 *
3851 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
3852 */
3853TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
3854 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3855 .TripleDesEncryptionKey(168)
3856 .BlockMode(BlockMode::CBC)
3857 .Authorization(TAG_NO_AUTH_REQUIRED)
3858 .Authorization(TAG_CALLER_NONCE)
3859 .Padding(PaddingMode::NONE)));
3860 string message = "1234567890123456";
3861 vector<uint8_t> iv;
3862 // Don't specify IV, should get a random one.
3863 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
3864 EXPECT_EQ(message.size(), ciphertext1.size());
3865 EXPECT_EQ(8U, iv.size());
3866
3867 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
3868 EXPECT_EQ(message, plaintext);
3869
3870 // Now specify an IV, should also work.
3871 iv = AidlBuf("abcdefgh");
3872 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
3873
3874 // Decrypt with correct IV.
3875 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
3876 EXPECT_EQ(message, plaintext);
3877
3878 // Now try with wrong IV.
3879 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
3880 EXPECT_NE(message, plaintext);
3881}
3882
3883/*
3884 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
3885 *
3886 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
3887 */
3888TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
3889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3890 .TripleDesEncryptionKey(168)
3891 .BlockMode(BlockMode::CBC)
3892 .Authorization(TAG_NO_AUTH_REQUIRED)
3893 .Padding(PaddingMode::NONE)));
3894
3895 string message = "12345678901234567890123456789012";
3896 vector<uint8_t> iv;
3897 // Don't specify nonce, should get a random one.
3898 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
3899 EXPECT_EQ(message.size(), ciphertext1.size());
3900 EXPECT_EQ(8U, iv.size());
3901
3902 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
3903 EXPECT_EQ(message, plaintext);
3904
3905 // Now specify a nonce, should fail.
3906 auto input_params = AuthorizationSetBuilder()
3907 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
3908 .BlockMode(BlockMode::CBC)
3909 .Padding(PaddingMode::NONE);
3910 AuthorizationSet output_params;
3911 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
3912 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
3913}
3914
3915/*
3916 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
3917 *
3918 * Verifies that 3DES ECB-only keys do not allow CBC usage.
3919 */
3920TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
3921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3922 .TripleDesEncryptionKey(168)
3923 .BlockMode(BlockMode::ECB)
3924 .Authorization(TAG_NO_AUTH_REQUIRED)
3925 .Padding(PaddingMode::NONE)));
3926 // Two-block message.
3927 string message = "1234567890123456";
3928 auto begin_params =
3929 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3930 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
3931}
3932
3933/*
3934 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
3935 *
3936 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
3937 */
3938TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
3939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3940 .TripleDesEncryptionKey(168)
3941 .BlockMode(BlockMode::CBC)
3942 .Authorization(TAG_NO_AUTH_REQUIRED)
3943 .Padding(PaddingMode::NONE)));
3944 // Message is slightly shorter than two blocks.
3945 string message = "123456789012345";
3946
3947 auto begin_params =
3948 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3949 AuthorizationSet output_params;
3950 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
3951 string ciphertext;
3952 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
3953}
3954
3955/*
3956 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
3957 *
3958 * Verifies that PKCS7 padding works correctly in CBC mode.
3959 */
3960TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
3961 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3962 .TripleDesEncryptionKey(168)
3963 .BlockMode(BlockMode::CBC)
3964 .Authorization(TAG_NO_AUTH_REQUIRED)
3965 .Padding(PaddingMode::PKCS7)));
3966
3967 // Try various message lengths; all should work.
3968 for (size_t i = 0; i < 32; ++i) {
3969 string message(i, 'a');
3970 vector<uint8_t> iv;
3971 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
3972 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3973 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
3974 EXPECT_EQ(message, plaintext);
3975 }
3976}
3977
3978/*
3979 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
3980 *
3981 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
3982 */
3983TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
3984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3985 .TripleDesEncryptionKey(168)
3986 .BlockMode(BlockMode::CBC)
3987 .Authorization(TAG_NO_AUTH_REQUIRED)
3988 .Padding(PaddingMode::NONE)));
3989
3990 // Try various message lengths; all should fail.
3991 for (size_t i = 0; i < 32; ++i) {
3992 auto begin_params =
3993 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
3994 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
3995 }
3996}
3997
3998/*
3999 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4000 *
4001 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4002 */
4003TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4005 .TripleDesEncryptionKey(168)
4006 .BlockMode(BlockMode::CBC)
4007 .Authorization(TAG_NO_AUTH_REQUIRED)
4008 .Padding(PaddingMode::PKCS7)));
4009
4010 string message = "a";
4011 vector<uint8_t> iv;
4012 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4013 EXPECT_EQ(8U, ciphertext.size());
4014 EXPECT_NE(ciphertext, message);
4015 ++ciphertext[ciphertext.size() / 2];
4016
4017 auto begin_params = AuthorizationSetBuilder()
4018 .BlockMode(BlockMode::CBC)
4019 .Padding(PaddingMode::PKCS7)
4020 .Authorization(TAG_NONCE, iv);
4021 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4022 string plaintext;
4023 int32_t input_consumed;
4024 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext, &input_consumed));
4025 EXPECT_EQ(ciphertext.size(), input_consumed);
4026 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4027}
4028
4029/*
4030 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4031 *
4032 * Verifies that 3DES CBC works with many different input sizes.
4033 */
4034TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4036 .TripleDesEncryptionKey(168)
4037 .BlockMode(BlockMode::CBC)
4038 .Authorization(TAG_NO_AUTH_REQUIRED)
4039 .Padding(PaddingMode::NONE)));
4040
4041 int increment = 7;
4042 string message(240, 'a');
4043 AuthorizationSet input_params =
4044 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4045 AuthorizationSet output_params;
4046 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4047
4048 string ciphertext;
4049 int32_t input_consumed;
4050 for (size_t i = 0; i < message.size(); i += increment)
4051 EXPECT_EQ(ErrorCode::OK,
4052 Update(message.substr(i, increment), &ciphertext, &input_consumed));
4053 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4054 EXPECT_EQ(message.size(), ciphertext.size());
4055
4056 // Move TAG_NONCE into input_params
4057 input_params = output_params;
4058 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4059 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4060 output_params.Clear();
4061
4062 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4063 string plaintext;
4064 for (size_t i = 0; i < ciphertext.size(); i += increment)
4065 EXPECT_EQ(ErrorCode::OK,
4066 Update(ciphertext.substr(i, increment), &plaintext, &input_consumed));
4067 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4068 EXPECT_EQ(ciphertext.size(), plaintext.size());
4069 EXPECT_EQ(message, plaintext);
4070}
4071
4072INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4073
4074typedef KeyMintAidlTestBase MaxOperationsTest;
4075
4076/*
4077 * MaxOperationsTest.TestLimitAes
4078 *
4079 * Verifies that the max uses per boot tag works correctly with AES keys.
4080 */
4081TEST_P(MaxOperationsTest, TestLimitAes) {
4082 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4083
4084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4085 .Authorization(TAG_NO_AUTH_REQUIRED)
4086 .AesEncryptionKey(128)
4087 .EcbMode()
4088 .Padding(PaddingMode::NONE)
4089 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4090
4091 string message = "1234567890123456";
4092
4093 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4094
4095 EncryptMessage(message, params);
4096 EncryptMessage(message, params);
4097 EncryptMessage(message, params);
4098
4099 // Fourth time should fail.
4100 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
4101}
4102
4103/*
Qi Wud22ec842020-11-26 13:27:53 +08004104 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07004105 *
4106 * Verifies that the max uses per boot tag works correctly with RSA keys.
4107 */
4108TEST_P(MaxOperationsTest, TestLimitRsa) {
4109 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4110
4111 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4112 .Authorization(TAG_NO_AUTH_REQUIRED)
4113 .RsaSigningKey(1024, 65537)
4114 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004115 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
4116 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004117
4118 string message = "1234567890123456";
4119
4120 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4121
4122 SignMessage(message, params);
4123 SignMessage(message, params);
4124 SignMessage(message, params);
4125
4126 // Fourth time should fail.
4127 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
4128}
4129
4130INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
4131
Qi Wud22ec842020-11-26 13:27:53 +08004132typedef KeyMintAidlTestBase UsageCountLimitTest;
4133
4134/*
Qi Wubeefae42021-01-28 23:16:37 +08004135 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004136 *
Qi Wubeefae42021-01-28 23:16:37 +08004137 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004138 */
Qi Wubeefae42021-01-28 23:16:37 +08004139TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08004140 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4141
4142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4143 .Authorization(TAG_NO_AUTH_REQUIRED)
4144 .AesEncryptionKey(128)
4145 .EcbMode()
4146 .Padding(PaddingMode::NONE)
4147 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
4148
4149 // Check the usage count limit tag appears in the authorizations.
4150 AuthorizationSet auths;
4151 for (auto& entry : key_characteristics_) {
4152 auths.push_back(AuthorizationSet(entry.authorizations));
4153 }
4154 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4155 << "key usage count limit " << 1U << " missing";
4156
4157 string message = "1234567890123456";
4158 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4159
Qi Wubeefae42021-01-28 23:16:37 +08004160 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4161 AuthorizationSet keystore_auths =
4162 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4163
Qi Wud22ec842020-11-26 13:27:53 +08004164 // First usage of AES key should work.
4165 EncryptMessage(message, params);
4166
Qi Wud22ec842020-11-26 13:27:53 +08004167 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4168 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4169 // must be invalidated from secure storage (such as RPMB partition).
4170 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4171 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004172 // Usage count limit tag is enforced by keystore, keymint does nothing.
4173 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08004174 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4175 }
4176}
4177
4178/*
Qi Wubeefae42021-01-28 23:16:37 +08004179 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004180 *
Qi Wubeefae42021-01-28 23:16:37 +08004181 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004182 */
Qi Wubeefae42021-01-28 23:16:37 +08004183TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
4184 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4185
4186 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4187 .Authorization(TAG_NO_AUTH_REQUIRED)
4188 .AesEncryptionKey(128)
4189 .EcbMode()
4190 .Padding(PaddingMode::NONE)
4191 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
4192
4193 // Check the usage count limit tag appears in the authorizations.
4194 AuthorizationSet auths;
4195 for (auto& entry : key_characteristics_) {
4196 auths.push_back(AuthorizationSet(entry.authorizations));
4197 }
4198 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4199 << "key usage count limit " << 3U << " missing";
4200
4201 string message = "1234567890123456";
4202 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4203
4204 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4205 AuthorizationSet keystore_auths =
4206 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4207
4208 EncryptMessage(message, params);
4209 EncryptMessage(message, params);
4210 EncryptMessage(message, params);
4211
4212 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4213 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4214 // must be invalidated from secure storage (such as RPMB partition).
4215 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4216 } else {
4217 // Usage count limit tag is enforced by keystore, keymint does nothing.
4218 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
4219 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4220 }
4221}
4222
4223/*
4224 * UsageCountLimitTest.TestSingleUseRsa
4225 *
4226 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
4227 */
4228TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08004229 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4230
4231 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4232 .Authorization(TAG_NO_AUTH_REQUIRED)
4233 .RsaSigningKey(1024, 65537)
4234 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004235 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4236 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08004237
4238 // Check the usage count limit tag appears in the authorizations.
4239 AuthorizationSet auths;
4240 for (auto& entry : key_characteristics_) {
4241 auths.push_back(AuthorizationSet(entry.authorizations));
4242 }
4243 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4244 << "key usage count limit " << 1U << " missing";
4245
4246 string message = "1234567890123456";
4247 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4248
Qi Wubeefae42021-01-28 23:16:37 +08004249 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4250 AuthorizationSet keystore_auths =
4251 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4252
Qi Wud22ec842020-11-26 13:27:53 +08004253 // First usage of RSA key should work.
4254 SignMessage(message, params);
4255
Qi Wud22ec842020-11-26 13:27:53 +08004256 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4257 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4258 // must be invalidated from secure storage (such as RPMB partition).
4259 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4260 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004261 // Usage count limit tag is enforced by keystore, keymint does nothing.
4262 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
4263 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4264 }
4265}
4266
4267/*
4268 * UsageCountLimitTest.TestLimitUseRsa
4269 *
4270 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
4271 */
4272TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
4273 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4274
4275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4276 .Authorization(TAG_NO_AUTH_REQUIRED)
4277 .RsaSigningKey(1024, 65537)
4278 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004279 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
4280 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08004281
4282 // Check the usage count limit tag appears in the authorizations.
4283 AuthorizationSet auths;
4284 for (auto& entry : key_characteristics_) {
4285 auths.push_back(AuthorizationSet(entry.authorizations));
4286 }
4287 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4288 << "key usage count limit " << 3U << " missing";
4289
4290 string message = "1234567890123456";
4291 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4292
4293 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4294 AuthorizationSet keystore_auths =
4295 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4296
4297 SignMessage(message, params);
4298 SignMessage(message, params);
4299 SignMessage(message, params);
4300
4301 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4302 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4303 // must be invalidated from secure storage (such as RPMB partition).
4304 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4305 } else {
4306 // Usage count limit tag is enforced by keystore, keymint does nothing.
4307 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08004308 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4309 }
4310}
4311
Qi Wu8e727f72021-02-11 02:49:33 +08004312/*
4313 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
4314 *
4315 * Verifies that when rollback resistance is supported by the KeyMint implementation with
4316 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
4317 * in hardware.
4318 */
4319TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
4320 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4321
4322 auto error = GenerateKey(AuthorizationSetBuilder()
4323 .RsaSigningKey(2048, 65537)
4324 .Digest(Digest::NONE)
4325 .Padding(PaddingMode::NONE)
4326 .Authorization(TAG_NO_AUTH_REQUIRED)
4327 .Authorization(TAG_ROLLBACK_RESISTANCE)
4328 .SetDefaultValidity());
4329 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4330
4331 if (error == ErrorCode::OK) {
4332 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
4333 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
4334 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4335 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4336
4337 // The KeyMint should also enforce single use key in hardware when it supports rollback
4338 // resistance.
4339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4340 .Authorization(TAG_NO_AUTH_REQUIRED)
4341 .RsaSigningKey(1024, 65537)
4342 .NoDigestOrPadding()
4343 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4344 .SetDefaultValidity()));
4345
4346 // Check the usage count limit tag appears in the hardware authorizations.
4347 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4348 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4349 << "key usage count limit " << 1U << " missing";
4350
4351 string message = "1234567890123456";
4352 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4353
4354 // First usage of RSA key should work.
4355 SignMessage(message, params);
4356
4357 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4358 // must be invalidated from secure storage (such as RPMB partition).
4359 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4360 }
4361}
4362
Qi Wud22ec842020-11-26 13:27:53 +08004363INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
4364
Selene Huang31ab4042020-04-29 04:22:39 -07004365typedef KeyMintAidlTestBase AddEntropyTest;
4366
4367/*
4368 * AddEntropyTest.AddEntropy
4369 *
4370 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
4371 * is actually added.
4372 */
4373TEST_P(AddEntropyTest, AddEntropy) {
4374 string data = "foo";
4375 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
4376}
4377
4378/*
4379 * AddEntropyTest.AddEmptyEntropy
4380 *
4381 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
4382 */
4383TEST_P(AddEntropyTest, AddEmptyEntropy) {
4384 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
4385}
4386
4387/*
4388 * AddEntropyTest.AddLargeEntropy
4389 *
4390 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
4391 */
4392TEST_P(AddEntropyTest, AddLargeEntropy) {
4393 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
4394}
4395
4396INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
4397
Selene Huang31ab4042020-04-29 04:22:39 -07004398typedef KeyMintAidlTestBase KeyDeletionTest;
4399
4400/**
4401 * KeyDeletionTest.DeleteKey
4402 *
4403 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4404 * valid key blob.
4405 */
4406TEST_P(KeyDeletionTest, DeleteKey) {
4407 auto error = GenerateKey(AuthorizationSetBuilder()
4408 .RsaSigningKey(2048, 65537)
4409 .Digest(Digest::NONE)
4410 .Padding(PaddingMode::NONE)
4411 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004412 .Authorization(TAG_ROLLBACK_RESISTANCE)
4413 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004414 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4415
4416 // Delete must work if rollback protection is implemented
4417 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004418 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004419 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4420
4421 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4422
4423 string message = "12345678901234567890123456789012";
4424 AuthorizationSet begin_out_params;
4425 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4426 Begin(KeyPurpose::SIGN, key_blob_,
4427 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4428 &begin_out_params));
4429 AbortIfNeeded();
4430 key_blob_ = AidlBuf();
4431 }
4432}
4433
4434/**
4435 * KeyDeletionTest.DeleteInvalidKey
4436 *
4437 * This test checks that the HAL excepts invalid key blobs..
4438 */
4439TEST_P(KeyDeletionTest, DeleteInvalidKey) {
4440 // Generate key just to check if rollback protection is implemented
4441 auto error = GenerateKey(AuthorizationSetBuilder()
4442 .RsaSigningKey(2048, 65537)
4443 .Digest(Digest::NONE)
4444 .Padding(PaddingMode::NONE)
4445 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004446 .Authorization(TAG_ROLLBACK_RESISTANCE)
4447 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004448 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4449
4450 // Delete must work if rollback protection is implemented
4451 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004452 AuthorizationSet enforced(SecLevelAuthorizations());
4453 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004454
4455 // Delete the key we don't care about the result at this point.
4456 DeleteKey();
4457
4458 // Now create an invalid key blob and delete it.
4459 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
4460
4461 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4462 }
4463}
4464
4465/**
4466 * KeyDeletionTest.DeleteAllKeys
4467 *
4468 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4469 *
4470 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4471 * FBE/FDE encryption keys, which means that the device will not even boot until after the
4472 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4473 * been provisioned. Use this test only on dedicated testing devices that have no valuable
4474 * credentials stored in Keystore/Keymint.
4475 */
4476TEST_P(KeyDeletionTest, DeleteAllKeys) {
4477 if (!arm_deleteAllKeys) return;
4478 auto error = GenerateKey(AuthorizationSetBuilder()
4479 .RsaSigningKey(2048, 65537)
4480 .Digest(Digest::NONE)
4481 .Padding(PaddingMode::NONE)
4482 .Authorization(TAG_NO_AUTH_REQUIRED)
4483 .Authorization(TAG_ROLLBACK_RESISTANCE));
4484 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4485
4486 // Delete must work if rollback protection is implemented
4487 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004488 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004489 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4490
4491 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4492
4493 string message = "12345678901234567890123456789012";
4494 AuthorizationSet begin_out_params;
4495
4496 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4497 Begin(KeyPurpose::SIGN, key_blob_,
4498 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4499 &begin_out_params));
4500 AbortIfNeeded();
4501 key_blob_ = AidlBuf();
4502 }
4503}
4504
4505INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
4506
4507using UpgradeKeyTest = KeyMintAidlTestBase;
4508
4509/*
4510 * UpgradeKeyTest.UpgradeKey
4511 *
4512 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
4513 */
4514TEST_P(UpgradeKeyTest, UpgradeKey) {
4515 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4516 .AesEncryptionKey(128)
4517 .Padding(PaddingMode::NONE)
4518 .Authorization(TAG_NO_AUTH_REQUIRED)));
4519
4520 auto result = UpgradeKey(key_blob_);
4521
4522 // Key doesn't need upgrading. Should get okay, but no new key blob.
4523 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
4524}
4525
4526INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
4527
4528using ClearOperationsTest = KeyMintAidlTestBase;
4529
4530/*
4531 * ClearSlotsTest.TooManyOperations
4532 *
4533 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
4534 * operations are started without being finished or aborted. Also verifies
4535 * that aborting the operations clears the operations.
4536 *
4537 */
4538TEST_P(ClearOperationsTest, TooManyOperations) {
4539 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4540 .Authorization(TAG_NO_AUTH_REQUIRED)
4541 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004542 .Padding(PaddingMode::NONE)
4543 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004544
4545 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4546 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08004547 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07004548 AuthorizationSet out_params;
4549 ErrorCode result;
4550 size_t i;
4551
4552 for (i = 0; i < max_operations; i++) {
4553 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
4554 if (ErrorCode::OK != result) {
4555 break;
4556 }
4557 }
4558 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
4559 // Try again just in case there's a weird overflow bug
4560 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
4561 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
4562 for (size_t j = 0; j < i; j++) {
4563 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
4564 << "Aboort failed for i = " << j << std::endl;
4565 }
4566 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
4567 AbortIfNeeded();
4568}
4569
4570INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
4571
4572typedef KeyMintAidlTestBase TransportLimitTest;
4573
4574/*
4575 * TransportLimitTest.FinishInput
4576 *
4577 * Verifies that passing input data to finish succeeds as expected.
4578 */
4579TEST_P(TransportLimitTest, LargeFinishInput) {
4580 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4581 .Authorization(TAG_NO_AUTH_REQUIRED)
4582 .AesEncryptionKey(128)
4583 .BlockMode(BlockMode::ECB)
4584 .Padding(PaddingMode::NONE)));
4585
4586 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
4587 auto cipher_params =
4588 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4589
4590 AuthorizationSet out_params;
4591 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
4592
4593 string plain_message = std::string(1 << msg_size, 'x');
4594 string encrypted_message;
4595 auto rc = Finish(plain_message, &encrypted_message);
4596
4597 EXPECT_EQ(ErrorCode::OK, rc);
4598 EXPECT_EQ(plain_message.size(), encrypted_message.size())
4599 << "Encrypt finish returned OK, but did not consume all of the given input";
4600 cipher_params.push_back(out_params);
4601
4602 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
4603
4604 string decrypted_message;
4605 rc = Finish(encrypted_message, &decrypted_message);
4606 EXPECT_EQ(ErrorCode::OK, rc);
4607 EXPECT_EQ(plain_message.size(), decrypted_message.size())
4608 << "Decrypt finish returned OK, did not consume all of the given input";
4609 }
4610}
4611
4612INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
4613
David Zeuthene0c40892021-01-08 12:54:11 -05004614typedef KeyMintAidlTestBase KeyAgreementTest;
4615
4616int CurveToOpenSslCurveName(EcCurve curve) {
4617 switch (curve) {
4618 case EcCurve::P_224:
4619 return NID_secp224r1;
4620 case EcCurve::P_256:
4621 return NID_X9_62_prime256v1;
4622 case EcCurve::P_384:
4623 return NID_secp384r1;
4624 case EcCurve::P_521:
4625 return NID_secp521r1;
4626 }
4627}
4628
4629/*
4630 * KeyAgreementTest.Ecdh
4631 *
4632 * Verifies that ECDH works for all curves
4633 */
4634TEST_P(KeyAgreementTest, Ecdh) {
4635 // Because it's possible to use this API with keys on different curves, we
4636 // check all N^2 combinations where N is the number of supported
4637 // curves.
4638 //
4639 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
4640 // lot more curves we can be smart about things and just pick |otherCurve| so
4641 // it's not |curve| and that way we end up with only 2*N runs
4642 //
4643 for (auto curve : ValidCurves()) {
4644 for (auto localCurve : ValidCurves()) {
4645 // Generate EC key locally (with access to private key material)
4646 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
4647 int curveName = CurveToOpenSslCurveName(localCurve);
4648 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
4649 ASSERT_NE(group, nullptr);
4650 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
4651 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
4652 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
4653 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
4654
4655 // Get encoded form of the public part of the locally generated key...
4656 unsigned char* p = nullptr;
4657 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
4658 ASSERT_GT(encodedPublicKeySize, 0);
4659 vector<uint8_t> encodedPublicKey(
4660 reinterpret_cast<const uint8_t*>(p),
4661 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
4662 OPENSSL_free(p);
4663
4664 // Generate EC key in KeyMint (only access to public key material)
4665 vector<uint8_t> challenge = {0x41, 0x42};
4666 EXPECT_EQ(
4667 ErrorCode::OK,
4668 GenerateKey(AuthorizationSetBuilder()
4669 .Authorization(TAG_NO_AUTH_REQUIRED)
4670 .Authorization(TAG_EC_CURVE, curve)
4671 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4672 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4673 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08004674 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
4675 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05004676 << "Failed to generate key";
4677 ASSERT_GT(cert_chain_.size(), 0);
4678 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4679 ASSERT_NE(kmKeyCert, nullptr);
4680 // Check that keyAgreement (bit 4) is set in KeyUsage
4681 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
4682 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
4683 ASSERT_NE(kmPkey, nullptr);
4684 if (dump_Attestations) {
4685 for (size_t n = 0; n < cert_chain_.size(); n++) {
4686 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
4687 }
4688 }
4689
4690 // Now that we have the two keys, we ask KeyMint to perform ECDH...
4691 if (curve != localCurve) {
4692 // If the keys are using different curves KeyMint should fail with
4693 // ErrorCode:INVALID_ARGUMENT. Check that.
4694 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
4695 string ZabFromKeyMintStr;
4696 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
4697 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
4698 &ZabFromKeyMintStr));
4699
4700 } else {
4701 // Otherwise if the keys are using the same curve, it should work.
4702 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
4703 string ZabFromKeyMintStr;
4704 EXPECT_EQ(ErrorCode::OK,
4705 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
4706 &ZabFromKeyMintStr));
4707 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
4708
4709 // Perform local ECDH between the two keys so we can check if we get the same Zab..
4710 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
4711 ASSERT_NE(ctx, nullptr);
4712 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
4713 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
4714 size_t ZabFromTestLen = 0;
4715 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
4716 vector<uint8_t> ZabFromTest;
4717 ZabFromTest.resize(ZabFromTestLen);
4718 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
4719
4720 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
4721 }
4722
4723 CheckedDeleteKey();
4724 }
4725 }
4726}
4727
4728INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
4729
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00004730typedef KeyMintAidlTestBase EarlyBootKeyTest;
4731
4732TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
4733 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
4734 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
4735
4736 CheckedDeleteKey(&aesKeyData.blob);
4737 CheckedDeleteKey(&hmacKeyData.blob);
4738 CheckedDeleteKey(&rsaKeyData.blob);
4739 CheckedDeleteKey(&ecdsaKeyData.blob);
4740}
4741
4742// This is a more comprenhensive test, but it can only be run on a machine which is still in early
4743// boot stage, which no proper Android device is by the time we can run VTS. To use this,
4744// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
4745// early boot, so you'll have to reboot between runs.
4746TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
4747 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
4748 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
4749 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
4750 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4751 EXPECT_TRUE(
4752 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4753 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4754 EXPECT_TRUE(
4755 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4756
4757 // Should be able to use keys, since early boot has not ended
4758 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
4759 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
4760 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
4761 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
4762
4763 // End early boot
4764 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
4765 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
4766
4767 // Should not be able to use already-created keys.
4768 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
4769 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
4770 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
4771 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
4772
4773 CheckedDeleteKey(&aesKeyData.blob);
4774 CheckedDeleteKey(&hmacKeyData.blob);
4775 CheckedDeleteKey(&rsaKeyData.blob);
4776 CheckedDeleteKey(&ecdsaKeyData.blob);
4777
4778 // Should not be able to create new keys
4779 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
4780 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
4781
4782 CheckedDeleteKey(&aesKeyData.blob);
4783 CheckedDeleteKey(&hmacKeyData.blob);
4784 CheckedDeleteKey(&rsaKeyData.blob);
4785 CheckedDeleteKey(&ecdsaKeyData.blob);
4786}
4787INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
4788
4789typedef KeyMintAidlTestBase UnlockedDeviceRequiredTest;
4790
4791// This may be a problematic test. It can't be run repeatedly without unlocking the device in
4792// between runs... and on most test devices there are no enrolled credentials so it can't be
4793// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
4794// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
4795// a manual test process, which includes unlocking between runs, which is why it's included here.
4796// Well, that and the fact that it's the only test we can do without also making calls into the
4797// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
4798// implications might be, so that may or may not be a solution.
4799TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
4800 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
4801 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
4802
4803 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
4804 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
4805 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
4806 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
4807
4808 ErrorCode rc = GetReturnErrorCode(
4809 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
4810 ASSERT_EQ(ErrorCode::OK, rc);
4811 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
4812 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
4813 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
4814 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
4815
4816 CheckedDeleteKey(&aesKeyData.blob);
4817 CheckedDeleteKey(&hmacKeyData.blob);
4818 CheckedDeleteKey(&rsaKeyData.blob);
4819 CheckedDeleteKey(&ecdsaKeyData.blob);
4820}
4821INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
4822
Janis Danisevskis24c04702020-12-16 18:28:39 -08004823} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07004824
4825int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07004826 std::cout << "Testing ";
4827 auto halInstances =
4828 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
4829 std::cout << "HAL instances:\n";
4830 for (auto& entry : halInstances) {
4831 std::cout << " " << entry << '\n';
4832 }
4833
Selene Huang31ab4042020-04-29 04:22:39 -07004834 ::testing::InitGoogleTest(&argc, argv);
4835 for (int i = 1; i < argc; ++i) {
4836 if (argv[i][0] == '-') {
4837 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07004838 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
4839 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07004840 }
4841 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07004842 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
4843 dump_Attestations = true;
4844 } else {
4845 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07004846 }
4847 }
4848 }
Shawn Willden08a7e432020-12-11 13:05:27 +00004849 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07004850}