blob: 09cdab1a483d306a64add22d24381b607e8da736 [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
David Drysdale4dc01072021-04-01 12:17:35 +010030#include <android/binder_manager.h>
31
32#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080033#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070034
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
38#include "KeyMintAidlTestBase.h"
39
Janis Danisevskis24c04702020-12-16 18:28:39 -080040using aidl::android::hardware::security::keymint::AuthorizationSet;
41using aidl::android::hardware::security::keymint::KeyCharacteristics;
42using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070043
Selene Huang31ab4042020-04-29 04:22:39 -070044namespace std {
45
Janis Danisevskis24c04702020-12-16 18:28:39 -080046using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070047
48template <>
49struct std::equal_to<KeyCharacteristics> {
50 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070051 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070052
Shawn Willden7f424372021-01-10 18:06:50 -070053 // this isn't very efficient. Oh, well.
54 AuthorizationSet a_auths(a.authorizations);
55 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070056
Shawn Willden7f424372021-01-10 18:06:50 -070057 a_auths.Sort();
58 b_auths.Sort();
59
60 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070061 }
62};
63
64} // namespace std
65
Janis Danisevskis24c04702020-12-16 18:28:39 -080066namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000067
Selene Huang31ab4042020-04-29 04:22:39 -070068namespace {
69
70template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000071bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
72 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070073 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080074 if (auto p = authorizationValue(ttag, param)) {
75 return *p == expected_value;
76 }
77 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070078 });
79 return (it != set.end());
80}
81
82template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000083bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070084 auto it = std::find_if(set.begin(), set.end(),
85 [&](const KeyParameter& param) { return param.tag == tag; });
86 return (it != set.end());
87}
88
89constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
90 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
91 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
92 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
93 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
105
106string hex2str(string a) {
107 string b;
108 size_t num = a.size() / 2;
109 b.resize(num);
110 for (size_t i = 0; i < num; i++) {
111 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
112 }
113 return b;
114}
115
116string rsa_key =
117 hex2str("30820275020100300d06092a864886f70d01010105000482025f3082025b"
118 "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
119 "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
120 "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
121 "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
122 "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
123 "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
124 "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
125 "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
126 "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
127 "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
128 "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
129 "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
130 "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
131 "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
132 "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
133 "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
134 "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
135 "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
136 "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
137 "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
138 "3492d6");
139
Selene Huange5727e62021-04-13 22:41:20 -0700140/*
141 * DER-encoded PKCS#8 format RSA key. Generated using:
142 *
143 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
144 */
145string rsa_2048_key =
146 hex2str("308204BD020100300D06092A864886F70D0101010500048204A7308204A3"
147 "0201000282010100BEBC342B56D443B1299F9A6A7056E80A897E318476A5"
148 "A18029E63B2ED739A61791D339F58DC763D9D14911F2EDEC383DEE11F631"
149 "9B44510E7A3ECD9B79B97382E49500ACF8117DC89CAF0E621F77756554A2"
150 "FD4664BFE7AB8B59AB48340DBFA27B93B5A81F6ECDEB02D0759307128DF3"
151 "E3BAD4055C8B840216DFAA5700670E6C5126F0962FCB70FF308F25049164"
152 "CCF76CC2DA66A7DD9A81A714C2809D69186133D29D84568E892B6FFBF319"
153 "9BDB14383EE224407F190358F111A949552ABA6714227D1BD7F6B20DD0CB"
154 "88F9467B719339F33BFF35B3870B3F62204E4286B0948EA348B524544B5F"
155 "9838F29EE643B079EEF8A713B220D7806924CDF7295070C5020301000102"
156 "82010069F377F35F2F584EF075353CCD1CA99738DB3DBC7C7FF35F9366CE"
157 "176DFD1B135AB10030344ABF5FBECF1D4659FDEF1C0FC430834BE1BE3911"
158 "951377BB3D563A2EA9CA8F4AD9C48A8CE6FD516A735C662686C7B4B3C09A"
159 "7B8354133E6F93F790D59EAEB92E84C9A4339302CCE28FDF04CCCAFA7DE3"
160 "F3A827D4F6F7D38E68B0EC6AB706645BF074A4E4090D06FB163124365FD5"
161 "EE7A20D350E9958CC30D91326E1B292E9EF5DB408EC42DAF737D20149704"
162 "D0A678A0FB5B5446863B099228A352D604BA8091A164D01D5AB05397C71E"
163 "AD20BE2A08FC528FE442817809C787FEE4AB97F97B9130D022153EDC6EB6"
164 "CBE7B0F8E3473F2E901209B5DB10F93604DB0102818100E83C0998214941"
165 "EA4F9293F1B77E2E99E6CF305FAF358238E126124FEAF2EB9724B2EA7B78"
166 "E6032343821A80E55D1D88FB12D220C3F41A56142FEC85796D1917F1E8C7"
167 "74F142B67D3D6E7B7E6B4383E94DB5929089DBB346D5BDAB40CC2D96EE04"
168 "09475E175C63BF78CFD744136740838127EA723FF3FE7FA368C1311B4A4E"
169 "0502818100D240FCC0F5D7715CDE21CB2DC86EA146132EA3B06F61FF2AF5"
170 "4BF38473F59DADCCE32B5F4CC32DD0BA6F509347B4B5B1B58C39F95E4798"
171 "CCBB43E83D0119ACF532F359CA743C85199F0286610E200997D731291717"
172 "9AC9B67558773212EC961E8BCE7A3CC809BC5486A96E4B0E6AF394D94E06"
173 "6A0900B7B70E82A44FB30053C102818100AD15DA1CBD6A492B66851BA8C3"
174 "16D38AB700E2CFDDD926A658003513C54BAA152B30021D667D20078F500F"
175 "8AD3E7F3945D74A891ED1A28EAD0FEEAEC8C14A8E834CF46A13D1378C99D"
176 "18940823CFDD27EC5810D59339E0C34198AC638E09C87CBB1B634A9864AE"
177 "9F4D5EB2D53514F67B4CAEC048C8AB849A02E397618F3271350281801FA2"
178 "C1A5331880A92D8F3E281C617108BF38244F16E352E69ED417C7153F9EC3"
179 "18F211839C643DCF8B4DD67CE2AC312E95178D5D952F06B1BF779F491692"
180 "4B70F582A23F11304E02A5E7565AE22A35E74FECC8B6FDC93F92A1A37703"
181 "E4CF0E63783BD02EB716A7ECBBFA606B10B74D01579522E7EF84D91FC522"
182 "292108D902C1028180796FE3825F9DCC85DF22D58690065D93898ACD65C0"
183 "87BEA8DA3A63BF4549B795E2CD0E3BE08CDEBD9FCF1720D9CDC5070D74F4"
184 "0DED8E1102C52152A31B6165F83A6722AECFCC35A493D7634664B888A08D"
185 "3EB034F12EA28BFEE346E205D334827F778B16ED40872BD29FCB36536B6E"
186 "93FFB06778696B4A9D81BB0A9423E63DE5");
187
Selene Huang31ab4042020-04-29 04:22:39 -0700188string ec_256_key =
189 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
190 "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
191 "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
192 "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
193 "1c6eb00083cf3376d11fd44949e0b2183bfe");
194
195string ec_521_key =
196 hex2str("3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
197 "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
198 "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
199 "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
200 "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
201 "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
202 "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
203 "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
204 "D9");
205
206string ec_256_key_rfc5915 =
207 hex2str("308193020100301306072a8648ce3d020106082a8648ce3d030107047930"
208 "770201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
209 "8e8d21c9fa750c1da00a06082a8648ce3d030107a14403420004e2cc561e"
210 "e701da0ad0ef0d176bb0c919d42e79c393fdc1bd6c4010d85cf2cf8e68c9"
211 "05464666f98dad4f01573ba81078b3428570a439ba3229fbc026c550682f");
212
213string ec_256_key_sec1 =
214 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
215 "6b0201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
216 "8e8d21c9fa750c1da14403420004e2cc561ee701da0ad0ef0d176bb0c919"
217 "d42e79c393fdc1bd6c4010d85cf2cf8e68c905464666f98dad4f01573ba8"
218 "1078b3428570a439ba3229fbc026c550682f");
219
220struct RSA_Delete {
221 void operator()(RSA* p) { RSA_free(p); }
222};
223
Selene Huang31ab4042020-04-29 04:22:39 -0700224std::string make_string(const uint8_t* data, size_t length) {
225 return std::string(reinterpret_cast<const char*>(data), length);
226}
227
228template <size_t N>
229std::string make_string(const uint8_t (&a)[N]) {
230 return make_string(a, N);
231}
232
233class AidlBuf : public vector<uint8_t> {
234 typedef vector<uint8_t> super;
235
236 public:
237 AidlBuf() {}
238 AidlBuf(const super& other) : super(other) {}
239 AidlBuf(super&& other) : super(std::move(other)) {}
240 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
241
242 AidlBuf& operator=(const super& other) {
243 super::operator=(other);
244 return *this;
245 }
246
247 AidlBuf& operator=(super&& other) {
248 super::operator=(std::move(other));
249 return *this;
250 }
251
252 AidlBuf& operator=(const string& other) {
253 resize(other.size());
254 for (size_t i = 0; i < other.size(); ++i) {
255 (*this)[i] = static_cast<uint8_t>(other[i]);
256 }
257 return *this;
258 }
259
260 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
261};
262
David Drysdale4dc01072021-04-01 12:17:35 +0100263string device_suffix(const string& name) {
264 size_t pos = name.find('/');
265 if (pos == string::npos) {
266 return name;
267 }
268 return name.substr(pos + 1);
269}
270
271bool matching_rp_instance(const string& km_name,
272 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
273 string km_suffix = device_suffix(km_name);
274
275 vector<string> rp_names =
276 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
277 for (const string& rp_name : rp_names) {
278 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
279 // KeyMint instance, assume they match.
280 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
281 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
282 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
283 return true;
284 }
285 }
286 return false;
287}
288
Selene Huang31ab4042020-04-29 04:22:39 -0700289} // namespace
290
291class NewKeyGenerationTest : public KeyMintAidlTestBase {
292 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700293 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700294 // TODO(swillden): Distinguish which params should be in which auth list.
295
Shawn Willden7f424372021-01-10 18:06:50 -0700296 AuthorizationSet auths;
297 for (auto& entry : keyCharacteristics) {
298 auths.push_back(AuthorizationSet(entry.authorizations));
299 }
Selene Huang31ab4042020-04-29 04:22:39 -0700300
301 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
302 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
303 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
304
Shawn Willden7f424372021-01-10 18:06:50 -0700305 // Verify that App data and ROT are NOT included.
Selene Huang31ab4042020-04-29 04:22:39 -0700306 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
Selene Huang31ab4042020-04-29 04:22:39 -0700307 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
308
309 // Check that some unexpected tags/values are NOT present.
310 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
311 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
312 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
313
Shawn Willden7f424372021-01-10 18:06:50 -0700314 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
315 ASSERT_TRUE(os_ver);
316 EXPECT_EQ(*os_ver, os_version());
Selene Huang31ab4042020-04-29 04:22:39 -0700317
Shawn Willden7f424372021-01-10 18:06:50 -0700318 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
319 ASSERT_TRUE(os_pl);
320 EXPECT_EQ(*os_pl, os_patch_level());
Selene Huang31ab4042020-04-29 04:22:39 -0700321 }
322};
323
324/*
325 * NewKeyGenerationTest.Rsa
326 *
327 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
328 * have correct characteristics.
329 */
330TEST_P(NewKeyGenerationTest, Rsa) {
331 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
332 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700333 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
335 .RsaSigningKey(key_size, 65537)
336 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800337 .Padding(PaddingMode::NONE)
338 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700339 &key_blob, &key_characteristics));
340
341 ASSERT_GT(key_blob.size(), 0U);
342 CheckBaseParams(key_characteristics);
343
Shawn Willden7f424372021-01-10 18:06:50 -0700344 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700345
346 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
347 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
348 << "Key size " << key_size << "missing";
349 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
350
351 CheckedDeleteKey(&key_blob);
352 }
353}
354
355/*
Qi Wud22ec842020-11-26 13:27:53 +0800356 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700357 *
358 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
359 * have correct characteristics.
360 */
361TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700362 auto challenge = "hello";
363 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700364
Selene Huang4f64c222021-04-13 19:54:36 -0700365 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700366 vector<uint8_t> key_blob;
367 vector<KeyCharacteristics> key_characteristics;
368 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
369 .RsaSigningKey(key_size, 65537)
370 .Digest(Digest::NONE)
371 .Padding(PaddingMode::NONE)
372 .AttestationChallenge(challenge)
373 .AttestationApplicationId(app_id)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800374 .Authorization(TAG_NO_AUTH_REQUIRED)
375 .SetDefaultValidity(),
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700376 &key_blob, &key_characteristics));
377
378 ASSERT_GT(key_blob.size(), 0U);
379 CheckBaseParams(key_characteristics);
380
381 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
382
383 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
384 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
385 << "Key size " << key_size << "missing";
386 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
387
Shawn Willden7c130392020-12-21 09:58:22 -0700388 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700389 ASSERT_GT(cert_chain_.size(), 0);
390
391 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
392 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
393 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
394 sw_enforced, hw_enforced, SecLevel(),
395 cert_chain_[0].encodedCertificate));
396
397 CheckedDeleteKey(&key_blob);
398 }
399}
400
401/*
David Drysdale4dc01072021-04-01 12:17:35 +0100402 * NewKeyGenerationTest.RsaWithRpkAttestation
403 *
404 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
405 * that has been generated using an associate IRemotelyProvisionedComponent.
406 */
407TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
408 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
409 // instance.
410 std::shared_ptr<IRemotelyProvisionedComponent> rp;
411 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
412 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
413
414 // Generate a P-256 keypair to use as an attestation key.
415 MacedPublicKey macedPubKey;
416 std::vector<uint8_t> privateKeyBlob;
417 auto status =
418 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
419 ASSERT_TRUE(status.isOk());
420 vector<uint8_t> coseKeyData;
421 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
422
423 AttestationKey attestation_key;
424 attestation_key.keyBlob = std::move(privateKeyBlob);
425 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
426
427 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
428 auto challenge = "hello";
429 auto app_id = "foo";
430
431 vector<uint8_t> key_blob;
432 vector<KeyCharacteristics> key_characteristics;
433 ASSERT_EQ(ErrorCode::OK,
434 GenerateKey(AuthorizationSetBuilder()
435 .RsaSigningKey(key_size, 65537)
436 .Digest(Digest::NONE)
437 .Padding(PaddingMode::NONE)
438 .AttestationChallenge(challenge)
439 .AttestationApplicationId(app_id)
440 .Authorization(TAG_NO_AUTH_REQUIRED)
441 .SetDefaultValidity(),
442 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
443
444 ASSERT_GT(key_blob.size(), 0U);
445 CheckBaseParams(key_characteristics);
446
447 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
448
449 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
450 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
451 << "Key size " << key_size << "missing";
452 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
453
454 // Attestation by itself is not valid (last entry is not self-signed).
455 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
456
457 // The signature over the attested key should correspond to the P256 public key.
458 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
459 ASSERT_TRUE(key_cert.get());
460 EVP_PKEY_Ptr signing_pubkey;
461 p256_pub_key(coseKeyData, &signing_pubkey);
462 ASSERT_TRUE(signing_pubkey.get());
463
464 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
465 << "Verification of attested certificate failed "
466 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
467
468 CheckedDeleteKey(&key_blob);
469 }
470}
471
472/*
Selene Huang4f64c222021-04-13 19:54:36 -0700473 * NewKeyGenerationTest.RsaEncryptionWithAttestation
474 *
475 * Verifies that keymint attestation for RSA encryption keys with challenge and
476 * app id is also successful.
477 */
478TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
479 auto key_size = 2048;
480 auto challenge = "hello";
481 auto app_id = "foo";
482
483 vector<uint8_t> key_blob;
484 vector<KeyCharacteristics> key_characteristics;
485 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
486 .RsaEncryptionKey(key_size, 65537)
487 .Padding(PaddingMode::NONE)
488 .AttestationChallenge(challenge)
489 .AttestationApplicationId(app_id)
490 .Authorization(TAG_NO_AUTH_REQUIRED)
491 .SetDefaultValidity(),
492 &key_blob, &key_characteristics));
493
494 ASSERT_GT(key_blob.size(), 0U);
495 AuthorizationSet auths;
496 for (auto& entry : key_characteristics) {
497 auths.push_back(AuthorizationSet(entry.authorizations));
498 }
499
500 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
501 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
502
503 // Verify that App data and ROT are NOT included.
504 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
505 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
506
507 // Check that some unexpected tags/values are NOT present.
508 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
509 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
510
511 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
512
513 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
514 ASSERT_TRUE(os_ver);
515 EXPECT_EQ(*os_ver, os_version());
516
517 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
518
519 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
520 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
521 << "Key size " << key_size << "missing";
522 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
523
524 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
525 ASSERT_GT(cert_chain_.size(), 0);
526
527 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
528 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
529 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
530 sw_enforced, hw_enforced, SecLevel(),
531 cert_chain_[0].encodedCertificate));
532
533 CheckedDeleteKey(&key_blob);
534}
535
536/*
537 * NewKeyGenerationTest.RsaWithSelfSign
538 *
539 * Verifies that attesting to RSA key generation is successful, and returns
540 * self signed certificate if no challenge is provided. And signing etc
541 * works as expected.
542 */
543TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
544 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
545 vector<uint8_t> key_blob;
546 vector<KeyCharacteristics> key_characteristics;
547 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
548 .RsaSigningKey(key_size, 65537)
549 .Digest(Digest::NONE)
550 .Padding(PaddingMode::NONE)
551 .Authorization(TAG_NO_AUTH_REQUIRED)
552 .SetDefaultValidity(),
553 &key_blob, &key_characteristics));
554
555 ASSERT_GT(key_blob.size(), 0U);
556 CheckBaseParams(key_characteristics);
557
558 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
559
560 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
561 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
562 << "Key size " << key_size << "missing";
563 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
564
565 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
566 ASSERT_EQ(cert_chain_.size(), 1);
567
568 CheckedDeleteKey(&key_blob);
569 }
570}
571
572/*
573 * NewKeyGenerationTest.RsaWithAttestationMissAppId
574 *
575 * Verifies that attesting to RSA checks for missing app ID.
576 */
577TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
578 auto challenge = "hello";
579 vector<uint8_t> key_blob;
580 vector<KeyCharacteristics> key_characteristics;
581
582 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
583 GenerateKey(AuthorizationSetBuilder()
584 .RsaSigningKey(2048, 65537)
585 .Digest(Digest::NONE)
586 .Padding(PaddingMode::NONE)
587 .AttestationChallenge(challenge)
588 .Authorization(TAG_NO_AUTH_REQUIRED)
589 .SetDefaultValidity(),
590 &key_blob, &key_characteristics));
591}
592
593/*
594 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
595 *
596 * Verifies that attesting to RSA ignores app id if challenge is missing.
597 */
598TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
599 auto key_size = 2048;
600 auto app_id = "foo";
601
602 vector<uint8_t> key_blob;
603 vector<KeyCharacteristics> key_characteristics;
604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
605 .RsaSigningKey(key_size, 65537)
606 .Digest(Digest::NONE)
607 .Padding(PaddingMode::NONE)
608 .AttestationApplicationId(app_id)
609 .Authorization(TAG_NO_AUTH_REQUIRED)
610 .SetDefaultValidity(),
611 &key_blob, &key_characteristics));
612
613 ASSERT_GT(key_blob.size(), 0U);
614 CheckBaseParams(key_characteristics);
615
616 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
617
618 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
619 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
620 << "Key size " << key_size << "missing";
621 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
622
623 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
624 ASSERT_EQ(cert_chain_.size(), 1);
625
626 CheckedDeleteKey(&key_blob);
627}
628
629/*
Qi Wud22ec842020-11-26 13:27:53 +0800630 * NewKeyGenerationTest.LimitedUsageRsa
631 *
632 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
633 * resulting keys have correct characteristics.
634 */
635TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
636 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
637 vector<uint8_t> key_blob;
638 vector<KeyCharacteristics> key_characteristics;
639 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
640 .RsaSigningKey(key_size, 65537)
641 .Digest(Digest::NONE)
642 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800643 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
644 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800645 &key_blob, &key_characteristics));
646
647 ASSERT_GT(key_blob.size(), 0U);
648 CheckBaseParams(key_characteristics);
649
650 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
651
652 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
653 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
654 << "Key size " << key_size << "missing";
655 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
656
657 // Check the usage count limit tag appears in the authorizations.
658 AuthorizationSet auths;
659 for (auto& entry : key_characteristics) {
660 auths.push_back(AuthorizationSet(entry.authorizations));
661 }
662 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
663 << "key usage count limit " << 1U << " missing";
664
665 CheckedDeleteKey(&key_blob);
666 }
667}
668
669/*
Qi Wubeefae42021-01-28 23:16:37 +0800670 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
671 *
672 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
673 * resulting keys have correct characteristics and attestation.
674 */
675TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700676 auto challenge = "hello";
677 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +0800678
Selene Huang4f64c222021-04-13 19:54:36 -0700679 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +0800680 vector<uint8_t> key_blob;
681 vector<KeyCharacteristics> key_characteristics;
682 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
683 .RsaSigningKey(key_size, 65537)
684 .Digest(Digest::NONE)
685 .Padding(PaddingMode::NONE)
686 .AttestationChallenge(challenge)
687 .AttestationApplicationId(app_id)
688 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800689 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
690 .SetDefaultValidity(),
Qi Wubeefae42021-01-28 23:16:37 +0800691 &key_blob, &key_characteristics));
692
693 ASSERT_GT(key_blob.size(), 0U);
694 CheckBaseParams(key_characteristics);
695
696 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
697
698 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
699 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
700 << "Key size " << key_size << "missing";
701 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
702
703 // Check the usage count limit tag appears in the authorizations.
704 AuthorizationSet auths;
705 for (auto& entry : key_characteristics) {
706 auths.push_back(AuthorizationSet(entry.authorizations));
707 }
708 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
709 << "key usage count limit " << 1U << " missing";
710
711 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -0700712 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +0800713 ASSERT_GT(cert_chain_.size(), 0);
714
715 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
716 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
717 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
718 sw_enforced, hw_enforced, SecLevel(),
719 cert_chain_[0].encodedCertificate));
720
721 CheckedDeleteKey(&key_blob);
722 }
723}
724
725/*
Selene Huang31ab4042020-04-29 04:22:39 -0700726 * NewKeyGenerationTest.NoInvalidRsaSizes
727 *
728 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
729 */
730TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
731 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
732 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700733 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700734 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
735 GenerateKey(AuthorizationSetBuilder()
736 .RsaSigningKey(key_size, 65537)
737 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800738 .Padding(PaddingMode::NONE)
739 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700740 &key_blob, &key_characteristics));
741 }
742}
743
744/*
745 * NewKeyGenerationTest.RsaNoDefaultSize
746 *
747 * Verifies that failing to specify a key size for RSA key generation returns
748 * UNSUPPORTED_KEY_SIZE.
749 */
750TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
751 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
752 GenerateKey(AuthorizationSetBuilder()
753 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
754 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800755 .SigningKey()
756 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700757}
758
759/*
760 * NewKeyGenerationTest.Ecdsa
761 *
762 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
763 * have correct characteristics.
764 */
765TEST_P(NewKeyGenerationTest, Ecdsa) {
766 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
767 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700768 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
770 .EcdsaSigningKey(key_size)
771 .Digest(Digest::NONE)
772 .SetDefaultValidity(),
773 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -0700774 ASSERT_GT(key_blob.size(), 0U);
775 CheckBaseParams(key_characteristics);
776
Shawn Willden7f424372021-01-10 18:06:50 -0700777 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700778
779 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
780 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
781 << "Key size " << key_size << "missing";
782
783 CheckedDeleteKey(&key_blob);
784 }
785}
786
787/*
Selene Huang4f64c222021-04-13 19:54:36 -0700788 * NewKeyGenerationTest.EcdsaAttestation
789 *
790 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
791 * an attestation will be generated.
792 */
793TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
794 auto challenge = "hello";
795 auto app_id = "foo";
796
797 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
798 vector<uint8_t> key_blob;
799 vector<KeyCharacteristics> key_characteristics;
800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
801 .Authorization(TAG_NO_AUTH_REQUIRED)
802 .EcdsaSigningKey(key_size)
803 .Digest(Digest::NONE)
804 .AttestationChallenge(challenge)
805 .AttestationApplicationId(app_id)
806 .SetDefaultValidity(),
807 &key_blob, &key_characteristics));
808 ASSERT_GT(key_blob.size(), 0U);
809 CheckBaseParams(key_characteristics);
810
811 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
812
813 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
814 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
815 << "Key size " << key_size << "missing";
816
817 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
818 ASSERT_GT(cert_chain_.size(), 0);
819
820 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
821 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
822 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
823 sw_enforced, hw_enforced, SecLevel(),
824 cert_chain_[0].encodedCertificate));
825
826 CheckedDeleteKey(&key_blob);
827 }
828}
829
830/*
831 * NewKeyGenerationTest.EcdsaSelfSignAttestation
832 *
833 * Verifies that if no challenge is provided to an Ecdsa key generation, then
834 * the key will generate a self signed attestation.
835 */
836TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
837 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
838 vector<uint8_t> key_blob;
839 vector<KeyCharacteristics> key_characteristics;
840 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
841 .EcdsaSigningKey(key_size)
842 .Digest(Digest::NONE)
843 .SetDefaultValidity(),
844 &key_blob, &key_characteristics));
845 ASSERT_GT(key_blob.size(), 0U);
846 CheckBaseParams(key_characteristics);
847
848 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
849
850 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
851 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
852 << "Key size " << key_size << "missing";
853
854 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
855 ASSERT_EQ(cert_chain_.size(), 1);
856
857 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
858 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
859
860 CheckedDeleteKey(&key_blob);
861 }
862}
863
864/*
865 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
866 *
867 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
868 * app id must also be provided or else it will fail.
869 */
870TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
871 auto challenge = "hello";
872 vector<uint8_t> key_blob;
873 vector<KeyCharacteristics> key_characteristics;
874
875 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
876 GenerateKey(AuthorizationSetBuilder()
877 .EcdsaSigningKey(EcCurve::P_256)
878 .Digest(Digest::NONE)
879 .AttestationChallenge(challenge)
880 .SetDefaultValidity(),
881 &key_blob, &key_characteristics));
882}
883
884/*
885 * NewKeyGenerationTest.EcdsaIgnoreAppId
886 *
887 * Verifies that if no challenge is provided to the Ecdsa key generation, then
888 * any appid will be ignored, and keymint will generate a self sign certificate.
889 */
890TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
891 auto app_id = "foo";
892
893 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
894 vector<uint8_t> key_blob;
895 vector<KeyCharacteristics> key_characteristics;
896 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
897 .EcdsaSigningKey(key_size)
898 .Digest(Digest::NONE)
899 .AttestationApplicationId(app_id)
900 .SetDefaultValidity(),
901 &key_blob, &key_characteristics));
902
903 ASSERT_GT(key_blob.size(), 0U);
904 CheckBaseParams(key_characteristics);
905
906 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
907
908 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
909 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
910 << "Key size " << key_size << "missing";
911
912 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
913 ASSERT_EQ(cert_chain_.size(), 1);
914
915 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
916 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
917
918 CheckedDeleteKey(&key_blob);
919 }
920}
921
922/*
923 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
924 *
925 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
926 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
927 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
928 * to specify how many following bytes will be used to encode the length.
929 */
930TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
931 auto challenge = "hello";
932 auto key_size = 256;
933 std::vector<uint32_t> app_id_lengths{143, 258};
934
935 for (uint32_t length : app_id_lengths) {
936 const string app_id(length, 'a');
937 vector<uint8_t> key_blob;
938 vector<KeyCharacteristics> key_characteristics;
939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
940 .Authorization(TAG_NO_AUTH_REQUIRED)
941 .EcdsaSigningKey(key_size)
942 .Digest(Digest::NONE)
943 .AttestationChallenge(challenge)
944 .AttestationApplicationId(app_id)
945 .SetDefaultValidity(),
946 &key_blob, &key_characteristics));
947 ASSERT_GT(key_blob.size(), 0U);
948 CheckBaseParams(key_characteristics);
949
950 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
951
952 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
953 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
954 << "Key size " << key_size << "missing";
955
956 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
957 ASSERT_GT(cert_chain_.size(), 0);
958
959 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
960 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
961 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
962 sw_enforced, hw_enforced, SecLevel(),
963 cert_chain_[0].encodedCertificate));
964
965 CheckedDeleteKey(&key_blob);
966 }
967}
968
969/*
Qi Wud22ec842020-11-26 13:27:53 +0800970 * NewKeyGenerationTest.LimitedUsageEcdsa
971 *
972 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
973 * resulting keys have correct characteristics.
974 */
975TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
976 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
977 vector<uint8_t> key_blob;
978 vector<KeyCharacteristics> key_characteristics;
979 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
980 .EcdsaSigningKey(key_size)
981 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800982 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
983 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800984 &key_blob, &key_characteristics));
985
986 ASSERT_GT(key_blob.size(), 0U);
987 CheckBaseParams(key_characteristics);
988
989 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
990
991 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
992 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
993 << "Key size " << key_size << "missing";
994
995 // Check the usage count limit tag appears in the authorizations.
996 AuthorizationSet auths;
997 for (auto& entry : key_characteristics) {
998 auths.push_back(AuthorizationSet(entry.authorizations));
999 }
1000 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1001 << "key usage count limit " << 1U << " missing";
1002
1003 CheckedDeleteKey(&key_blob);
1004 }
1005}
1006
1007/*
Selene Huang31ab4042020-04-29 04:22:39 -07001008 * NewKeyGenerationTest.EcdsaDefaultSize
1009 *
1010 * Verifies that failing to specify a key size for EC key generation returns
1011 * UNSUPPORTED_KEY_SIZE.
1012 */
1013TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1014 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1015 GenerateKey(AuthorizationSetBuilder()
1016 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1017 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001018 .Digest(Digest::NONE)
1019 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001020}
1021
1022/*
1023 * NewKeyGenerationTest.EcdsaInvalidSize
1024 *
1025 * Verifies that specifying an invalid key size for EC key generation returns
1026 * UNSUPPORTED_KEY_SIZE.
1027 */
1028TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1029 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1030 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001031 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001032 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1033 .EcdsaSigningKey(key_size)
1034 .Digest(Digest::NONE)
1035 .SetDefaultValidity(),
1036 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001037 }
1038
Janis Danisevskis164bb872021-02-09 11:30:25 -08001039 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1040 .EcdsaSigningKey(190)
1041 .Digest(Digest::NONE)
1042 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001043}
1044
1045/*
1046 * NewKeyGenerationTest.EcdsaMismatchKeySize
1047 *
1048 * Verifies that specifying mismatched key size and curve for EC key generation returns
1049 * INVALID_ARGUMENT.
1050 */
1051TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1052 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1053
1054 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1055 GenerateKey(AuthorizationSetBuilder()
1056 .EcdsaSigningKey(224)
1057 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001058 .Digest(Digest::NONE)
1059 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001060}
1061
1062/*
1063 * NewKeyGenerationTest.EcdsaAllValidSizes
1064 *
1065 * Verifies that keymint supports all required EC key sizes.
1066 */
1067TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1068 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1069 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001070 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1071 .EcdsaSigningKey(size)
1072 .Digest(Digest::NONE)
1073 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001074 << "Failed to generate size: " << size;
1075 CheckedDeleteKey();
1076 }
1077}
1078
1079/*
1080 * NewKeyGenerationTest.EcdsaInvalidCurves
1081 *
1082 * Verifies that keymint does not support any curve designated as unsupported.
1083 */
1084TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1085 Digest digest;
1086 if (SecLevel() == SecurityLevel::STRONGBOX) {
1087 digest = Digest::SHA_2_256;
1088 } else {
1089 digest = Digest::SHA_2_512;
1090 }
1091 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001092 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1093 .EcdsaSigningKey(curve)
1094 .Digest(digest)
1095 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001096 << "Failed to generate key on curve: " << curve;
1097 CheckedDeleteKey();
1098 }
1099}
1100
1101/*
1102 * NewKeyGenerationTest.Hmac
1103 *
1104 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1105 * characteristics.
1106 */
1107TEST_P(NewKeyGenerationTest, Hmac) {
1108 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1109 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001110 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001111 constexpr size_t key_size = 128;
1112 ASSERT_EQ(ErrorCode::OK,
1113 GenerateKey(
1114 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1115 TAG_MIN_MAC_LENGTH, 128),
1116 &key_blob, &key_characteristics));
1117
1118 ASSERT_GT(key_blob.size(), 0U);
1119 CheckBaseParams(key_characteristics);
1120
Shawn Willden7f424372021-01-10 18:06:50 -07001121 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1122 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1123 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1124 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001125
1126 CheckedDeleteKey(&key_blob);
1127 }
1128}
1129
1130/*
Selene Huang4f64c222021-04-13 19:54:36 -07001131 * NewKeyGenerationTest.HmacNoAttestation
1132 *
1133 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1134 * and app id are provided.
1135 */
1136TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1137 auto challenge = "hello";
1138 auto app_id = "foo";
1139
1140 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1141 vector<uint8_t> key_blob;
1142 vector<KeyCharacteristics> key_characteristics;
1143 constexpr size_t key_size = 128;
1144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1145 .HmacKey(key_size)
1146 .Digest(digest)
1147 .AttestationChallenge(challenge)
1148 .AttestationApplicationId(app_id)
1149 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1150 &key_blob, &key_characteristics));
1151
1152 ASSERT_GT(key_blob.size(), 0U);
1153 ASSERT_EQ(cert_chain_.size(), 0);
1154 CheckBaseParams(key_characteristics);
1155
1156 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1157 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1158 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1159 << "Key size " << key_size << "missing";
1160
1161 CheckedDeleteKey(&key_blob);
1162 }
1163}
1164
1165/*
Qi Wud22ec842020-11-26 13:27:53 +08001166 * NewKeyGenerationTest.LimitedUsageHmac
1167 *
1168 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1169 * resulting keys have correct characteristics.
1170 */
1171TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1172 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1173 vector<uint8_t> key_blob;
1174 vector<KeyCharacteristics> key_characteristics;
1175 constexpr size_t key_size = 128;
1176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1177 .HmacKey(key_size)
1178 .Digest(digest)
1179 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1180 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1181 &key_blob, &key_characteristics));
1182
1183 ASSERT_GT(key_blob.size(), 0U);
1184 CheckBaseParams(key_characteristics);
1185
1186 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1187 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1188 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1189 << "Key size " << key_size << "missing";
1190
1191 // Check the usage count limit tag appears in the authorizations.
1192 AuthorizationSet auths;
1193 for (auto& entry : key_characteristics) {
1194 auths.push_back(AuthorizationSet(entry.authorizations));
1195 }
1196 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1197 << "key usage count limit " << 1U << " missing";
1198
1199 CheckedDeleteKey(&key_blob);
1200 }
1201}
1202
1203/*
Selene Huang31ab4042020-04-29 04:22:39 -07001204 * NewKeyGenerationTest.HmacCheckKeySizes
1205 *
1206 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1207 */
1208TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1209 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1210 if (key_size < 64 || key_size % 8 != 0) {
1211 // To keep this test from being very slow, we only test a random fraction of
1212 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1213 // them, we expect to run ~40 of them in each run.
1214 if (key_size % 8 == 0 || random() % 10 == 0) {
1215 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1216 GenerateKey(AuthorizationSetBuilder()
1217 .HmacKey(key_size)
1218 .Digest(Digest::SHA_2_256)
1219 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1220 << "HMAC key size " << key_size << " invalid";
1221 }
1222 } else {
1223 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1224 .HmacKey(key_size)
1225 .Digest(Digest::SHA_2_256)
1226 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1227 << "Failed to generate HMAC key of size " << key_size;
1228 CheckedDeleteKey();
1229 }
1230 }
1231}
1232
1233/*
1234 * NewKeyGenerationTest.HmacCheckMinMacLengths
1235 *
1236 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1237 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1238 * specific MAC length that failed, so reproducing a failed run will be easy.
1239 */
1240TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1241 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1242 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1243 // To keep this test from being very long, we only test a random fraction of
1244 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1245 // we expect to run ~17 of them in each run.
1246 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1247 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1248 GenerateKey(AuthorizationSetBuilder()
1249 .HmacKey(128)
1250 .Digest(Digest::SHA_2_256)
1251 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1252 << "HMAC min mac length " << min_mac_length << " invalid.";
1253 }
1254 } else {
1255 EXPECT_EQ(ErrorCode::OK,
1256 GenerateKey(AuthorizationSetBuilder()
1257 .HmacKey(128)
1258 .Digest(Digest::SHA_2_256)
1259 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1260 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1261 CheckedDeleteKey();
1262 }
1263 }
1264}
1265
1266/*
1267 * NewKeyGenerationTest.HmacMultipleDigests
1268 *
1269 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1270 */
1271TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1272 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1273
1274 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1275 GenerateKey(AuthorizationSetBuilder()
1276 .HmacKey(128)
1277 .Digest(Digest::SHA1)
1278 .Digest(Digest::SHA_2_256)
1279 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1280}
1281
1282/*
1283 * NewKeyGenerationTest.HmacDigestNone
1284 *
1285 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1286 */
1287TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1288 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1289 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1290 128)));
1291
1292 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1293 GenerateKey(AuthorizationSetBuilder()
1294 .HmacKey(128)
1295 .Digest(Digest::NONE)
1296 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1297}
1298
Selene Huang4f64c222021-04-13 19:54:36 -07001299/*
1300 * NewKeyGenerationTest.AesNoAttestation
1301 *
1302 * Verifies that attestation parameters to AES keys are ignored and generateKey
1303 * will succeed.
1304 */
1305TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1306 auto challenge = "hello";
1307 auto app_id = "foo";
1308
1309 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1310 .Authorization(TAG_NO_AUTH_REQUIRED)
1311 .AesEncryptionKey(128)
1312 .EcbMode()
1313 .Padding(PaddingMode::PKCS7)
1314 .AttestationChallenge(challenge)
1315 .AttestationApplicationId(app_id)));
1316
1317 ASSERT_EQ(cert_chain_.size(), 0);
1318}
1319
1320/*
1321 * NewKeyGenerationTest.TripleDesNoAttestation
1322 *
1323 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1324 * will be successful. No attestation should be generated.
1325 */
1326TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1327 auto challenge = "hello";
1328 auto app_id = "foo";
1329
1330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1331 .TripleDesEncryptionKey(168)
1332 .BlockMode(BlockMode::ECB)
1333 .Authorization(TAG_NO_AUTH_REQUIRED)
1334 .Padding(PaddingMode::NONE)
1335 .AttestationChallenge(challenge)
1336 .AttestationApplicationId(app_id)));
1337 ASSERT_EQ(cert_chain_.size(), 0);
1338}
1339
Selene Huang31ab4042020-04-29 04:22:39 -07001340INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1341
1342typedef KeyMintAidlTestBase SigningOperationsTest;
1343
1344/*
1345 * SigningOperationsTest.RsaSuccess
1346 *
1347 * Verifies that raw RSA signature operations succeed.
1348 */
1349TEST_P(SigningOperationsTest, RsaSuccess) {
1350 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1351 .RsaSigningKey(2048, 65537)
1352 .Digest(Digest::NONE)
1353 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001354 .Authorization(TAG_NO_AUTH_REQUIRED)
1355 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001356 string message = "12345678901234567890123456789012";
1357 string signature = SignMessage(
1358 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1359}
1360
1361/*
1362 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1363 *
Shawn Willden7f424372021-01-10 18:06:50 -07001364 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001365 */
1366TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1368 .Authorization(TAG_NO_AUTH_REQUIRED)
1369 .RsaSigningKey(2048, 65537)
1370 .Digest(Digest::NONE)
1371 .Padding(PaddingMode::NONE)
1372 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001373 .Authorization(TAG_APPLICATION_DATA, "appdata")
1374 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001375 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1376 Begin(KeyPurpose::SIGN,
1377 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1378 AbortIfNeeded();
1379 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1380 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1381 .Digest(Digest::NONE)
1382 .Padding(PaddingMode::NONE)
1383 .Authorization(TAG_APPLICATION_ID, "clientid")));
1384 AbortIfNeeded();
1385 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1386 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1387 .Digest(Digest::NONE)
1388 .Padding(PaddingMode::NONE)
1389 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1390 AbortIfNeeded();
1391 EXPECT_EQ(ErrorCode::OK,
1392 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1393 .Digest(Digest::NONE)
1394 .Padding(PaddingMode::NONE)
1395 .Authorization(TAG_APPLICATION_DATA, "appdata")
1396 .Authorization(TAG_APPLICATION_ID, "clientid")));
1397 AbortIfNeeded();
1398}
1399
1400/*
1401 * SigningOperationsTest.RsaPssSha256Success
1402 *
1403 * Verifies that RSA-PSS signature operations succeed.
1404 */
1405TEST_P(SigningOperationsTest, RsaPssSha256Success) {
1406 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1407 .RsaSigningKey(2048, 65537)
1408 .Digest(Digest::SHA_2_256)
1409 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001410 .Authorization(TAG_NO_AUTH_REQUIRED)
1411 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001412 // Use large message, which won't work without digesting.
1413 string message(1024, 'a');
1414 string signature = SignMessage(
1415 message,
1416 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1417}
1418
1419/*
1420 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1421 *
1422 * Verifies that keymint rejects signature operations that specify a padding mode when the key
1423 * supports only unpadded operations.
1424 */
1425TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1426 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1427 .RsaSigningKey(2048, 65537)
1428 .Digest(Digest::NONE)
1429 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001430 .Padding(PaddingMode::NONE)
1431 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001432 string message = "12345678901234567890123456789012";
1433 string signature;
1434
1435 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1436 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1437 .Digest(Digest::NONE)
1438 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1439}
1440
1441/*
1442 * SigningOperationsTest.NoUserConfirmation
1443 *
1444 * Verifies that keymint rejects signing operations for keys with
1445 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1446 * presented.
1447 */
1448TEST_P(SigningOperationsTest, NoUserConfirmation) {
1449 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001450 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1451 .RsaSigningKey(1024, 65537)
1452 .Digest(Digest::NONE)
1453 .Padding(PaddingMode::NONE)
1454 .Authorization(TAG_NO_AUTH_REQUIRED)
1455 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1456 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001457
1458 const string message = "12345678901234567890123456789012";
1459 EXPECT_EQ(ErrorCode::OK,
1460 Begin(KeyPurpose::SIGN,
1461 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1462 string signature;
1463 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1464}
1465
1466/*
1467 * SigningOperationsTest.RsaPkcs1Sha256Success
1468 *
1469 * Verifies that digested RSA-PKCS1 signature operations succeed.
1470 */
1471TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1472 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1473 .RsaSigningKey(2048, 65537)
1474 .Digest(Digest::SHA_2_256)
1475 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001476 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1477 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001478 string message(1024, 'a');
1479 string signature = SignMessage(message, AuthorizationSetBuilder()
1480 .Digest(Digest::SHA_2_256)
1481 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1482}
1483
1484/*
1485 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1486 *
1487 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1488 */
1489TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1491 .RsaSigningKey(2048, 65537)
1492 .Digest(Digest::NONE)
1493 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001494 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1495 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001496 string message(53, 'a');
1497 string signature = SignMessage(message, AuthorizationSetBuilder()
1498 .Digest(Digest::NONE)
1499 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1500}
1501
1502/*
1503 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1504 *
1505 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1506 * given a too-long message.
1507 */
1508TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1509 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1510 .RsaSigningKey(2048, 65537)
1511 .Digest(Digest::NONE)
1512 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001513 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1514 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001515 string message(257, 'a');
1516
1517 EXPECT_EQ(ErrorCode::OK,
1518 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1519 .Digest(Digest::NONE)
1520 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1521 string signature;
1522 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1523}
1524
1525/*
1526 * SigningOperationsTest.RsaPssSha512TooSmallKey
1527 *
1528 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1529 * used with a key that is too small for the message.
1530 *
1531 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
1532 * keymint specification requires that salt_size == digest_size, so the message will be
1533 * digest_size * 2 +
1534 * 16. Such a message can only be signed by a given key if the key is at least that size. This
1535 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
1536 * for a 1024-bit key.
1537 */
1538TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1539 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1541 .RsaSigningKey(1024, 65537)
1542 .Digest(Digest::SHA_2_512)
1543 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001544 .Padding(PaddingMode::RSA_PSS)
1545 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001546 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1547 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1548 .Digest(Digest::SHA_2_512)
1549 .Padding(PaddingMode::RSA_PSS)));
1550}
1551
1552/*
1553 * SigningOperationsTest.RsaNoPaddingTooLong
1554 *
1555 * Verifies that raw RSA signature operations fail with the correct error code when
1556 * given a too-long message.
1557 */
1558TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1560 .RsaSigningKey(2048, 65537)
1561 .Digest(Digest::NONE)
1562 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001563 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1564 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001565 // One byte too long
1566 string message(2048 / 8 + 1, 'a');
1567 ASSERT_EQ(ErrorCode::OK,
1568 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1569 .Digest(Digest::NONE)
1570 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1571 string result;
1572 ErrorCode finish_error_code = Finish(message, &result);
1573 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1574 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1575
1576 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1577 message = string(128 * 1024, 'a');
1578 ASSERT_EQ(ErrorCode::OK,
1579 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1580 .Digest(Digest::NONE)
1581 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1582 finish_error_code = Finish(message, &result);
1583 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1584 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1585}
1586
1587/*
1588 * SigningOperationsTest.RsaAbort
1589 *
1590 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1591 * test, but the behavior should be algorithm and purpose-independent.
1592 */
1593TEST_P(SigningOperationsTest, RsaAbort) {
1594 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1595 .RsaSigningKey(2048, 65537)
1596 .Digest(Digest::NONE)
1597 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001598 .Padding(PaddingMode::NONE)
1599 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001600
1601 ASSERT_EQ(ErrorCode::OK,
1602 Begin(KeyPurpose::SIGN,
1603 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1604 EXPECT_EQ(ErrorCode::OK, Abort());
1605
1606 // Another abort should fail
1607 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1608
1609 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001610 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001611}
1612
1613/*
1614 * SigningOperationsTest.RsaUnsupportedPadding
1615 *
1616 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1617 * with a padding mode inappropriate for RSA.
1618 */
1619TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1621 .RsaSigningKey(2048, 65537)
1622 .Authorization(TAG_NO_AUTH_REQUIRED)
1623 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001624 .Padding(PaddingMode::PKCS7)
1625 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001626 ASSERT_EQ(
1627 ErrorCode::UNSUPPORTED_PADDING_MODE,
1628 Begin(KeyPurpose::SIGN,
1629 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1630}
1631
1632/*
1633 * SigningOperationsTest.RsaPssNoDigest
1634 *
1635 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
1636 */
1637TEST_P(SigningOperationsTest, RsaNoDigest) {
1638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1639 .RsaSigningKey(2048, 65537)
1640 .Authorization(TAG_NO_AUTH_REQUIRED)
1641 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001642 .Padding(PaddingMode::RSA_PSS)
1643 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001644 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1645 Begin(KeyPurpose::SIGN,
1646 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1647
1648 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1649 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1650}
1651
1652/*
1653 * SigningOperationsTest.RsaPssNoDigest
1654 *
1655 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
1656 * supported in some cases (as validated in other tests), but a mode must be specified.
1657 */
1658TEST_P(SigningOperationsTest, RsaNoPadding) {
1659 // Padding must be specified
1660 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1661 .RsaKey(2048, 65537)
1662 .Authorization(TAG_NO_AUTH_REQUIRED)
1663 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001664 .Digest(Digest::NONE)
1665 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001666 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1667 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1668}
1669
1670/*
1671 * SigningOperationsTest.RsaShortMessage
1672 *
1673 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1674 */
1675TEST_P(SigningOperationsTest, RsaTooShortMessage) {
1676 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1677 .Authorization(TAG_NO_AUTH_REQUIRED)
1678 .RsaSigningKey(2048, 65537)
1679 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001680 .Padding(PaddingMode::NONE)
1681 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001682
1683 // Barely shorter
1684 string message(2048 / 8 - 1, 'a');
1685 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1686
1687 // Much shorter
1688 message = "a";
1689 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1690}
1691
1692/*
1693 * SigningOperationsTest.RsaSignWithEncryptionKey
1694 *
1695 * Verifies that RSA encryption keys cannot be used to sign.
1696 */
1697TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
1698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1699 .Authorization(TAG_NO_AUTH_REQUIRED)
1700 .RsaEncryptionKey(2048, 65537)
1701 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001702 .Padding(PaddingMode::NONE)
1703 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001704 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1705 Begin(KeyPurpose::SIGN,
1706 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1707}
1708
1709/*
1710 * SigningOperationsTest.RsaSignTooLargeMessage
1711 *
1712 * Verifies that attempting a raw signature of a message which is the same length as the key,
1713 * but numerically larger than the public modulus, fails with the correct error.
1714 */
1715TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
1716 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1717 .Authorization(TAG_NO_AUTH_REQUIRED)
1718 .RsaSigningKey(2048, 65537)
1719 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001720 .Padding(PaddingMode::NONE)
1721 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001722
1723 // Largest possible message will always be larger than the public modulus.
1724 string message(2048 / 8, static_cast<char>(0xff));
1725 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1726 .Authorization(TAG_NO_AUTH_REQUIRED)
1727 .Digest(Digest::NONE)
1728 .Padding(PaddingMode::NONE)));
1729 string signature;
1730 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1731}
1732
1733/*
1734 * SigningOperationsTest.EcdsaAllSizesAndHashes
1735 *
1736 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1737 */
1738TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1739 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1740 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1741 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1742 .Authorization(TAG_NO_AUTH_REQUIRED)
1743 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001744 .Digest(digest)
1745 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001746 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1747 << " and digest " << digest;
1748 if (error != ErrorCode::OK) continue;
1749
1750 string message(1024, 'a');
1751 if (digest == Digest::NONE) message.resize(key_size / 8);
1752 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1753 CheckedDeleteKey();
1754 }
1755 }
1756}
1757
1758/*
1759 * SigningOperationsTest.EcdsaAllCurves
1760 *
1761 * Verifies that ECDSA operations succeed with all possible curves.
1762 */
1763TEST_P(SigningOperationsTest, EcdsaAllCurves) {
1764 for (auto curve : ValidCurves()) {
1765 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1766 .Authorization(TAG_NO_AUTH_REQUIRED)
1767 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001768 .Digest(Digest::SHA_2_256)
1769 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001770 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1771 if (error != ErrorCode::OK) continue;
1772
1773 string message(1024, 'a');
1774 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1775 CheckedDeleteKey();
1776 }
1777}
1778
1779/*
1780 * SigningOperationsTest.EcdsaNoDigestHugeData
1781 *
1782 * Verifies that ECDSA operations support very large messages, even without digesting. This
1783 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
1784 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
1785 * the framework.
1786 */
1787TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
1788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1789 .Authorization(TAG_NO_AUTH_REQUIRED)
1790 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001791 .Digest(Digest::NONE)
1792 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001793 string message(1 * 1024, 'a');
1794 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1795}
1796
1797/*
1798 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
1799 *
1800 * Verifies that using an EC key requires the correct app ID/data.
1801 */
1802TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
1803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1804 .Authorization(TAG_NO_AUTH_REQUIRED)
1805 .EcdsaSigningKey(256)
1806 .Digest(Digest::NONE)
1807 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001808 .Authorization(TAG_APPLICATION_DATA, "appdata")
1809 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001810 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1811 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1812 AbortIfNeeded();
1813 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1814 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1815 .Digest(Digest::NONE)
1816 .Authorization(TAG_APPLICATION_ID, "clientid")));
1817 AbortIfNeeded();
1818 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1819 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1820 .Digest(Digest::NONE)
1821 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1822 AbortIfNeeded();
1823 EXPECT_EQ(ErrorCode::OK,
1824 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1825 .Digest(Digest::NONE)
1826 .Authorization(TAG_APPLICATION_DATA, "appdata")
1827 .Authorization(TAG_APPLICATION_ID, "clientid")));
1828 AbortIfNeeded();
1829}
1830
1831/*
1832 * SigningOperationsTest.AesEcbSign
1833 *
1834 * Verifies that attempts to use AES keys to sign fail in the correct way.
1835 */
1836TEST_P(SigningOperationsTest, AesEcbSign) {
1837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1838 .Authorization(TAG_NO_AUTH_REQUIRED)
1839 .SigningKey()
1840 .AesEncryptionKey(128)
1841 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
1842
1843 AuthorizationSet out_params;
1844 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1845 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
1846 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1847 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
1848}
1849
1850/*
1851 * SigningOperationsTest.HmacAllDigests
1852 *
1853 * Verifies that HMAC works with all digests.
1854 */
1855TEST_P(SigningOperationsTest, HmacAllDigests) {
1856 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1858 .Authorization(TAG_NO_AUTH_REQUIRED)
1859 .HmacKey(128)
1860 .Digest(digest)
1861 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1862 << "Failed to create HMAC key with digest " << digest;
1863 string message = "12345678901234567890123456789012";
1864 string signature = MacMessage(message, digest, 160);
1865 EXPECT_EQ(160U / 8U, signature.size())
1866 << "Failed to sign with HMAC key with digest " << digest;
1867 CheckedDeleteKey();
1868 }
1869}
1870
1871/*
1872 * SigningOperationsTest.HmacSha256TooLargeMacLength
1873 *
1874 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
1875 * digest size.
1876 */
1877TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1878 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1879 .Authorization(TAG_NO_AUTH_REQUIRED)
1880 .HmacKey(128)
1881 .Digest(Digest::SHA_2_256)
1882 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1883 AuthorizationSet output_params;
1884 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1885 AuthorizationSetBuilder()
1886 .Digest(Digest::SHA_2_256)
1887 .Authorization(TAG_MAC_LENGTH, 264),
1888 &output_params));
1889}
1890
1891/*
1892 * SigningOperationsTest.HmacSha256TooSmallMacLength
1893 *
1894 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1895 * specified minimum MAC length.
1896 */
1897TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1898 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1899 .Authorization(TAG_NO_AUTH_REQUIRED)
1900 .HmacKey(128)
1901 .Digest(Digest::SHA_2_256)
1902 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1903 AuthorizationSet output_params;
1904 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1905 AuthorizationSetBuilder()
1906 .Digest(Digest::SHA_2_256)
1907 .Authorization(TAG_MAC_LENGTH, 120),
1908 &output_params));
1909}
1910
1911/*
1912 * SigningOperationsTest.HmacRfc4231TestCase3
1913 *
1914 * Validates against the test vectors from RFC 4231 test case 3.
1915 */
1916TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1917 string key(20, 0xaa);
1918 string message(50, 0xdd);
1919 uint8_t sha_224_expected[] = {
1920 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1921 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1922 };
1923 uint8_t sha_256_expected[] = {
1924 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1925 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1926 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1927 };
1928 uint8_t sha_384_expected[] = {
1929 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1930 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1931 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1932 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1933 };
1934 uint8_t sha_512_expected[] = {
1935 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1936 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1937 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1938 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1939 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1940 };
1941
1942 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1943 if (SecLevel() != SecurityLevel::STRONGBOX) {
1944 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1945 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1946 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1947 }
1948}
1949
1950/*
1951 * SigningOperationsTest.HmacRfc4231TestCase5
1952 *
1953 * Validates against the test vectors from RFC 4231 test case 5.
1954 */
1955TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
1956 string key(20, 0x0c);
1957 string message = "Test With Truncation";
1958
1959 uint8_t sha_224_expected[] = {
1960 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1961 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1962 };
1963 uint8_t sha_256_expected[] = {
1964 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1965 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1966 };
1967 uint8_t sha_384_expected[] = {
1968 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1969 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1970 };
1971 uint8_t sha_512_expected[] = {
1972 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1973 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1974 };
1975
1976 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1977 if (SecLevel() != SecurityLevel::STRONGBOX) {
1978 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1979 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1980 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1981 }
1982}
1983
1984INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
1985
1986typedef KeyMintAidlTestBase VerificationOperationsTest;
1987
1988/*
1989 * VerificationOperationsTest.RsaSuccess
1990 *
1991 * Verifies that a simple RSA signature/verification sequence succeeds.
1992 */
1993TEST_P(VerificationOperationsTest, RsaSuccess) {
1994 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1995 .Authorization(TAG_NO_AUTH_REQUIRED)
1996 .RsaSigningKey(2048, 65537)
1997 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001998 .Padding(PaddingMode::NONE)
1999 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002000 string message = "12345678901234567890123456789012";
2001 string signature = SignMessage(
2002 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2003 VerifyMessage(message, signature,
2004 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2005}
2006
2007/*
2008 * VerificationOperationsTest.RsaSuccess
2009 *
2010 * Verifies RSA signature/verification for all padding modes and digests.
2011 */
2012TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2013 auto authorizations = AuthorizationSetBuilder()
2014 .Authorization(TAG_NO_AUTH_REQUIRED)
2015 .RsaSigningKey(2048, 65537)
2016 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2017 .Padding(PaddingMode::NONE)
2018 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002019 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2020 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002021
2022 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2023
2024 string message(128, 'a');
2025 string corrupt_message(message);
2026 ++corrupt_message[corrupt_message.size() / 2];
2027
2028 for (auto padding :
2029 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2030 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2031 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2032 // Digesting only makes sense with padding.
2033 continue;
2034 }
2035
2036 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2037 // PSS requires digesting.
2038 continue;
2039 }
2040
2041 string signature =
2042 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2043 VerifyMessage(message, signature,
2044 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2045
2046 /* TODO(seleneh) add exportkey tests back later when we have decided on
2047 * the new api.
2048 if (digest != Digest::NONE) {
2049 // Verify with OpenSSL.
2050 vector<uint8_t> pubkey;
2051 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2052
2053 const uint8_t* p = pubkey.data();
2054 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2055 ASSERT_TRUE(pkey.get());
2056
2057 EVP_MD_CTX digest_ctx;
2058 EVP_MD_CTX_init(&digest_ctx);
2059 EVP_PKEY_CTX* pkey_ctx;
2060 const EVP_MD* md = openssl_digest(digest);
2061 ASSERT_NE(md, nullptr);
2062 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2063 nullptr, pkey.get()));
2064
2065 switch (padding) {
2066 case PaddingMode::RSA_PSS:
2067 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2068 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2069 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2070 // PKCS1 is the default; don't need to set anything.
2071 break;
2072 default:
2073 FAIL();
2074 break;
2075 }
2076
2077 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2078 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2079 reinterpret_cast<const
2080 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2081 }
2082 */
2083
2084 // Corrupt signature shouldn't verify.
2085 string corrupt_signature(signature);
2086 ++corrupt_signature[corrupt_signature.size() / 2];
2087
2088 EXPECT_EQ(ErrorCode::OK,
2089 Begin(KeyPurpose::VERIFY,
2090 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2091 string result;
2092 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2093
2094 // Corrupt message shouldn't verify
2095 EXPECT_EQ(ErrorCode::OK,
2096 Begin(KeyPurpose::VERIFY,
2097 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2098 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2099 }
2100 }
2101}
2102
2103/*
2104 * VerificationOperationsTest.RsaSuccess
2105 *
2106 * Verifies ECDSA signature/verification for all digests and curves.
2107 */
2108TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2109 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2110
2111 string message = "1234567890";
2112 string corrupt_message = "2234567890";
2113 for (auto curve : ValidCurves()) {
2114 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2115 .Authorization(TAG_NO_AUTH_REQUIRED)
2116 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002117 .Digest(digests)
2118 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002119 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2120 if (error != ErrorCode::OK) {
2121 continue;
2122 }
2123
2124 for (auto digest : digests) {
2125 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2126 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2127
2128 /* TODO(seleneh) add exportkey tests back later when we have decided on
2129 * the new api.
2130
2131 // Verify with OpenSSL
2132 if (digest != Digest::NONE) {
2133 vector<uint8_t> pubkey;
2134 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2135 << curve << ' ' << digest;
2136
2137 const uint8_t* p = pubkey.data();
2138 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2139 ASSERT_TRUE(pkey.get());
2140
2141 EVP_MD_CTX digest_ctx;
2142 EVP_MD_CTX_init(&digest_ctx);
2143 EVP_PKEY_CTX* pkey_ctx;
2144 const EVP_MD* md = openssl_digest(digest);
2145
2146 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2147 nullptr, pkey.get()))
2148 << curve << ' ' << digest;
2149
2150 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2151 message.size()))
2152 << curve << ' ' << digest;
2153
2154 EXPECT_EQ(1,
2155 EVP_DigestVerifyFinal(&digest_ctx,
2156 reinterpret_cast<const
2157 uint8_t*>(signature.data()), signature.size()))
2158 << curve << ' ' << digest;
2159
2160 EVP_MD_CTX_cleanup(&digest_ctx);
2161 }
2162 */
2163 // Corrupt signature shouldn't verify.
2164 string corrupt_signature(signature);
2165 ++corrupt_signature[corrupt_signature.size() / 2];
2166
2167 EXPECT_EQ(ErrorCode::OK,
2168 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2169 << curve << ' ' << digest;
2170
2171 string result;
2172 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2173 << curve << ' ' << digest;
2174
2175 // Corrupt message shouldn't verify
2176 EXPECT_EQ(ErrorCode::OK,
2177 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2178 << curve << ' ' << digest;
2179
2180 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2181 << curve << ' ' << digest;
2182 }
2183
2184 auto rc = DeleteKey();
2185 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2186 }
2187}
2188
2189/*
2190 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2191 *
2192 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2193 */
2194TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2195 string key_material = "HelloThisIsAKey";
2196
2197 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002198 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002199 EXPECT_EQ(ErrorCode::OK,
2200 ImportKey(AuthorizationSetBuilder()
2201 .Authorization(TAG_NO_AUTH_REQUIRED)
2202 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2203 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2204 .Digest(Digest::SHA_2_256)
2205 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2206 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2207 EXPECT_EQ(ErrorCode::OK,
2208 ImportKey(AuthorizationSetBuilder()
2209 .Authorization(TAG_NO_AUTH_REQUIRED)
2210 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2211 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2212 .Digest(Digest::SHA_2_256)
2213 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2214 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2215
2216 string message = "This is a message.";
2217 string signature = SignMessage(
2218 signing_key, message,
2219 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2220
2221 // Signing key should not work.
2222 AuthorizationSet out_params;
2223 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2224 Begin(KeyPurpose::VERIFY, signing_key,
2225 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2226
2227 // Verification key should work.
2228 VerifyMessage(verification_key, message, signature,
2229 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2230
2231 CheckedDeleteKey(&signing_key);
2232 CheckedDeleteKey(&verification_key);
2233}
2234
2235INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2236
2237typedef KeyMintAidlTestBase ExportKeyTest;
2238
2239/*
2240 * ExportKeyTest.RsaUnsupportedKeyFormat
2241 *
2242 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2243 */
2244// TODO(seleneh) add ExportKey to GenerateKey
2245// check result
2246
2247class ImportKeyTest : public KeyMintAidlTestBase {
2248 public:
2249 template <TagType tag_type, Tag tag, typename ValueT>
2250 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2251 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002252 for (auto& entry : key_characteristics_) {
2253 if (entry.securityLevel == SecLevel()) {
2254 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2255 << "Tag " << tag << " with value " << expected
2256 << " not found at security level" << entry.securityLevel;
2257 } else {
2258 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2259 << "Tag " << tag << " found at security level " << entry.securityLevel;
2260 }
Selene Huang31ab4042020-04-29 04:22:39 -07002261 }
2262 }
2263
2264 void CheckOrigin() {
2265 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002266 // Origin isn't a crypto param, but it always lives with them.
2267 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002268 }
2269};
2270
2271/*
2272 * ImportKeyTest.RsaSuccess
2273 *
2274 * Verifies that importing and using an RSA key pair works correctly.
2275 */
2276TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002277 uint32_t key_size;
2278 string key;
2279
2280 if (SecLevel() == SecurityLevel::STRONGBOX) {
2281 key_size = 2048;
2282 key = rsa_2048_key;
2283 } else {
2284 key_size = 1024;
2285 key = rsa_key;
2286 }
2287
Selene Huang31ab4042020-04-29 04:22:39 -07002288 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2289 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07002290 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07002291 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002292 .Padding(PaddingMode::RSA_PSS)
2293 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07002294 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07002295
2296 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07002297 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002298 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2299 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2300 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2301 CheckOrigin();
2302
2303 string message(1024 / 8, 'a');
2304 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2305 string signature = SignMessage(message, params);
2306 VerifyMessage(message, signature, params);
2307}
2308
2309/*
2310 * ImportKeyTest.RsaKeySizeMismatch
2311 *
2312 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2313 * correct way.
2314 */
2315TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2316 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2317 ImportKey(AuthorizationSetBuilder()
2318 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2319 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002320 .Padding(PaddingMode::NONE)
2321 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002322 KeyFormat::PKCS8, rsa_key));
2323}
2324
2325/*
2326 * ImportKeyTest.RsaPublicExponentMismatch
2327 *
2328 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
2329 * fails in the correct way.
2330 */
2331TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2332 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2333 ImportKey(AuthorizationSetBuilder()
2334 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2335 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002336 .Padding(PaddingMode::NONE)
2337 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002338 KeyFormat::PKCS8, rsa_key));
2339}
2340
2341/*
2342 * ImportKeyTest.EcdsaSuccess
2343 *
2344 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2345 */
2346TEST_P(ImportKeyTest, EcdsaSuccess) {
2347 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2348 .Authorization(TAG_NO_AUTH_REQUIRED)
2349 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002350 .Digest(Digest::SHA_2_256)
2351 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002352 KeyFormat::PKCS8, ec_256_key));
2353
2354 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2355 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2356 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2357 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2358
2359 CheckOrigin();
2360
2361 string message(32, 'a');
2362 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2363 string signature = SignMessage(message, params);
2364 VerifyMessage(message, signature, params);
2365}
2366
2367/*
2368 * ImportKeyTest.EcdsaP256RFC5915Success
2369 *
2370 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
2371 * correctly.
2372 */
2373TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
2374 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2375 .Authorization(TAG_NO_AUTH_REQUIRED)
2376 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002377 .Digest(Digest::SHA_2_256)
2378 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002379 KeyFormat::PKCS8, ec_256_key_rfc5915));
2380
2381 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2382 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2383 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2384 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2385
2386 CheckOrigin();
2387
2388 string message(32, 'a');
2389 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2390 string signature = SignMessage(message, params);
2391 VerifyMessage(message, signature, params);
2392}
2393
2394/*
2395 * ImportKeyTest.EcdsaP256SEC1Success
2396 *
2397 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
2398 */
2399TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
2400 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2401 .Authorization(TAG_NO_AUTH_REQUIRED)
2402 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002403 .Digest(Digest::SHA_2_256)
2404 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002405 KeyFormat::PKCS8, ec_256_key_sec1));
2406
2407 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2408 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2409 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2410 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2411
2412 CheckOrigin();
2413
2414 string message(32, 'a');
2415 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2416 string signature = SignMessage(message, params);
2417 VerifyMessage(message, signature, params);
2418}
2419
2420/*
2421 * ImportKeyTest.Ecdsa521Success
2422 *
2423 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2424 */
2425TEST_P(ImportKeyTest, Ecdsa521Success) {
2426 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2427 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2428 .Authorization(TAG_NO_AUTH_REQUIRED)
2429 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002430 .Digest(Digest::SHA_2_256)
2431 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002432 KeyFormat::PKCS8, ec_521_key));
2433
2434 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2435 CheckCryptoParam(TAG_KEY_SIZE, 521U);
2436 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2437 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2438 CheckOrigin();
2439
2440 string message(32, 'a');
2441 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2442 string signature = SignMessage(message, params);
2443 VerifyMessage(message, signature, params);
2444}
2445
2446/*
2447 * ImportKeyTest.EcdsaSizeMismatch
2448 *
2449 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2450 * correct way.
2451 */
2452TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2453 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2454 ImportKey(AuthorizationSetBuilder()
2455 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002456 .Digest(Digest::NONE)
2457 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002458 KeyFormat::PKCS8, ec_256_key));
2459}
2460
2461/*
2462 * ImportKeyTest.EcdsaCurveMismatch
2463 *
2464 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
2465 * the correct way.
2466 */
2467TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2468 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2469 ImportKey(AuthorizationSetBuilder()
2470 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002471 .Digest(Digest::NONE)
2472 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002473 KeyFormat::PKCS8, ec_256_key));
2474}
2475
2476/*
2477 * ImportKeyTest.AesSuccess
2478 *
2479 * Verifies that importing and using an AES key works.
2480 */
2481TEST_P(ImportKeyTest, AesSuccess) {
2482 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2483 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2484 .Authorization(TAG_NO_AUTH_REQUIRED)
2485 .AesEncryptionKey(key.size() * 8)
2486 .EcbMode()
2487 .Padding(PaddingMode::PKCS7),
2488 KeyFormat::RAW, key));
2489
2490 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2491 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2492 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2493 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2494 CheckOrigin();
2495
2496 string message = "Hello World!";
2497 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2498 string ciphertext = EncryptMessage(message, params);
2499 string plaintext = DecryptMessage(ciphertext, params);
2500 EXPECT_EQ(message, plaintext);
2501}
2502
2503/*
2504 * ImportKeyTest.AesSuccess
2505 *
2506 * Verifies that importing and using an HMAC key works.
2507 */
2508TEST_P(ImportKeyTest, HmacKeySuccess) {
2509 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2510 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2511 .Authorization(TAG_NO_AUTH_REQUIRED)
2512 .HmacKey(key.size() * 8)
2513 .Digest(Digest::SHA_2_256)
2514 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2515 KeyFormat::RAW, key));
2516
2517 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2518 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2519 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2520 CheckOrigin();
2521
2522 string message = "Hello World!";
2523 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2524 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2525}
2526
2527INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
2528
2529auto wrapped_key = hex2str(
2530 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
2531 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
2532 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
2533 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
2534 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
2535 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
2536 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
2537 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
2538 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
2539
2540auto wrapped_key_masked = hex2str(
2541 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
2542 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
2543 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
2544 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
2545 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
2546 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
2547 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
2548 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
2549 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
2550
2551auto wrapping_key = hex2str(
2552 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
2553 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
2554 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
2555 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
2556 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
2557 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
2558 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
2559 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
2560 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
2561 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
2562 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
2563 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
2564 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
2565 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
2566 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
2567 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
2568 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
2569 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
2570 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
2571 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
2572 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
2573 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
2574 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
2575 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
2576 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
2577 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
2578 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
2579 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
2580 "f27ba61be6ad02dfddda8f4e6822");
2581
2582string zero_masking_key =
2583 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
2584string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
2585
2586class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
2587
2588TEST_P(ImportWrappedKeyTest, Success) {
2589 auto wrapping_key_desc = AuthorizationSetBuilder()
2590 .RsaEncryptionKey(2048, 65537)
2591 .Digest(Digest::SHA_2_256)
2592 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002593 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2594 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002595
2596 ASSERT_EQ(ErrorCode::OK,
2597 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
2598 AuthorizationSetBuilder()
2599 .Digest(Digest::SHA_2_256)
2600 .Padding(PaddingMode::RSA_OAEP)));
2601
2602 string message = "Hello World!";
2603 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2604 string ciphertext = EncryptMessage(message, params);
2605 string plaintext = DecryptMessage(ciphertext, params);
2606 EXPECT_EQ(message, plaintext);
2607}
2608
2609TEST_P(ImportWrappedKeyTest, SuccessMasked) {
2610 auto wrapping_key_desc = AuthorizationSetBuilder()
2611 .RsaEncryptionKey(2048, 65537)
2612 .Digest(Digest::SHA_2_256)
2613 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002614 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2615 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002616
2617 ASSERT_EQ(ErrorCode::OK,
2618 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
2619 AuthorizationSetBuilder()
2620 .Digest(Digest::SHA_2_256)
2621 .Padding(PaddingMode::RSA_OAEP)));
2622}
2623
2624TEST_P(ImportWrappedKeyTest, WrongMask) {
2625 auto wrapping_key_desc = AuthorizationSetBuilder()
2626 .RsaEncryptionKey(2048, 65537)
2627 .Digest(Digest::SHA_2_256)
2628 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002629 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2630 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002631
2632 ASSERT_EQ(
2633 ErrorCode::VERIFICATION_FAILED,
2634 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2635 AuthorizationSetBuilder()
2636 .Digest(Digest::SHA_2_256)
2637 .Padding(PaddingMode::RSA_OAEP)));
2638}
2639
2640TEST_P(ImportWrappedKeyTest, WrongPurpose) {
2641 auto wrapping_key_desc = AuthorizationSetBuilder()
2642 .RsaEncryptionKey(2048, 65537)
2643 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002644 .Padding(PaddingMode::RSA_OAEP)
2645 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002646
2647 ASSERT_EQ(
2648 ErrorCode::INCOMPATIBLE_PURPOSE,
2649 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2650 AuthorizationSetBuilder()
2651 .Digest(Digest::SHA_2_256)
2652 .Padding(PaddingMode::RSA_OAEP)));
2653}
2654
2655INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
2656
2657typedef KeyMintAidlTestBase EncryptionOperationsTest;
2658
2659/*
2660 * EncryptionOperationsTest.RsaNoPaddingSuccess
2661 *
2662 * Verifies that raw RSA encryption works.
2663 */
2664TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2665 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2666 .Authorization(TAG_NO_AUTH_REQUIRED)
2667 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002668 .Padding(PaddingMode::NONE)
2669 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002670
2671 string message = string(2048 / 8, 'a');
2672 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2673 string ciphertext1 = EncryptMessage(message, params);
2674 EXPECT_EQ(2048U / 8, ciphertext1.size());
2675
2676 string ciphertext2 = EncryptMessage(message, params);
2677 EXPECT_EQ(2048U / 8, ciphertext2.size());
2678
2679 // Unpadded RSA is deterministic
2680 EXPECT_EQ(ciphertext1, ciphertext2);
2681}
2682
2683/*
2684 * EncryptionOperationsTest.RsaNoPaddingShortMessage
2685 *
2686 * Verifies that raw RSA encryption of short messages works.
2687 */
2688TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2689 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2690 .Authorization(TAG_NO_AUTH_REQUIRED)
2691 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002692 .Padding(PaddingMode::NONE)
2693 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002694
2695 string message = "1";
2696 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2697
2698 string ciphertext = EncryptMessage(message, params);
2699 EXPECT_EQ(2048U / 8, ciphertext.size());
2700
2701 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
2702 string plaintext = DecryptMessage(ciphertext, params);
2703
2704 EXPECT_EQ(expected_plaintext, plaintext);
2705
2706 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2707 message = static_cast<char>(1);
2708 ciphertext = EncryptMessage(message, params);
2709 EXPECT_EQ(2048U / 8, ciphertext.size());
2710 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
2711}
2712
2713/*
2714 * EncryptionOperationsTest.RsaNoPaddingTooLong
2715 *
2716 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2717 */
2718TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2719 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2720 .Authorization(TAG_NO_AUTH_REQUIRED)
2721 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002722 .Padding(PaddingMode::NONE)
2723 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002724
2725 string message(2048 / 8 + 1, 'a');
2726
2727 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2728 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2729
2730 string result;
2731 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2732}
2733
2734/*
2735 * EncryptionOperationsTest.RsaNoPaddingTooLarge
2736 *
2737 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
2738 * way.
2739 */
2740// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
2741// version of ExportKey inside generateKey
2742
2743/*
2744 * EncryptionOperationsTest.RsaOaepSuccess
2745 *
2746 * Verifies that RSA-OAEP encryption operations work, with all digests.
2747 */
2748TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2749 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2750
2751 size_t key_size = 2048; // Need largish key for SHA-512 test.
2752 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2753 .Authorization(TAG_NO_AUTH_REQUIRED)
2754 .RsaEncryptionKey(key_size, 65537)
2755 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002756 .Digest(digests)
2757 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002758
2759 string message = "Hello";
2760
2761 for (auto digest : digests) {
2762 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2763 string ciphertext1 = EncryptMessage(message, params);
2764 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2765 EXPECT_EQ(key_size / 8, ciphertext1.size());
2766
2767 string ciphertext2 = EncryptMessage(message, params);
2768 EXPECT_EQ(key_size / 8, ciphertext2.size());
2769
2770 // OAEP randomizes padding so every result should be different (with astronomically high
2771 // probability).
2772 EXPECT_NE(ciphertext1, ciphertext2);
2773
2774 string plaintext1 = DecryptMessage(ciphertext1, params);
2775 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2776 string plaintext2 = DecryptMessage(ciphertext2, params);
2777 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2778
2779 // Decrypting corrupted ciphertext should fail.
2780 size_t offset_to_corrupt = random() % ciphertext1.size();
2781 char corrupt_byte;
2782 do {
2783 corrupt_byte = static_cast<char>(random() % 256);
2784 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2785 ciphertext1[offset_to_corrupt] = corrupt_byte;
2786
2787 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2788 string result;
2789 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2790 EXPECT_EQ(0U, result.size());
2791 }
2792}
2793
2794/*
2795 * EncryptionOperationsTest.RsaOaepInvalidDigest
2796 *
2797 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2798 * without a digest.
2799 */
2800TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2801 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2802 .Authorization(TAG_NO_AUTH_REQUIRED)
2803 .RsaEncryptionKey(2048, 65537)
2804 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002805 .Digest(Digest::NONE)
2806 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002807 string message = "Hello World!";
2808
2809 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2810 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2811}
2812
2813/*
2814 * EncryptionOperationsTest.RsaOaepInvalidDigest
2815 *
2816 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
2817 * with a different digest than was used to encrypt.
2818 */
2819TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2820 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2821
2822 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2823 .Authorization(TAG_NO_AUTH_REQUIRED)
2824 .RsaEncryptionKey(1024, 65537)
2825 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002826 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
2827 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002828 string message = "Hello World!";
2829 string ciphertext = EncryptMessage(
2830 message,
2831 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2832
2833 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2834 .Digest(Digest::SHA_2_256)
2835 .Padding(PaddingMode::RSA_OAEP)));
2836 string result;
2837 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2838 EXPECT_EQ(0U, result.size());
2839}
2840
2841/*
2842 * EncryptionOperationsTest.RsaOaepTooLarge
2843 *
2844 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2845 * too-large message.
2846 */
2847TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2848 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2849 .Authorization(TAG_NO_AUTH_REQUIRED)
2850 .RsaEncryptionKey(2048, 65537)
2851 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002852 .Digest(Digest::SHA_2_256)
2853 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002854 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
2855 constexpr size_t oaep_overhead = 2 * digest_size + 2;
2856 string message(2048 / 8 - oaep_overhead + 1, 'a');
2857 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2858 .Padding(PaddingMode::RSA_OAEP)
2859 .Digest(Digest::SHA_2_256)));
2860 string result;
2861 ErrorCode error = Finish(message, &result);
2862 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2863 EXPECT_EQ(0U, result.size());
2864}
2865
2866/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002867 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
2868 *
2869 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
2870 * digests.
2871 */
2872TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
2873 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2874
2875 size_t key_size = 2048; // Need largish key for SHA-512 test.
2876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2877 .OaepMGFDigest(digests)
2878 .Authorization(TAG_NO_AUTH_REQUIRED)
2879 .RsaEncryptionKey(key_size, 65537)
2880 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002881 .Digest(Digest::SHA_2_256)
2882 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002883
2884 string message = "Hello";
2885
2886 for (auto digest : digests) {
2887 auto params = AuthorizationSetBuilder()
2888 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
2889 .Digest(Digest::SHA_2_256)
2890 .Padding(PaddingMode::RSA_OAEP);
2891 string ciphertext1 = EncryptMessage(message, params);
2892 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2893 EXPECT_EQ(key_size / 8, ciphertext1.size());
2894
2895 string ciphertext2 = EncryptMessage(message, params);
2896 EXPECT_EQ(key_size / 8, ciphertext2.size());
2897
2898 // OAEP randomizes padding so every result should be different (with astronomically high
2899 // probability).
2900 EXPECT_NE(ciphertext1, ciphertext2);
2901
2902 string plaintext1 = DecryptMessage(ciphertext1, params);
2903 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2904 string plaintext2 = DecryptMessage(ciphertext2, params);
2905 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2906
2907 // Decrypting corrupted ciphertext should fail.
2908 size_t offset_to_corrupt = random() % ciphertext1.size();
2909 char corrupt_byte;
2910 do {
2911 corrupt_byte = static_cast<char>(random() % 256);
2912 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2913 ciphertext1[offset_to_corrupt] = corrupt_byte;
2914
2915 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2916 string result;
2917 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2918 EXPECT_EQ(0U, result.size());
2919 }
2920}
2921
2922/*
2923 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
2924 *
2925 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2926 * with incompatible MGF digest.
2927 */
2928TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
2929 ASSERT_EQ(ErrorCode::OK,
2930 GenerateKey(AuthorizationSetBuilder()
2931 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
2932 .Authorization(TAG_NO_AUTH_REQUIRED)
2933 .RsaEncryptionKey(2048, 65537)
2934 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002935 .Digest(Digest::SHA_2_256)
2936 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002937 string message = "Hello World!";
2938
2939 auto params = AuthorizationSetBuilder()
2940 .Padding(PaddingMode::RSA_OAEP)
2941 .Digest(Digest::SHA_2_256)
2942 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
2943 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2944}
2945
2946/*
2947 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
2948 *
2949 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2950 * with unsupported MGF digest.
2951 */
2952TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
2953 ASSERT_EQ(ErrorCode::OK,
2954 GenerateKey(AuthorizationSetBuilder()
2955 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
2956 .Authorization(TAG_NO_AUTH_REQUIRED)
2957 .RsaEncryptionKey(2048, 65537)
2958 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002959 .Digest(Digest::SHA_2_256)
2960 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002961 string message = "Hello World!";
2962
2963 auto params = AuthorizationSetBuilder()
2964 .Padding(PaddingMode::RSA_OAEP)
2965 .Digest(Digest::SHA_2_256)
2966 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
2967 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2968}
2969
2970/*
Selene Huang31ab4042020-04-29 04:22:39 -07002971 * EncryptionOperationsTest.RsaPkcs1Success
2972 *
2973 * Verifies that RSA PKCS encryption/decrypts works.
2974 */
2975TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2977 .Authorization(TAG_NO_AUTH_REQUIRED)
2978 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002979 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
2980 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002981
2982 string message = "Hello World!";
2983 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2984 string ciphertext1 = EncryptMessage(message, params);
2985 EXPECT_EQ(2048U / 8, ciphertext1.size());
2986
2987 string ciphertext2 = EncryptMessage(message, params);
2988 EXPECT_EQ(2048U / 8, ciphertext2.size());
2989
2990 // PKCS1 v1.5 randomizes padding so every result should be different.
2991 EXPECT_NE(ciphertext1, ciphertext2);
2992
2993 string plaintext = DecryptMessage(ciphertext1, params);
2994 EXPECT_EQ(message, plaintext);
2995
2996 // Decrypting corrupted ciphertext should fail.
2997 size_t offset_to_corrupt = random() % ciphertext1.size();
2998 char corrupt_byte;
2999 do {
3000 corrupt_byte = static_cast<char>(random() % 256);
3001 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3002 ciphertext1[offset_to_corrupt] = corrupt_byte;
3003
3004 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3005 string result;
3006 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3007 EXPECT_EQ(0U, result.size());
3008}
3009
3010/*
3011 * EncryptionOperationsTest.RsaPkcs1TooLarge
3012 *
3013 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
3014 */
3015TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
3016 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3017 .Authorization(TAG_NO_AUTH_REQUIRED)
3018 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003019 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3020 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003021 string message(2048 / 8 - 10, 'a');
3022
3023 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3024 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3025 string result;
3026 ErrorCode error = Finish(message, &result);
3027 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3028 EXPECT_EQ(0U, result.size());
3029}
3030
3031/*
3032 * EncryptionOperationsTest.EcdsaEncrypt
3033 *
3034 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
3035 */
3036TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
3037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3038 .Authorization(TAG_NO_AUTH_REQUIRED)
3039 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003040 .Digest(Digest::NONE)
3041 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003042 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3043 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3044 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3045}
3046
3047/*
3048 * EncryptionOperationsTest.HmacEncrypt
3049 *
3050 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
3051 */
3052TEST_P(EncryptionOperationsTest, HmacEncrypt) {
3053 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3054 .Authorization(TAG_NO_AUTH_REQUIRED)
3055 .HmacKey(128)
3056 .Digest(Digest::SHA_2_256)
3057 .Padding(PaddingMode::NONE)
3058 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3059 auto params = AuthorizationSetBuilder()
3060 .Digest(Digest::SHA_2_256)
3061 .Padding(PaddingMode::NONE)
3062 .Authorization(TAG_MAC_LENGTH, 128);
3063 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3064 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3065}
3066
3067/*
3068 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3069 *
3070 * Verifies that AES ECB mode works.
3071 */
3072TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
3073 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3074 .Authorization(TAG_NO_AUTH_REQUIRED)
3075 .AesEncryptionKey(128)
3076 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3077 .Padding(PaddingMode::NONE)));
3078
3079 ASSERT_GT(key_blob_.size(), 0U);
3080 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3081
3082 // Two-block message.
3083 string message = "12345678901234567890123456789012";
3084 string ciphertext1 = EncryptMessage(message, params);
3085 EXPECT_EQ(message.size(), ciphertext1.size());
3086
3087 string ciphertext2 = EncryptMessage(string(message), params);
3088 EXPECT_EQ(message.size(), ciphertext2.size());
3089
3090 // ECB is deterministic.
3091 EXPECT_EQ(ciphertext1, ciphertext2);
3092
3093 string plaintext = DecryptMessage(ciphertext1, params);
3094 EXPECT_EQ(message, plaintext);
3095}
3096
3097/*
3098 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3099 *
3100 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
3101 */
3102TEST_P(EncryptionOperationsTest, AesWrongMode) {
3103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3104 .Authorization(TAG_NO_AUTH_REQUIRED)
3105 .AesEncryptionKey(128)
3106 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3107 .Padding(PaddingMode::NONE)));
3108
3109 ASSERT_GT(key_blob_.size(), 0U);
3110
3111 // Two-block message.
3112 string message = "12345678901234567890123456789012";
3113 EXPECT_EQ(
3114 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
3115 Begin(KeyPurpose::ENCRYPT,
3116 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
3117}
3118
3119/*
3120 * EncryptionOperationsTest.AesWrongPurpose
3121 *
3122 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
3123 * specified.
3124 */
3125TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
3126 auto err = GenerateKey(AuthorizationSetBuilder()
3127 .Authorization(TAG_NO_AUTH_REQUIRED)
3128 .AesKey(128)
3129 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
3130 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3131 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3132 .Padding(PaddingMode::NONE));
3133 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
3134 ASSERT_GT(key_blob_.size(), 0U);
3135
3136 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3137 .BlockMode(BlockMode::GCM)
3138 .Padding(PaddingMode::NONE)
3139 .Authorization(TAG_MAC_LENGTH, 128));
3140 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3141
3142 CheckedDeleteKey();
3143
3144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3145 .Authorization(TAG_NO_AUTH_REQUIRED)
3146 .AesKey(128)
3147 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
3148 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3149 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3150 .Padding(PaddingMode::NONE)));
3151
3152 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3153 .BlockMode(BlockMode::GCM)
3154 .Padding(PaddingMode::NONE)
3155 .Authorization(TAG_MAC_LENGTH, 128));
3156 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3157}
3158
3159/*
3160 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
3161 *
3162 * Verifies that AES encryption fails in the correct way when provided an input that is not a
3163 * multiple of the block size and no padding is specified.
3164 */
3165TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
3166 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3167 .Authorization(TAG_NO_AUTH_REQUIRED)
3168 .AesEncryptionKey(128)
3169 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3170 .Padding(PaddingMode::NONE)));
3171 // Message is slightly shorter than two blocks.
3172 string message(16 * 2 - 1, 'a');
3173
3174 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3175 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3176 string ciphertext;
3177 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
3178 EXPECT_EQ(0U, ciphertext.size());
3179}
3180
3181/*
3182 * EncryptionOperationsTest.AesEcbPkcs7Padding
3183 *
3184 * Verifies that AES PKCS7 padding works for any message length.
3185 */
3186TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
3187 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3188 .Authorization(TAG_NO_AUTH_REQUIRED)
3189 .AesEncryptionKey(128)
3190 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3191 .Padding(PaddingMode::PKCS7)));
3192
3193 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3194
3195 // Try various message lengths; all should work.
3196 for (size_t i = 0; i < 32; ++i) {
3197 string message(i, 'a');
3198 string ciphertext = EncryptMessage(message, params);
3199 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
3200 string plaintext = DecryptMessage(ciphertext, params);
3201 EXPECT_EQ(message, plaintext);
3202 }
3203}
3204
3205/*
3206 * EncryptionOperationsTest.AesEcbWrongPadding
3207 *
3208 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
3209 * specified.
3210 */
3211TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
3212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3213 .Authorization(TAG_NO_AUTH_REQUIRED)
3214 .AesEncryptionKey(128)
3215 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3216 .Padding(PaddingMode::NONE)));
3217
3218 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3219
3220 // Try various message lengths; all should fail
3221 for (size_t i = 0; i < 32; ++i) {
3222 string message(i, 'a');
3223 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3224 }
3225}
3226
3227/*
3228 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
3229 *
3230 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
3231 */
3232TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
3233 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3234 .Authorization(TAG_NO_AUTH_REQUIRED)
3235 .AesEncryptionKey(128)
3236 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3237 .Padding(PaddingMode::PKCS7)));
3238
3239 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3240
3241 string message = "a";
3242 string ciphertext = EncryptMessage(message, params);
3243 EXPECT_EQ(16U, ciphertext.size());
3244 EXPECT_NE(ciphertext, message);
3245 ++ciphertext[ciphertext.size() / 2];
3246
3247 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3248 string plaintext;
3249 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3250}
3251
3252vector<uint8_t> CopyIv(const AuthorizationSet& set) {
3253 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003254 EXPECT_TRUE(iv);
3255 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07003256}
3257
3258/*
3259 * EncryptionOperationsTest.AesCtrRoundTripSuccess
3260 *
3261 * Verifies that AES CTR mode works.
3262 */
3263TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3264 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3265 .Authorization(TAG_NO_AUTH_REQUIRED)
3266 .AesEncryptionKey(128)
3267 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3268 .Padding(PaddingMode::NONE)));
3269
3270 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3271
3272 string message = "123";
3273 AuthorizationSet out_params;
3274 string ciphertext1 = EncryptMessage(message, params, &out_params);
3275 vector<uint8_t> iv1 = CopyIv(out_params);
3276 EXPECT_EQ(16U, iv1.size());
3277
3278 EXPECT_EQ(message.size(), ciphertext1.size());
3279
3280 out_params.Clear();
3281 string ciphertext2 = EncryptMessage(message, params, &out_params);
3282 vector<uint8_t> iv2 = CopyIv(out_params);
3283 EXPECT_EQ(16U, iv2.size());
3284
3285 // IVs should be random, so ciphertexts should differ.
3286 EXPECT_NE(ciphertext1, ciphertext2);
3287
3288 auto params_iv1 =
3289 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3290 auto params_iv2 =
3291 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3292
3293 string plaintext = DecryptMessage(ciphertext1, params_iv1);
3294 EXPECT_EQ(message, plaintext);
3295 plaintext = DecryptMessage(ciphertext2, params_iv2);
3296 EXPECT_EQ(message, plaintext);
3297
3298 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3299 plaintext = DecryptMessage(ciphertext1, params_iv2);
3300 EXPECT_NE(message, plaintext);
3301 plaintext = DecryptMessage(ciphertext2, params_iv1);
3302 EXPECT_NE(message, plaintext);
3303}
3304
3305/*
3306 * EncryptionOperationsTest.AesIncremental
3307 *
3308 * Verifies that AES works, all modes, when provided data in various size increments.
3309 */
3310TEST_P(EncryptionOperationsTest, AesIncremental) {
3311 auto block_modes = {
3312 BlockMode::ECB,
3313 BlockMode::CBC,
3314 BlockMode::CTR,
3315 BlockMode::GCM,
3316 };
3317
3318 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3319 .Authorization(TAG_NO_AUTH_REQUIRED)
3320 .AesEncryptionKey(128)
3321 .BlockMode(block_modes)
3322 .Padding(PaddingMode::NONE)
3323 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3324
3325 for (int increment = 1; increment <= 240; ++increment) {
3326 for (auto block_mode : block_modes) {
3327 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07003328 auto params =
3329 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
3330 if (block_mode == BlockMode::GCM) {
3331 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3332 }
Selene Huang31ab4042020-04-29 04:22:39 -07003333
3334 AuthorizationSet output_params;
3335 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3336
3337 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07003338 string to_send;
3339 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003340 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003341 }
Shawn Willden92d79c02021-02-19 07:31:55 -07003342 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
3343 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07003344
3345 switch (block_mode) {
3346 case BlockMode::GCM:
3347 EXPECT_EQ(message.size() + 16, ciphertext.size());
3348 break;
3349 case BlockMode::CTR:
3350 EXPECT_EQ(message.size(), ciphertext.size());
3351 break;
3352 case BlockMode::CBC:
3353 case BlockMode::ECB:
3354 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3355 break;
3356 }
3357
3358 auto iv = output_params.GetTagValue(TAG_NONCE);
3359 switch (block_mode) {
3360 case BlockMode::CBC:
3361 case BlockMode::GCM:
3362 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003363 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
3364 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
3365 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003366 break;
3367
3368 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003369 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07003370 break;
3371 }
3372
3373 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3374 << "Decrypt begin() failed for block mode " << block_mode;
3375
3376 string plaintext;
3377 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003378 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003379 }
3380 ErrorCode error = Finish(to_send, &plaintext);
3381 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
3382 << " and increment " << increment;
3383 if (error == ErrorCode::OK) {
3384 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3385 << block_mode << " and increment " << increment;
3386 }
3387 }
3388 }
3389}
3390
3391struct AesCtrSp80038aTestVector {
3392 const char* key;
3393 const char* nonce;
3394 const char* plaintext;
3395 const char* ciphertext;
3396};
3397
3398// These test vectors are taken from
3399// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3400static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3401 // AES-128
3402 {
3403 "2b7e151628aed2a6abf7158809cf4f3c",
3404 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3405 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3406 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3407 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3408 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3409 },
3410 // AES-192
3411 {
3412 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
3413 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3414 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3415 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3416 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3417 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3418 },
3419 // AES-256
3420 {
3421 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3422 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3423 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3424 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3425 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3426 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3427 },
3428};
3429
3430/*
3431 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3432 *
3433 * Verifies AES CTR implementation against SP800-38A test vectors.
3434 */
3435TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3436 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3437 for (size_t i = 0; i < 3; i++) {
3438 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3439 const string key = hex2str(test.key);
3440 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3441 InvalidSizes.end())
3442 continue;
3443 const string nonce = hex2str(test.nonce);
3444 const string plaintext = hex2str(test.plaintext);
3445 const string ciphertext = hex2str(test.ciphertext);
3446 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3447 }
3448}
3449
3450/*
3451 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3452 *
3453 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
3454 */
3455TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3456 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3457 .Authorization(TAG_NO_AUTH_REQUIRED)
3458 .AesEncryptionKey(128)
3459 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3460 .Padding(PaddingMode::PKCS7)));
3461 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3462 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3463}
3464
3465/*
3466 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3467 *
3468 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3469 */
3470TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3471 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3472 .Authorization(TAG_NO_AUTH_REQUIRED)
3473 .AesEncryptionKey(128)
3474 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3475 .Authorization(TAG_CALLER_NONCE)
3476 .Padding(PaddingMode::NONE)));
3477
3478 auto params = AuthorizationSetBuilder()
3479 .BlockMode(BlockMode::CTR)
3480 .Padding(PaddingMode::NONE)
3481 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
3482 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3483
3484 params = AuthorizationSetBuilder()
3485 .BlockMode(BlockMode::CTR)
3486 .Padding(PaddingMode::NONE)
3487 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
3488 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3489
3490 params = AuthorizationSetBuilder()
3491 .BlockMode(BlockMode::CTR)
3492 .Padding(PaddingMode::NONE)
3493 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
3494 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3495}
3496
3497/*
3498 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3499 *
3500 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3501 */
3502TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3503 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3504 .Authorization(TAG_NO_AUTH_REQUIRED)
3505 .AesEncryptionKey(128)
3506 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3507 .Padding(PaddingMode::NONE)));
3508 // Two-block message.
3509 string message = "12345678901234567890123456789012";
3510 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3511 AuthorizationSet out_params;
3512 string ciphertext1 = EncryptMessage(message, params, &out_params);
3513 vector<uint8_t> iv1 = CopyIv(out_params);
3514 EXPECT_EQ(message.size(), ciphertext1.size());
3515
3516 out_params.Clear();
3517
3518 string ciphertext2 = EncryptMessage(message, params, &out_params);
3519 vector<uint8_t> iv2 = CopyIv(out_params);
3520 EXPECT_EQ(message.size(), ciphertext2.size());
3521
3522 // IVs should be random, so ciphertexts should differ.
3523 EXPECT_NE(ciphertext1, ciphertext2);
3524
3525 params.push_back(TAG_NONCE, iv1);
3526 string plaintext = DecryptMessage(ciphertext1, params);
3527 EXPECT_EQ(message, plaintext);
3528}
3529
3530/*
3531 * EncryptionOperationsTest.AesCallerNonce
3532 *
3533 * Verifies that AES caller-provided nonces work correctly.
3534 */
3535TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3536 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3537 .Authorization(TAG_NO_AUTH_REQUIRED)
3538 .AesEncryptionKey(128)
3539 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3540 .Authorization(TAG_CALLER_NONCE)
3541 .Padding(PaddingMode::NONE)));
3542
3543 string message = "12345678901234567890123456789012";
3544
3545 // Don't specify nonce, should get a random one.
3546 AuthorizationSetBuilder params =
3547 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3548 AuthorizationSet out_params;
3549 string ciphertext = EncryptMessage(message, params, &out_params);
3550 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003551 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003552
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003553 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003554 string plaintext = DecryptMessage(ciphertext, params);
3555 EXPECT_EQ(message, plaintext);
3556
3557 // Now specify a nonce, should also work.
3558 params = AuthorizationSetBuilder()
3559 .BlockMode(BlockMode::CBC)
3560 .Padding(PaddingMode::NONE)
3561 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3562 out_params.Clear();
3563 ciphertext = EncryptMessage(message, params, &out_params);
3564
3565 // Decrypt with correct nonce.
3566 plaintext = DecryptMessage(ciphertext, params);
3567 EXPECT_EQ(message, plaintext);
3568
3569 // Try with wrong nonce.
3570 params = AuthorizationSetBuilder()
3571 .BlockMode(BlockMode::CBC)
3572 .Padding(PaddingMode::NONE)
3573 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
3574 plaintext = DecryptMessage(ciphertext, params);
3575 EXPECT_NE(message, plaintext);
3576}
3577
3578/*
3579 * EncryptionOperationsTest.AesCallerNonceProhibited
3580 *
3581 * Verifies that caller-provided nonces are not permitted when not specified in the key
3582 * authorizations.
3583 */
3584TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
3585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3586 .Authorization(TAG_NO_AUTH_REQUIRED)
3587 .AesEncryptionKey(128)
3588 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3589 .Padding(PaddingMode::NONE)));
3590
3591 string message = "12345678901234567890123456789012";
3592
3593 // Don't specify nonce, should get a random one.
3594 AuthorizationSetBuilder params =
3595 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3596 AuthorizationSet out_params;
3597 string ciphertext = EncryptMessage(message, params, &out_params);
3598 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003599 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003600
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003601 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003602 string plaintext = DecryptMessage(ciphertext, params);
3603 EXPECT_EQ(message, plaintext);
3604
3605 // Now specify a nonce, should fail
3606 params = AuthorizationSetBuilder()
3607 .BlockMode(BlockMode::CBC)
3608 .Padding(PaddingMode::NONE)
3609 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3610 out_params.Clear();
3611 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3612}
3613
3614/*
3615 * EncryptionOperationsTest.AesGcmRoundTripSuccess
3616 *
3617 * Verifies that AES GCM mode works.
3618 */
3619TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3621 .Authorization(TAG_NO_AUTH_REQUIRED)
3622 .AesEncryptionKey(128)
3623 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3624 .Padding(PaddingMode::NONE)
3625 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3626
3627 string aad = "foobar";
3628 string message = "123456789012345678901234567890123456";
3629
3630 auto begin_params = AuthorizationSetBuilder()
3631 .BlockMode(BlockMode::GCM)
3632 .Padding(PaddingMode::NONE)
3633 .Authorization(TAG_MAC_LENGTH, 128);
3634
Selene Huang31ab4042020-04-29 04:22:39 -07003635 // Encrypt
3636 AuthorizationSet begin_out_params;
3637 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3638 << "Begin encrypt";
3639 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003640 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3641 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003642 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3643
3644 // Grab nonce
3645 begin_params.push_back(begin_out_params);
3646
3647 // Decrypt.
3648 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07003649 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003650 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003651 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003652 EXPECT_EQ(message.length(), plaintext.length());
3653 EXPECT_EQ(message, plaintext);
3654}
3655
3656/*
3657 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
3658 *
3659 * Verifies that AES GCM mode works, even when there's a long delay
3660 * between operations.
3661 */
3662TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
3663 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3664 .Authorization(TAG_NO_AUTH_REQUIRED)
3665 .AesEncryptionKey(128)
3666 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3667 .Padding(PaddingMode::NONE)
3668 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3669
3670 string aad = "foobar";
3671 string message = "123456789012345678901234567890123456";
3672
3673 auto begin_params = AuthorizationSetBuilder()
3674 .BlockMode(BlockMode::GCM)
3675 .Padding(PaddingMode::NONE)
3676 .Authorization(TAG_MAC_LENGTH, 128);
3677
Selene Huang31ab4042020-04-29 04:22:39 -07003678 // Encrypt
3679 AuthorizationSet begin_out_params;
3680 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3681 << "Begin encrypt";
3682 string ciphertext;
3683 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003684 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003685 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07003686 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003687
3688 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3689
3690 // Grab nonce
3691 begin_params.push_back(begin_out_params);
3692
3693 // Decrypt.
3694 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3695 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003696 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003697 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07003698 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003699 sleep(5);
3700 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3701 EXPECT_EQ(message.length(), plaintext.length());
3702 EXPECT_EQ(message, plaintext);
3703}
3704
3705/*
3706 * EncryptionOperationsTest.AesGcmDifferentNonces
3707 *
3708 * Verifies that encrypting the same data with different nonces produces different outputs.
3709 */
3710TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
3711 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3712 .Authorization(TAG_NO_AUTH_REQUIRED)
3713 .AesEncryptionKey(128)
3714 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3715 .Padding(PaddingMode::NONE)
3716 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3717 .Authorization(TAG_CALLER_NONCE)));
3718
3719 string aad = "foobar";
3720 string message = "123456789012345678901234567890123456";
3721 string nonce1 = "000000000000";
3722 string nonce2 = "111111111111";
3723 string nonce3 = "222222222222";
3724
3725 string ciphertext1 =
3726 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
3727 string ciphertext2 =
3728 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
3729 string ciphertext3 =
3730 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
3731
3732 ASSERT_NE(ciphertext1, ciphertext2);
3733 ASSERT_NE(ciphertext1, ciphertext3);
3734 ASSERT_NE(ciphertext2, ciphertext3);
3735}
3736
3737/*
3738 * EncryptionOperationsTest.AesGcmTooShortTag
3739 *
3740 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3741 */
3742TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
3743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3744 .Authorization(TAG_NO_AUTH_REQUIRED)
3745 .AesEncryptionKey(128)
3746 .BlockMode(BlockMode::GCM)
3747 .Padding(PaddingMode::NONE)
3748 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3749 string message = "123456789012345678901234567890123456";
3750 auto params = AuthorizationSetBuilder()
3751 .BlockMode(BlockMode::GCM)
3752 .Padding(PaddingMode::NONE)
3753 .Authorization(TAG_MAC_LENGTH, 96);
3754
3755 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3756}
3757
3758/*
3759 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3760 *
3761 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3762 */
3763TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3764 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3765 .Authorization(TAG_NO_AUTH_REQUIRED)
3766 .AesEncryptionKey(128)
3767 .BlockMode(BlockMode::GCM)
3768 .Padding(PaddingMode::NONE)
3769 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3770 string aad = "foobar";
3771 string message = "123456789012345678901234567890123456";
3772 auto params = AuthorizationSetBuilder()
3773 .BlockMode(BlockMode::GCM)
3774 .Padding(PaddingMode::NONE)
3775 .Authorization(TAG_MAC_LENGTH, 128);
3776
Selene Huang31ab4042020-04-29 04:22:39 -07003777 // Encrypt
3778 AuthorizationSet begin_out_params;
3779 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3780 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003781 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07003782
3783 AuthorizationSet finish_out_params;
3784 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003785 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3786 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003787
3788 params = AuthorizationSetBuilder()
3789 .Authorizations(begin_out_params)
3790 .BlockMode(BlockMode::GCM)
3791 .Padding(PaddingMode::NONE)
3792 .Authorization(TAG_MAC_LENGTH, 96);
3793
3794 // Decrypt.
3795 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3796}
3797
3798/*
3799 * EncryptionOperationsTest.AesGcmCorruptKey
3800 *
3801 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3802 */
3803TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3804 const uint8_t nonce_bytes[] = {
3805 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3806 };
3807 string nonce = make_string(nonce_bytes);
3808 const uint8_t ciphertext_bytes[] = {
3809 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
3810 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
3811 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
3812 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
3813 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3814 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3815 };
3816 string ciphertext = make_string(ciphertext_bytes);
3817
3818 auto params = AuthorizationSetBuilder()
3819 .BlockMode(BlockMode::GCM)
3820 .Padding(PaddingMode::NONE)
3821 .Authorization(TAG_MAC_LENGTH, 128)
3822 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3823
3824 auto import_params = AuthorizationSetBuilder()
3825 .Authorization(TAG_NO_AUTH_REQUIRED)
3826 .AesEncryptionKey(128)
3827 .BlockMode(BlockMode::GCM)
3828 .Padding(PaddingMode::NONE)
3829 .Authorization(TAG_CALLER_NONCE)
3830 .Authorization(TAG_MIN_MAC_LENGTH, 128);
3831
3832 // Import correct key and decrypt
3833 const uint8_t key_bytes[] = {
3834 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3835 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3836 };
3837 string key = make_string(key_bytes);
3838 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3839 string plaintext = DecryptMessage(ciphertext, params);
3840 CheckedDeleteKey();
3841
3842 // Corrupt key and attempt to decrypt
3843 key[0] = 0;
3844 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3845 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3846 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3847 CheckedDeleteKey();
3848}
3849
3850/*
3851 * EncryptionOperationsTest.AesGcmAadNoData
3852 *
3853 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3854 * encrypt.
3855 */
3856TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3858 .Authorization(TAG_NO_AUTH_REQUIRED)
3859 .AesEncryptionKey(128)
3860 .BlockMode(BlockMode::GCM)
3861 .Padding(PaddingMode::NONE)
3862 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3863
3864 string aad = "1234567890123456";
3865 auto params = AuthorizationSetBuilder()
3866 .BlockMode(BlockMode::GCM)
3867 .Padding(PaddingMode::NONE)
3868 .Authorization(TAG_MAC_LENGTH, 128);
3869
Selene Huang31ab4042020-04-29 04:22:39 -07003870 // Encrypt
3871 AuthorizationSet begin_out_params;
3872 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3873 string ciphertext;
3874 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003875 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3876 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003877 EXPECT_TRUE(finish_out_params.empty());
3878
3879 // Grab nonce
3880 params.push_back(begin_out_params);
3881
3882 // Decrypt.
3883 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003884 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003885 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003886 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003887
3888 EXPECT_TRUE(finish_out_params.empty());
3889
3890 EXPECT_EQ("", plaintext);
3891}
3892
3893/*
3894 * EncryptionOperationsTest.AesGcmMultiPartAad
3895 *
3896 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
3897 * chunks.
3898 */
3899TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3900 const size_t tag_bits = 128;
3901 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3902 .Authorization(TAG_NO_AUTH_REQUIRED)
3903 .AesEncryptionKey(128)
3904 .BlockMode(BlockMode::GCM)
3905 .Padding(PaddingMode::NONE)
3906 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3907
3908 string message = "123456789012345678901234567890123456";
3909 auto begin_params = AuthorizationSetBuilder()
3910 .BlockMode(BlockMode::GCM)
3911 .Padding(PaddingMode::NONE)
3912 .Authorization(TAG_MAC_LENGTH, tag_bits);
3913 AuthorizationSet begin_out_params;
3914
Selene Huang31ab4042020-04-29 04:22:39 -07003915 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3916
3917 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07003918 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
3919 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003920 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003921 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
3922 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003923
Selene Huang31ab4042020-04-29 04:22:39 -07003924 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07003925 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003926
3927 // Grab nonce.
3928 begin_params.push_back(begin_out_params);
3929
3930 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003931 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003932 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003933 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003934 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003935 EXPECT_EQ(message, plaintext);
3936}
3937
3938/*
3939 * EncryptionOperationsTest.AesGcmAadOutOfOrder
3940 *
3941 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3942 */
3943TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3944 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3945 .Authorization(TAG_NO_AUTH_REQUIRED)
3946 .AesEncryptionKey(128)
3947 .BlockMode(BlockMode::GCM)
3948 .Padding(PaddingMode::NONE)
3949 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3950
3951 string message = "123456789012345678901234567890123456";
3952 auto begin_params = AuthorizationSetBuilder()
3953 .BlockMode(BlockMode::GCM)
3954 .Padding(PaddingMode::NONE)
3955 .Authorization(TAG_MAC_LENGTH, 128);
3956 AuthorizationSet begin_out_params;
3957
Selene Huang31ab4042020-04-29 04:22:39 -07003958 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3959
Shawn Willden92d79c02021-02-19 07:31:55 -07003960 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003961 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003962 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
3963 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003964
Shawn Willden92d79c02021-02-19 07:31:55 -07003965 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07003966}
3967
3968/*
3969 * EncryptionOperationsTest.AesGcmBadAad
3970 *
3971 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3972 */
3973TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3974 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3975 .Authorization(TAG_NO_AUTH_REQUIRED)
3976 .AesEncryptionKey(128)
3977 .BlockMode(BlockMode::GCM)
3978 .Padding(PaddingMode::NONE)
3979 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3980
3981 string message = "12345678901234567890123456789012";
3982 auto begin_params = AuthorizationSetBuilder()
3983 .BlockMode(BlockMode::GCM)
3984 .Padding(PaddingMode::NONE)
3985 .Authorization(TAG_MAC_LENGTH, 128);
3986
Selene Huang31ab4042020-04-29 04:22:39 -07003987 // Encrypt
3988 AuthorizationSet begin_out_params;
3989 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003990 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07003991 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003992 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003993
3994 // Grab nonce
3995 begin_params.push_back(begin_out_params);
3996
Selene Huang31ab4042020-04-29 04:22:39 -07003997 // Decrypt.
3998 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003999 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004000 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004001 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004002}
4003
4004/*
4005 * EncryptionOperationsTest.AesGcmWrongNonce
4006 *
4007 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
4008 */
4009TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
4010 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4011 .Authorization(TAG_NO_AUTH_REQUIRED)
4012 .AesEncryptionKey(128)
4013 .BlockMode(BlockMode::GCM)
4014 .Padding(PaddingMode::NONE)
4015 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4016
4017 string message = "12345678901234567890123456789012";
4018 auto begin_params = AuthorizationSetBuilder()
4019 .BlockMode(BlockMode::GCM)
4020 .Padding(PaddingMode::NONE)
4021 .Authorization(TAG_MAC_LENGTH, 128);
4022
Selene Huang31ab4042020-04-29 04:22:39 -07004023 // Encrypt
4024 AuthorizationSet begin_out_params;
4025 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004026 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004027 string ciphertext;
4028 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004029 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004030
4031 // Wrong nonce
4032 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
4033
4034 // Decrypt.
4035 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004036 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004037 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004038 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004039
4040 // With wrong nonce, should have gotten garbage plaintext (or none).
4041 EXPECT_NE(message, plaintext);
4042}
4043
4044/*
4045 * EncryptionOperationsTest.AesGcmCorruptTag
4046 *
4047 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
4048 */
4049TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
4050 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4051 .Authorization(TAG_NO_AUTH_REQUIRED)
4052 .AesEncryptionKey(128)
4053 .BlockMode(BlockMode::GCM)
4054 .Padding(PaddingMode::NONE)
4055 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4056
4057 string aad = "1234567890123456";
4058 string message = "123456789012345678901234567890123456";
4059
4060 auto params = AuthorizationSetBuilder()
4061 .BlockMode(BlockMode::GCM)
4062 .Padding(PaddingMode::NONE)
4063 .Authorization(TAG_MAC_LENGTH, 128);
4064
Selene Huang31ab4042020-04-29 04:22:39 -07004065 // Encrypt
4066 AuthorizationSet begin_out_params;
4067 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004068 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004069 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004070 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004071
4072 // Corrupt tag
4073 ++(*ciphertext.rbegin());
4074
4075 // Grab nonce
4076 params.push_back(begin_out_params);
4077
4078 // Decrypt.
4079 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004080 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004081 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004082 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004083}
4084
4085/*
4086 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
4087 *
4088 * Verifies that 3DES is basically functional.
4089 */
4090TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
4091 auto auths = AuthorizationSetBuilder()
4092 .TripleDesEncryptionKey(168)
4093 .BlockMode(BlockMode::ECB)
4094 .Authorization(TAG_NO_AUTH_REQUIRED)
4095 .Padding(PaddingMode::NONE);
4096
4097 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
4098 // Two-block message.
4099 string message = "1234567890123456";
4100 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4101 string ciphertext1 = EncryptMessage(message, inParams);
4102 EXPECT_EQ(message.size(), ciphertext1.size());
4103
4104 string ciphertext2 = EncryptMessage(string(message), inParams);
4105 EXPECT_EQ(message.size(), ciphertext2.size());
4106
4107 // ECB is deterministic.
4108 EXPECT_EQ(ciphertext1, ciphertext2);
4109
4110 string plaintext = DecryptMessage(ciphertext1, inParams);
4111 EXPECT_EQ(message, plaintext);
4112}
4113
4114/*
4115 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
4116 *
4117 * Verifies that CBC keys reject ECB usage.
4118 */
4119TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
4120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4121 .TripleDesEncryptionKey(168)
4122 .BlockMode(BlockMode::CBC)
4123 .Authorization(TAG_NO_AUTH_REQUIRED)
4124 .Padding(PaddingMode::NONE)));
4125
4126 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4127 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4128}
4129
4130/*
4131 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
4132 *
4133 * Tests ECB mode with PKCS#7 padding, various message sizes.
4134 */
4135TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
4136 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4137 .TripleDesEncryptionKey(168)
4138 .BlockMode(BlockMode::ECB)
4139 .Authorization(TAG_NO_AUTH_REQUIRED)
4140 .Padding(PaddingMode::PKCS7)));
4141
4142 for (size_t i = 0; i < 32; ++i) {
4143 string message(i, 'a');
4144 auto inParams =
4145 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4146 string ciphertext = EncryptMessage(message, inParams);
4147 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4148 string plaintext = DecryptMessage(ciphertext, inParams);
4149 EXPECT_EQ(message, plaintext);
4150 }
4151}
4152
4153/*
4154 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
4155 *
4156 * Verifies that keys configured for no padding reject PKCS7 padding
4157 */
4158TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
4159 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4160 .TripleDesEncryptionKey(168)
4161 .BlockMode(BlockMode::ECB)
4162 .Authorization(TAG_NO_AUTH_REQUIRED)
4163 .Padding(PaddingMode::NONE)));
4164 for (size_t i = 0; i < 32; ++i) {
4165 auto inParams =
4166 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4167 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4168 }
4169}
4170
4171/*
4172 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
4173 *
4174 * Verifies that corrupted padding is detected.
4175 */
4176TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
4177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4178 .TripleDesEncryptionKey(168)
4179 .BlockMode(BlockMode::ECB)
4180 .Authorization(TAG_NO_AUTH_REQUIRED)
4181 .Padding(PaddingMode::PKCS7)));
4182
4183 string message = "a";
4184 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
4185 EXPECT_EQ(8U, ciphertext.size());
4186 EXPECT_NE(ciphertext, message);
4187 ++ciphertext[ciphertext.size() / 2];
4188
4189 AuthorizationSetBuilder begin_params;
4190 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
4191 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
4192 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4193 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004194 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004195 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4196}
4197
4198struct TripleDesTestVector {
4199 const char* name;
4200 const KeyPurpose purpose;
4201 const BlockMode block_mode;
4202 const PaddingMode padding_mode;
4203 const char* key;
4204 const char* iv;
4205 const char* input;
4206 const char* output;
4207};
4208
4209// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
4210// of the NIST vectors are multiples of the block size.
4211static const TripleDesTestVector kTripleDesTestVectors[] = {
4212 {
4213 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4214 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
4215 "", // IV
4216 "329d86bdf1bc5af4", // input
4217 "d946c2756d78633f", // output
4218 },
4219 {
4220 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4221 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
4222 "", // IV
4223 "6b1540781b01ce1997adae102dbf3c5b", // input
4224 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
4225 },
4226 {
4227 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4228 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
4229 "", // IV
4230 "6daad94ce08acfe7", // input
4231 "660e7d32dcc90e79", // output
4232 },
4233 {
4234 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4235 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
4236 "", // IV
4237 "e9653a0a1f05d31b9acd12d73aa9879d", // input
4238 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
4239 },
4240 {
4241 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4242 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
4243 "43f791134c5647ba", // IV
4244 "dcc153cef81d6f24", // input
4245 "92538bd8af18d3ba", // output
4246 },
4247 {
4248 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4249 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4250 "c2e999cb6249023c", // IV
4251 "c689aee38a301bb316da75db36f110b5", // input
4252 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
4253 },
4254 {
4255 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
4256 PaddingMode::PKCS7,
4257 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4258 "c2e999cb6249023c", // IV
4259 "c689aee38a301bb316da75db36f110b500", // input
4260 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
4261 },
4262 {
4263 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
4264 PaddingMode::PKCS7,
4265 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4266 "c2e999cb6249023c", // IV
4267 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
4268 "c689aee38a301bb316da75db36f110b500", // output
4269 },
4270 {
4271 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4272 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
4273 "41746c7e442d3681", // IV
4274 "c53a7b0ec40600fe", // input
4275 "d4f00eb455de1034", // output
4276 },
4277 {
4278 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4279 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
4280 "3982bc02c3727d45", // IV
4281 "6006f10adef52991fcc777a1238bbb65", // input
4282 "edae09288e9e3bc05746d872b48e3b29", // output
4283 },
4284};
4285
4286/*
4287 * EncryptionOperationsTest.TripleDesTestVector
4288 *
4289 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
4290 */
4291TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
4292 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
4293 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
4294 SCOPED_TRACE(test->name);
4295 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
4296 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
4297 hex2str(test->output));
4298 }
4299}
4300
4301/*
4302 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
4303 *
4304 * Validates CBC mode functionality.
4305 */
4306TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
4307 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4308 .TripleDesEncryptionKey(168)
4309 .BlockMode(BlockMode::CBC)
4310 .Authorization(TAG_NO_AUTH_REQUIRED)
4311 .Padding(PaddingMode::NONE)));
4312
4313 ASSERT_GT(key_blob_.size(), 0U);
4314
4315 // Two-block message.
4316 string message = "1234567890123456";
4317 vector<uint8_t> iv1;
4318 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
4319 EXPECT_EQ(message.size(), ciphertext1.size());
4320
4321 vector<uint8_t> iv2;
4322 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
4323 EXPECT_EQ(message.size(), ciphertext2.size());
4324
4325 // IVs should be random, so ciphertexts should differ.
4326 EXPECT_NE(iv1, iv2);
4327 EXPECT_NE(ciphertext1, ciphertext2);
4328
4329 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
4330 EXPECT_EQ(message, plaintext);
4331}
4332
4333/*
4334 * EncryptionOperationsTest.TripleDesCallerIv
4335 *
4336 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
4337 */
4338TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
4339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4340 .TripleDesEncryptionKey(168)
4341 .BlockMode(BlockMode::CBC)
4342 .Authorization(TAG_NO_AUTH_REQUIRED)
4343 .Authorization(TAG_CALLER_NONCE)
4344 .Padding(PaddingMode::NONE)));
4345 string message = "1234567890123456";
4346 vector<uint8_t> iv;
4347 // Don't specify IV, should get a random one.
4348 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4349 EXPECT_EQ(message.size(), ciphertext1.size());
4350 EXPECT_EQ(8U, iv.size());
4351
4352 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4353 EXPECT_EQ(message, plaintext);
4354
4355 // Now specify an IV, should also work.
4356 iv = AidlBuf("abcdefgh");
4357 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
4358
4359 // Decrypt with correct IV.
4360 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
4361 EXPECT_EQ(message, plaintext);
4362
4363 // Now try with wrong IV.
4364 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
4365 EXPECT_NE(message, plaintext);
4366}
4367
4368/*
4369 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
4370 *
4371 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
4372 */
4373TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
4374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4375 .TripleDesEncryptionKey(168)
4376 .BlockMode(BlockMode::CBC)
4377 .Authorization(TAG_NO_AUTH_REQUIRED)
4378 .Padding(PaddingMode::NONE)));
4379
4380 string message = "12345678901234567890123456789012";
4381 vector<uint8_t> iv;
4382 // Don't specify nonce, should get a random one.
4383 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4384 EXPECT_EQ(message.size(), ciphertext1.size());
4385 EXPECT_EQ(8U, iv.size());
4386
4387 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4388 EXPECT_EQ(message, plaintext);
4389
4390 // Now specify a nonce, should fail.
4391 auto input_params = AuthorizationSetBuilder()
4392 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
4393 .BlockMode(BlockMode::CBC)
4394 .Padding(PaddingMode::NONE);
4395 AuthorizationSet output_params;
4396 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
4397 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4398}
4399
4400/*
4401 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
4402 *
4403 * Verifies that 3DES ECB-only keys do not allow CBC usage.
4404 */
4405TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
4406 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4407 .TripleDesEncryptionKey(168)
4408 .BlockMode(BlockMode::ECB)
4409 .Authorization(TAG_NO_AUTH_REQUIRED)
4410 .Padding(PaddingMode::NONE)));
4411 // Two-block message.
4412 string message = "1234567890123456";
4413 auto begin_params =
4414 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4415 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4416}
4417
4418/*
4419 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4420 *
4421 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4422 */
4423TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4424 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4425 .TripleDesEncryptionKey(168)
4426 .BlockMode(BlockMode::CBC)
4427 .Authorization(TAG_NO_AUTH_REQUIRED)
4428 .Padding(PaddingMode::NONE)));
4429 // Message is slightly shorter than two blocks.
4430 string message = "123456789012345";
4431
4432 auto begin_params =
4433 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4434 AuthorizationSet output_params;
4435 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4436 string ciphertext;
4437 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4438}
4439
4440/*
4441 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4442 *
4443 * Verifies that PKCS7 padding works correctly in CBC mode.
4444 */
4445TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4446 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4447 .TripleDesEncryptionKey(168)
4448 .BlockMode(BlockMode::CBC)
4449 .Authorization(TAG_NO_AUTH_REQUIRED)
4450 .Padding(PaddingMode::PKCS7)));
4451
4452 // Try various message lengths; all should work.
4453 for (size_t i = 0; i < 32; ++i) {
4454 string message(i, 'a');
4455 vector<uint8_t> iv;
4456 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4457 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4458 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4459 EXPECT_EQ(message, plaintext);
4460 }
4461}
4462
4463/*
4464 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4465 *
4466 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4467 */
4468TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4470 .TripleDesEncryptionKey(168)
4471 .BlockMode(BlockMode::CBC)
4472 .Authorization(TAG_NO_AUTH_REQUIRED)
4473 .Padding(PaddingMode::NONE)));
4474
4475 // Try various message lengths; all should fail.
4476 for (size_t i = 0; i < 32; ++i) {
4477 auto begin_params =
4478 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4479 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4480 }
4481}
4482
4483/*
4484 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4485 *
4486 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4487 */
4488TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4489 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4490 .TripleDesEncryptionKey(168)
4491 .BlockMode(BlockMode::CBC)
4492 .Authorization(TAG_NO_AUTH_REQUIRED)
4493 .Padding(PaddingMode::PKCS7)));
4494
4495 string message = "a";
4496 vector<uint8_t> iv;
4497 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4498 EXPECT_EQ(8U, ciphertext.size());
4499 EXPECT_NE(ciphertext, message);
4500 ++ciphertext[ciphertext.size() / 2];
4501
4502 auto begin_params = AuthorizationSetBuilder()
4503 .BlockMode(BlockMode::CBC)
4504 .Padding(PaddingMode::PKCS7)
4505 .Authorization(TAG_NONCE, iv);
4506 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4507 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004508 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004509 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4510}
4511
4512/*
4513 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4514 *
4515 * Verifies that 3DES CBC works with many different input sizes.
4516 */
4517TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4518 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4519 .TripleDesEncryptionKey(168)
4520 .BlockMode(BlockMode::CBC)
4521 .Authorization(TAG_NO_AUTH_REQUIRED)
4522 .Padding(PaddingMode::NONE)));
4523
4524 int increment = 7;
4525 string message(240, 'a');
4526 AuthorizationSet input_params =
4527 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4528 AuthorizationSet output_params;
4529 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4530
4531 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004532 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004533 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004534 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4535 EXPECT_EQ(message.size(), ciphertext.size());
4536
4537 // Move TAG_NONCE into input_params
4538 input_params = output_params;
4539 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4540 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4541 output_params.Clear();
4542
4543 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4544 string plaintext;
4545 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004546 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004547 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4548 EXPECT_EQ(ciphertext.size(), plaintext.size());
4549 EXPECT_EQ(message, plaintext);
4550}
4551
4552INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4553
4554typedef KeyMintAidlTestBase MaxOperationsTest;
4555
4556/*
4557 * MaxOperationsTest.TestLimitAes
4558 *
4559 * Verifies that the max uses per boot tag works correctly with AES keys.
4560 */
4561TEST_P(MaxOperationsTest, TestLimitAes) {
4562 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4563
4564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4565 .Authorization(TAG_NO_AUTH_REQUIRED)
4566 .AesEncryptionKey(128)
4567 .EcbMode()
4568 .Padding(PaddingMode::NONE)
4569 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4570
4571 string message = "1234567890123456";
4572
4573 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4574
4575 EncryptMessage(message, params);
4576 EncryptMessage(message, params);
4577 EncryptMessage(message, params);
4578
4579 // Fourth time should fail.
4580 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
4581}
4582
4583/*
Qi Wud22ec842020-11-26 13:27:53 +08004584 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07004585 *
4586 * Verifies that the max uses per boot tag works correctly with RSA keys.
4587 */
4588TEST_P(MaxOperationsTest, TestLimitRsa) {
4589 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4590
4591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4592 .Authorization(TAG_NO_AUTH_REQUIRED)
4593 .RsaSigningKey(1024, 65537)
4594 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004595 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
4596 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004597
4598 string message = "1234567890123456";
4599
4600 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4601
4602 SignMessage(message, params);
4603 SignMessage(message, params);
4604 SignMessage(message, params);
4605
4606 // Fourth time should fail.
4607 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
4608}
4609
4610INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
4611
Qi Wud22ec842020-11-26 13:27:53 +08004612typedef KeyMintAidlTestBase UsageCountLimitTest;
4613
4614/*
Qi Wubeefae42021-01-28 23:16:37 +08004615 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004616 *
Qi Wubeefae42021-01-28 23:16:37 +08004617 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004618 */
Qi Wubeefae42021-01-28 23:16:37 +08004619TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08004620 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4621
4622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4623 .Authorization(TAG_NO_AUTH_REQUIRED)
4624 .AesEncryptionKey(128)
4625 .EcbMode()
4626 .Padding(PaddingMode::NONE)
4627 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
4628
4629 // Check the usage count limit tag appears in the authorizations.
4630 AuthorizationSet auths;
4631 for (auto& entry : key_characteristics_) {
4632 auths.push_back(AuthorizationSet(entry.authorizations));
4633 }
4634 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4635 << "key usage count limit " << 1U << " missing";
4636
4637 string message = "1234567890123456";
4638 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4639
Qi Wubeefae42021-01-28 23:16:37 +08004640 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4641 AuthorizationSet keystore_auths =
4642 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4643
Qi Wud22ec842020-11-26 13:27:53 +08004644 // First usage of AES key should work.
4645 EncryptMessage(message, params);
4646
Qi Wud22ec842020-11-26 13:27:53 +08004647 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4648 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4649 // must be invalidated from secure storage (such as RPMB partition).
4650 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4651 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004652 // Usage count limit tag is enforced by keystore, keymint does nothing.
4653 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08004654 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4655 }
4656}
4657
4658/*
Qi Wubeefae42021-01-28 23:16:37 +08004659 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004660 *
Qi Wubeefae42021-01-28 23:16:37 +08004661 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004662 */
Qi Wubeefae42021-01-28 23:16:37 +08004663TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
4664 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4665
4666 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4667 .Authorization(TAG_NO_AUTH_REQUIRED)
4668 .AesEncryptionKey(128)
4669 .EcbMode()
4670 .Padding(PaddingMode::NONE)
4671 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
4672
4673 // Check the usage count limit tag appears in the authorizations.
4674 AuthorizationSet auths;
4675 for (auto& entry : key_characteristics_) {
4676 auths.push_back(AuthorizationSet(entry.authorizations));
4677 }
4678 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4679 << "key usage count limit " << 3U << " missing";
4680
4681 string message = "1234567890123456";
4682 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4683
4684 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4685 AuthorizationSet keystore_auths =
4686 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4687
4688 EncryptMessage(message, params);
4689 EncryptMessage(message, params);
4690 EncryptMessage(message, params);
4691
4692 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4693 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4694 // must be invalidated from secure storage (such as RPMB partition).
4695 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4696 } else {
4697 // Usage count limit tag is enforced by keystore, keymint does nothing.
4698 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
4699 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4700 }
4701}
4702
4703/*
4704 * UsageCountLimitTest.TestSingleUseRsa
4705 *
4706 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
4707 */
4708TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08004709 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4710
4711 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4712 .Authorization(TAG_NO_AUTH_REQUIRED)
4713 .RsaSigningKey(1024, 65537)
4714 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004715 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4716 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08004717
4718 // Check the usage count limit tag appears in the authorizations.
4719 AuthorizationSet auths;
4720 for (auto& entry : key_characteristics_) {
4721 auths.push_back(AuthorizationSet(entry.authorizations));
4722 }
4723 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4724 << "key usage count limit " << 1U << " missing";
4725
4726 string message = "1234567890123456";
4727 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4728
Qi Wubeefae42021-01-28 23:16:37 +08004729 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4730 AuthorizationSet keystore_auths =
4731 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4732
Qi Wud22ec842020-11-26 13:27:53 +08004733 // First usage of RSA key should work.
4734 SignMessage(message, params);
4735
Qi Wud22ec842020-11-26 13:27:53 +08004736 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4737 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4738 // must be invalidated from secure storage (such as RPMB partition).
4739 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4740 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004741 // Usage count limit tag is enforced by keystore, keymint does nothing.
4742 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
4743 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4744 }
4745}
4746
4747/*
4748 * UsageCountLimitTest.TestLimitUseRsa
4749 *
4750 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
4751 */
4752TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
4753 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4754
4755 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4756 .Authorization(TAG_NO_AUTH_REQUIRED)
4757 .RsaSigningKey(1024, 65537)
4758 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004759 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
4760 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08004761
4762 // Check the usage count limit tag appears in the authorizations.
4763 AuthorizationSet auths;
4764 for (auto& entry : key_characteristics_) {
4765 auths.push_back(AuthorizationSet(entry.authorizations));
4766 }
4767 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4768 << "key usage count limit " << 3U << " missing";
4769
4770 string message = "1234567890123456";
4771 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4772
4773 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4774 AuthorizationSet keystore_auths =
4775 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4776
4777 SignMessage(message, params);
4778 SignMessage(message, params);
4779 SignMessage(message, params);
4780
4781 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4782 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4783 // must be invalidated from secure storage (such as RPMB partition).
4784 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4785 } else {
4786 // Usage count limit tag is enforced by keystore, keymint does nothing.
4787 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08004788 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4789 }
4790}
4791
Qi Wu8e727f72021-02-11 02:49:33 +08004792/*
4793 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
4794 *
4795 * Verifies that when rollback resistance is supported by the KeyMint implementation with
4796 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
4797 * in hardware.
4798 */
4799TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
4800 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4801
4802 auto error = GenerateKey(AuthorizationSetBuilder()
4803 .RsaSigningKey(2048, 65537)
4804 .Digest(Digest::NONE)
4805 .Padding(PaddingMode::NONE)
4806 .Authorization(TAG_NO_AUTH_REQUIRED)
4807 .Authorization(TAG_ROLLBACK_RESISTANCE)
4808 .SetDefaultValidity());
4809 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4810
4811 if (error == ErrorCode::OK) {
4812 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
4813 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
4814 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4815 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4816
4817 // The KeyMint should also enforce single use key in hardware when it supports rollback
4818 // resistance.
4819 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4820 .Authorization(TAG_NO_AUTH_REQUIRED)
4821 .RsaSigningKey(1024, 65537)
4822 .NoDigestOrPadding()
4823 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4824 .SetDefaultValidity()));
4825
4826 // Check the usage count limit tag appears in the hardware authorizations.
4827 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4828 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4829 << "key usage count limit " << 1U << " missing";
4830
4831 string message = "1234567890123456";
4832 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4833
4834 // First usage of RSA key should work.
4835 SignMessage(message, params);
4836
4837 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4838 // must be invalidated from secure storage (such as RPMB partition).
4839 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4840 }
4841}
4842
Qi Wud22ec842020-11-26 13:27:53 +08004843INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
4844
Selene Huang31ab4042020-04-29 04:22:39 -07004845typedef KeyMintAidlTestBase AddEntropyTest;
4846
4847/*
4848 * AddEntropyTest.AddEntropy
4849 *
4850 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
4851 * is actually added.
4852 */
4853TEST_P(AddEntropyTest, AddEntropy) {
4854 string data = "foo";
4855 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
4856}
4857
4858/*
4859 * AddEntropyTest.AddEmptyEntropy
4860 *
4861 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
4862 */
4863TEST_P(AddEntropyTest, AddEmptyEntropy) {
4864 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
4865}
4866
4867/*
4868 * AddEntropyTest.AddLargeEntropy
4869 *
4870 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
4871 */
4872TEST_P(AddEntropyTest, AddLargeEntropy) {
4873 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
4874}
4875
4876INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
4877
Selene Huang31ab4042020-04-29 04:22:39 -07004878typedef KeyMintAidlTestBase KeyDeletionTest;
4879
4880/**
4881 * KeyDeletionTest.DeleteKey
4882 *
4883 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4884 * valid key blob.
4885 */
4886TEST_P(KeyDeletionTest, DeleteKey) {
4887 auto error = GenerateKey(AuthorizationSetBuilder()
4888 .RsaSigningKey(2048, 65537)
4889 .Digest(Digest::NONE)
4890 .Padding(PaddingMode::NONE)
4891 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004892 .Authorization(TAG_ROLLBACK_RESISTANCE)
4893 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004894 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4895
4896 // Delete must work if rollback protection is implemented
4897 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004898 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004899 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4900
4901 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4902
4903 string message = "12345678901234567890123456789012";
4904 AuthorizationSet begin_out_params;
4905 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4906 Begin(KeyPurpose::SIGN, key_blob_,
4907 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4908 &begin_out_params));
4909 AbortIfNeeded();
4910 key_blob_ = AidlBuf();
4911 }
4912}
4913
4914/**
4915 * KeyDeletionTest.DeleteInvalidKey
4916 *
4917 * This test checks that the HAL excepts invalid key blobs..
4918 */
4919TEST_P(KeyDeletionTest, DeleteInvalidKey) {
4920 // Generate key just to check if rollback protection is implemented
4921 auto error = GenerateKey(AuthorizationSetBuilder()
4922 .RsaSigningKey(2048, 65537)
4923 .Digest(Digest::NONE)
4924 .Padding(PaddingMode::NONE)
4925 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004926 .Authorization(TAG_ROLLBACK_RESISTANCE)
4927 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004928 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4929
4930 // Delete must work if rollback protection is implemented
4931 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004932 AuthorizationSet enforced(SecLevelAuthorizations());
4933 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004934
4935 // Delete the key we don't care about the result at this point.
4936 DeleteKey();
4937
4938 // Now create an invalid key blob and delete it.
4939 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
4940
4941 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4942 }
4943}
4944
4945/**
4946 * KeyDeletionTest.DeleteAllKeys
4947 *
4948 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4949 *
4950 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4951 * FBE/FDE encryption keys, which means that the device will not even boot until after the
4952 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4953 * been provisioned. Use this test only on dedicated testing devices that have no valuable
4954 * credentials stored in Keystore/Keymint.
4955 */
4956TEST_P(KeyDeletionTest, DeleteAllKeys) {
4957 if (!arm_deleteAllKeys) return;
4958 auto error = GenerateKey(AuthorizationSetBuilder()
4959 .RsaSigningKey(2048, 65537)
4960 .Digest(Digest::NONE)
4961 .Padding(PaddingMode::NONE)
4962 .Authorization(TAG_NO_AUTH_REQUIRED)
4963 .Authorization(TAG_ROLLBACK_RESISTANCE));
4964 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4965
4966 // Delete must work if rollback protection is implemented
4967 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004968 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004969 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4970
4971 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4972
4973 string message = "12345678901234567890123456789012";
4974 AuthorizationSet begin_out_params;
4975
4976 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4977 Begin(KeyPurpose::SIGN, key_blob_,
4978 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4979 &begin_out_params));
4980 AbortIfNeeded();
4981 key_blob_ = AidlBuf();
4982 }
4983}
4984
4985INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
4986
4987using UpgradeKeyTest = KeyMintAidlTestBase;
4988
4989/*
4990 * UpgradeKeyTest.UpgradeKey
4991 *
4992 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
4993 */
4994TEST_P(UpgradeKeyTest, UpgradeKey) {
4995 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4996 .AesEncryptionKey(128)
4997 .Padding(PaddingMode::NONE)
4998 .Authorization(TAG_NO_AUTH_REQUIRED)));
4999
5000 auto result = UpgradeKey(key_blob_);
5001
5002 // Key doesn't need upgrading. Should get okay, but no new key blob.
5003 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
5004}
5005
5006INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
5007
5008using ClearOperationsTest = KeyMintAidlTestBase;
5009
5010/*
5011 * ClearSlotsTest.TooManyOperations
5012 *
5013 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
5014 * operations are started without being finished or aborted. Also verifies
5015 * that aborting the operations clears the operations.
5016 *
5017 */
5018TEST_P(ClearOperationsTest, TooManyOperations) {
5019 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5020 .Authorization(TAG_NO_AUTH_REQUIRED)
5021 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005022 .Padding(PaddingMode::NONE)
5023 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005024
5025 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5026 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08005027 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07005028 AuthorizationSet out_params;
5029 ErrorCode result;
5030 size_t i;
5031
5032 for (i = 0; i < max_operations; i++) {
5033 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
5034 if (ErrorCode::OK != result) {
5035 break;
5036 }
5037 }
5038 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
5039 // Try again just in case there's a weird overflow bug
5040 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
5041 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5042 for (size_t j = 0; j < i; j++) {
5043 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
5044 << "Aboort failed for i = " << j << std::endl;
5045 }
5046 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5047 AbortIfNeeded();
5048}
5049
5050INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
5051
5052typedef KeyMintAidlTestBase TransportLimitTest;
5053
5054/*
5055 * TransportLimitTest.FinishInput
5056 *
5057 * Verifies that passing input data to finish succeeds as expected.
5058 */
5059TEST_P(TransportLimitTest, LargeFinishInput) {
5060 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5061 .Authorization(TAG_NO_AUTH_REQUIRED)
5062 .AesEncryptionKey(128)
5063 .BlockMode(BlockMode::ECB)
5064 .Padding(PaddingMode::NONE)));
5065
5066 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
5067 auto cipher_params =
5068 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5069
5070 AuthorizationSet out_params;
5071 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
5072
5073 string plain_message = std::string(1 << msg_size, 'x');
5074 string encrypted_message;
5075 auto rc = Finish(plain_message, &encrypted_message);
5076
5077 EXPECT_EQ(ErrorCode::OK, rc);
5078 EXPECT_EQ(plain_message.size(), encrypted_message.size())
5079 << "Encrypt finish returned OK, but did not consume all of the given input";
5080 cipher_params.push_back(out_params);
5081
5082 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
5083
5084 string decrypted_message;
5085 rc = Finish(encrypted_message, &decrypted_message);
5086 EXPECT_EQ(ErrorCode::OK, rc);
5087 EXPECT_EQ(plain_message.size(), decrypted_message.size())
5088 << "Decrypt finish returned OK, did not consume all of the given input";
5089 }
5090}
5091
5092INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
5093
David Zeuthene0c40892021-01-08 12:54:11 -05005094typedef KeyMintAidlTestBase KeyAgreementTest;
5095
5096int CurveToOpenSslCurveName(EcCurve curve) {
5097 switch (curve) {
5098 case EcCurve::P_224:
5099 return NID_secp224r1;
5100 case EcCurve::P_256:
5101 return NID_X9_62_prime256v1;
5102 case EcCurve::P_384:
5103 return NID_secp384r1;
5104 case EcCurve::P_521:
5105 return NID_secp521r1;
5106 }
5107}
5108
5109/*
5110 * KeyAgreementTest.Ecdh
5111 *
5112 * Verifies that ECDH works for all curves
5113 */
5114TEST_P(KeyAgreementTest, Ecdh) {
5115 // Because it's possible to use this API with keys on different curves, we
5116 // check all N^2 combinations where N is the number of supported
5117 // curves.
5118 //
5119 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
5120 // lot more curves we can be smart about things and just pick |otherCurve| so
5121 // it's not |curve| and that way we end up with only 2*N runs
5122 //
5123 for (auto curve : ValidCurves()) {
5124 for (auto localCurve : ValidCurves()) {
5125 // Generate EC key locally (with access to private key material)
5126 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
5127 int curveName = CurveToOpenSslCurveName(localCurve);
5128 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
5129 ASSERT_NE(group, nullptr);
5130 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
5131 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
5132 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
5133 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
5134
5135 // Get encoded form of the public part of the locally generated key...
5136 unsigned char* p = nullptr;
5137 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
5138 ASSERT_GT(encodedPublicKeySize, 0);
5139 vector<uint8_t> encodedPublicKey(
5140 reinterpret_cast<const uint8_t*>(p),
5141 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
5142 OPENSSL_free(p);
5143
5144 // Generate EC key in KeyMint (only access to public key material)
5145 vector<uint8_t> challenge = {0x41, 0x42};
5146 EXPECT_EQ(
5147 ErrorCode::OK,
5148 GenerateKey(AuthorizationSetBuilder()
5149 .Authorization(TAG_NO_AUTH_REQUIRED)
5150 .Authorization(TAG_EC_CURVE, curve)
5151 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
5152 .Authorization(TAG_ALGORITHM, Algorithm::EC)
5153 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08005154 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
5155 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05005156 << "Failed to generate key";
5157 ASSERT_GT(cert_chain_.size(), 0);
5158 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
5159 ASSERT_NE(kmKeyCert, nullptr);
5160 // Check that keyAgreement (bit 4) is set in KeyUsage
5161 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
5162 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
5163 ASSERT_NE(kmPkey, nullptr);
5164 if (dump_Attestations) {
5165 for (size_t n = 0; n < cert_chain_.size(); n++) {
5166 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
5167 }
5168 }
5169
5170 // Now that we have the two keys, we ask KeyMint to perform ECDH...
5171 if (curve != localCurve) {
5172 // If the keys are using different curves KeyMint should fail with
5173 // ErrorCode:INVALID_ARGUMENT. Check that.
5174 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5175 string ZabFromKeyMintStr;
5176 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
5177 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5178 &ZabFromKeyMintStr));
5179
5180 } else {
5181 // Otherwise if the keys are using the same curve, it should work.
5182 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5183 string ZabFromKeyMintStr;
5184 EXPECT_EQ(ErrorCode::OK,
5185 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5186 &ZabFromKeyMintStr));
5187 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
5188
5189 // Perform local ECDH between the two keys so we can check if we get the same Zab..
5190 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
5191 ASSERT_NE(ctx, nullptr);
5192 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
5193 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
5194 size_t ZabFromTestLen = 0;
5195 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
5196 vector<uint8_t> ZabFromTest;
5197 ZabFromTest.resize(ZabFromTestLen);
5198 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
5199
5200 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
5201 }
5202
5203 CheckedDeleteKey();
5204 }
5205 }
5206}
5207
5208INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
5209
Shawn Willdend659c7c2021-02-19 14:51:51 -07005210using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005211
5212TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
5213 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5214 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5215
5216 CheckedDeleteKey(&aesKeyData.blob);
5217 CheckedDeleteKey(&hmacKeyData.blob);
5218 CheckedDeleteKey(&rsaKeyData.blob);
5219 CheckedDeleteKey(&ecdsaKeyData.blob);
5220}
5221
5222// This is a more comprenhensive test, but it can only be run on a machine which is still in early
5223// boot stage, which no proper Android device is by the time we can run VTS. To use this,
5224// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
5225// early boot, so you'll have to reboot between runs.
5226TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
5227 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5228 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5229 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
5230 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5231 EXPECT_TRUE(
5232 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5233 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5234 EXPECT_TRUE(
5235 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5236
5237 // Should be able to use keys, since early boot has not ended
5238 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5239 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5240 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5241 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5242
5243 // End early boot
5244 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
5245 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
5246
5247 // Should not be able to use already-created keys.
5248 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
5249 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
5250 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
5251 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
5252
5253 CheckedDeleteKey(&aesKeyData.blob);
5254 CheckedDeleteKey(&hmacKeyData.blob);
5255 CheckedDeleteKey(&rsaKeyData.blob);
5256 CheckedDeleteKey(&ecdsaKeyData.blob);
5257
5258 // Should not be able to create new keys
5259 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
5260 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
5261
5262 CheckedDeleteKey(&aesKeyData.blob);
5263 CheckedDeleteKey(&hmacKeyData.blob);
5264 CheckedDeleteKey(&rsaKeyData.blob);
5265 CheckedDeleteKey(&ecdsaKeyData.blob);
5266}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005267
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005268INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
5269
Shawn Willdend659c7c2021-02-19 14:51:51 -07005270using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005271
5272// This may be a problematic test. It can't be run repeatedly without unlocking the device in
5273// between runs... and on most test devices there are no enrolled credentials so it can't be
5274// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
5275// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
5276// a manual test process, which includes unlocking between runs, which is why it's included here.
5277// Well, that and the fact that it's the only test we can do without also making calls into the
5278// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
5279// implications might be, so that may or may not be a solution.
5280TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
5281 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5282 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
5283
5284 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5285 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5286 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5287 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5288
5289 ErrorCode rc = GetReturnErrorCode(
5290 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
5291 ASSERT_EQ(ErrorCode::OK, rc);
5292 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
5293 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
5294 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
5295 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
5296
5297 CheckedDeleteKey(&aesKeyData.blob);
5298 CheckedDeleteKey(&hmacKeyData.blob);
5299 CheckedDeleteKey(&rsaKeyData.blob);
5300 CheckedDeleteKey(&ecdsaKeyData.blob);
5301}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005302
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005303INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
5304
Shawn Willdend659c7c2021-02-19 14:51:51 -07005305using PerformOperationTest = KeyMintAidlTestBase;
5306
5307TEST_P(PerformOperationTest, RequireUnimplemented) {
5308 vector<uint8_t> response;
5309 auto result = keymint_->performOperation({} /* request */, &response);
5310 ASSERT_EQ(GetReturnErrorCode(result), ErrorCode::UNIMPLEMENTED);
5311}
5312
5313INSTANTIATE_KEYMINT_AIDL_TEST(PerformOperationTest);
5314
Janis Danisevskis24c04702020-12-16 18:28:39 -08005315} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07005316
5317int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07005318 std::cout << "Testing ";
5319 auto halInstances =
5320 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
5321 std::cout << "HAL instances:\n";
5322 for (auto& entry : halInstances) {
5323 std::cout << " " << entry << '\n';
5324 }
5325
Selene Huang31ab4042020-04-29 04:22:39 -07005326 ::testing::InitGoogleTest(&argc, argv);
5327 for (int i = 1; i < argc; ++i) {
5328 if (argv[i][0] == '-') {
5329 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07005330 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5331 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07005332 }
5333 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07005334 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5335 dump_Attestations = true;
5336 } else {
5337 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07005338 }
5339 }
5340 }
Shawn Willden08a7e432020-12-11 13:05:27 +00005341 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07005342}