blob: 287b4dbd60b01f50a75fa7b9255fb22661d18ae7 [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) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000294 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700295 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
296 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
297
Selene Huang31ab4042020-04-29 04:22:39 -0700298 // Check that some unexpected tags/values are NOT present.
299 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
300 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000301 }
302
303 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
304 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
305 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
306 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
307
308 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
309 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
310 }
311
312 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
313 // TODO(swillden): Distinguish which params should be in which auth list.
314 AuthorizationSet auths;
315 for (auto& entry : keyCharacteristics) {
316 auths.push_back(AuthorizationSet(entry.authorizations));
317 }
318 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
319
320 // Verify that App data, ROT and auth timeout are NOT included.
321 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
322 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700323 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
324
David Drysdale7de9feb2021-03-05 14:56:19 +0000325 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700326 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000327 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700328 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700329 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000330 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700331 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000332
333 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700334 }
335};
336
337/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000338 * NewKeyGenerationTest.Aes
339 *
340 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
341 * have correct characteristics.
342 */
343TEST_P(NewKeyGenerationTest, Aes) {
344 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
345 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
346 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
347 SCOPED_TRACE(testing::Message()
348 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
349 vector<uint8_t> key_blob;
350 vector<KeyCharacteristics> key_characteristics;
351 auto builder = AuthorizationSetBuilder()
352 .AesEncryptionKey(key_size)
353 .BlockMode(block_mode)
354 .Padding(padding_mode)
355 .SetDefaultValidity();
356 if (block_mode == BlockMode::GCM) {
357 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
358 }
359 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
360
361 EXPECT_GT(key_blob.size(), 0U);
362 CheckSymmetricParams(key_characteristics);
363
364 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
365
366 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
367 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
368 << "Key size " << key_size << "missing";
369
370 CheckedDeleteKey(&key_blob);
371 }
372 }
373 }
374}
375
376/*
377 * NewKeyGenerationTest.AesInvalidSize
378 *
379 * Verifies that specifying an invalid key size for AES key generation returns
380 * UNSUPPORTED_KEY_SIZE.
381 */
382TEST_P(NewKeyGenerationTest, AesInvalidSize) {
383 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
384 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
385 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
386 SCOPED_TRACE(testing::Message()
387 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
388 vector<uint8_t> key_blob;
389 vector<KeyCharacteristics> key_characteristics;
390 auto builder = AuthorizationSetBuilder()
391 .AesEncryptionKey(key_size)
392 .BlockMode(block_mode)
393 .Padding(padding_mode)
394 .SetDefaultValidity();
395 if (block_mode == BlockMode::GCM) {
396 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
397 }
398 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
399 GenerateKey(builder, &key_blob, &key_characteristics));
400 }
401 }
402 }
403
404 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
405 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
406 vector<uint8_t> key_blob;
407 vector<KeyCharacteristics> key_characteristics;
408 // No key size specified
409 auto builder = AuthorizationSetBuilder()
410 .Authorization(TAG_ALGORITHM, Algorithm::AES)
411 .BlockMode(block_mode)
412 .Padding(padding_mode)
413 .SetDefaultValidity();
414 if (block_mode == BlockMode::GCM) {
415 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
416 }
417 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
418 GenerateKey(builder, &key_blob, &key_characteristics));
419 }
420 }
421}
422
423/*
424 * NewKeyGenerationTest.AesInvalidPadding
425 *
426 * Verifies that specifying an invalid padding on AES keys gives a failure
427 * somewhere along the way.
428 */
429TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
430 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
431 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
432 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
433 SCOPED_TRACE(testing::Message()
434 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
435 vector<uint8_t> key_blob;
436 vector<KeyCharacteristics> key_characteristics;
437 auto builder = AuthorizationSetBuilder()
438 .AesEncryptionKey(key_size)
439 .BlockMode(block_mode)
440 .Padding(padding_mode)
441 .SetDefaultValidity();
442 if (block_mode == BlockMode::GCM) {
443 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
444 }
445
446 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
447 if (result == ErrorCode::OK) {
448 // Key creation was OK but has generated a key that cannot be used.
449 auto params =
450 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
451 auto result = Begin(KeyPurpose::ENCRYPT, params);
452 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
453 result == ErrorCode::INVALID_KEY_BLOB);
454 } else {
455 // The KeyMint implementation detected that the generated key
456 // is unusable.
457 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
458 }
459 }
460 }
461 }
462}
463
464/*
465 * NewKeyGenerationTest.AesGcmMissingMinMac
466 *
467 * Verifies that specifying an invalid key size for AES key generation returns
468 * UNSUPPORTED_KEY_SIZE.
469 */
470TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
471 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
472 BlockMode block_mode = BlockMode::GCM;
473 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
474 SCOPED_TRACE(testing::Message()
475 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
476 vector<uint8_t> key_blob;
477 vector<KeyCharacteristics> key_characteristics;
478 // No MIN_MAC_LENGTH provided.
479 auto builder = AuthorizationSetBuilder()
480 .AesEncryptionKey(key_size)
481 .BlockMode(block_mode)
482 .Padding(padding_mode)
483 .SetDefaultValidity();
484 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
485 GenerateKey(builder, &key_blob, &key_characteristics));
486 }
487 }
488}
489
490/*
491 * NewKeyGenerationTest.TripleDes
492 *
493 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
494 * have correct characteristics.
495 */
496TEST_P(NewKeyGenerationTest, TripleDes) {
497 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
498 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
499 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
500 SCOPED_TRACE(testing::Message()
501 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
502 vector<uint8_t> key_blob;
503 vector<KeyCharacteristics> key_characteristics;
504 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
505 .TripleDesEncryptionKey(key_size)
506 .BlockMode(block_mode)
507 .Padding(padding_mode)
508 .Authorization(TAG_NO_AUTH_REQUIRED)
509 .SetDefaultValidity(),
510 &key_blob, &key_characteristics));
511
512 EXPECT_GT(key_blob.size(), 0U);
513 CheckSymmetricParams(key_characteristics);
514
515 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
516
517 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
518 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
519 << "Key size " << key_size << "missing";
520
521 CheckedDeleteKey(&key_blob);
522 }
523 }
524 }
525}
526
527/*
528 * NewKeyGenerationTest.TripleDesWithAttestation
529 *
530 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
531 * have correct characteristics.
532 *
533 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
534 * put in a certificate) but which isn't an error.
535 */
536TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
537 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
538 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
539 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
540 SCOPED_TRACE(testing::Message()
541 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
542
543 auto challenge = "hello";
544 auto app_id = "foo";
545
546 vector<uint8_t> key_blob;
547 vector<KeyCharacteristics> key_characteristics;
548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
549 .TripleDesEncryptionKey(key_size)
550 .BlockMode(block_mode)
551 .Padding(padding_mode)
552 .Authorization(TAG_NO_AUTH_REQUIRED)
553 .AttestationChallenge(challenge)
554 .AttestationApplicationId(app_id)
555 .SetDefaultValidity(),
556 &key_blob, &key_characteristics));
557
558 EXPECT_GT(key_blob.size(), 0U);
559 CheckSymmetricParams(key_characteristics);
560
561 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
562
563 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
564 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
565 << "Key size " << key_size << "missing";
566
567 CheckedDeleteKey(&key_blob);
568 }
569 }
570 }
571}
572
573/*
574 * NewKeyGenerationTest.TripleDesInvalidSize
575 *
576 * Verifies that specifying an invalid key size for 3-DES key generation returns
577 * UNSUPPORTED_KEY_SIZE.
578 */
579TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
580 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
581 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
582 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
583 SCOPED_TRACE(testing::Message()
584 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
585 vector<uint8_t> key_blob;
586 vector<KeyCharacteristics> key_characteristics;
587 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
588 GenerateKey(AuthorizationSetBuilder()
589 .TripleDesEncryptionKey(key_size)
590 .BlockMode(block_mode)
591 .Padding(padding_mode)
592 .Authorization(TAG_NO_AUTH_REQUIRED)
593 .SetDefaultValidity(),
594 &key_blob, &key_characteristics));
595 }
596 }
597 }
598
599 // Omitting the key size fails.
600 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
601 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
602 SCOPED_TRACE(testing::Message()
603 << "3DES-default-" << block_mode << "-" << padding_mode);
604 vector<uint8_t> key_blob;
605 vector<KeyCharacteristics> key_characteristics;
606 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
607 GenerateKey(AuthorizationSetBuilder()
608 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
609 .BlockMode(block_mode)
610 .Padding(padding_mode)
611 .Authorization(TAG_NO_AUTH_REQUIRED)
612 .SetDefaultValidity(),
613 &key_blob, &key_characteristics));
614 }
615 }
616}
617
618/*
Selene Huang31ab4042020-04-29 04:22:39 -0700619 * NewKeyGenerationTest.Rsa
620 *
621 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
622 * have correct characteristics.
623 */
624TEST_P(NewKeyGenerationTest, Rsa) {
625 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
626 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700627 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
629 .RsaSigningKey(key_size, 65537)
630 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800631 .Padding(PaddingMode::NONE)
632 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700633 &key_blob, &key_characteristics));
634
635 ASSERT_GT(key_blob.size(), 0U);
636 CheckBaseParams(key_characteristics);
637
Shawn Willden7f424372021-01-10 18:06:50 -0700638 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700639
640 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
641 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
642 << "Key size " << key_size << "missing";
643 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
644
645 CheckedDeleteKey(&key_blob);
646 }
647}
648
649/*
Qi Wud22ec842020-11-26 13:27:53 +0800650 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700651 *
652 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
653 * have correct characteristics.
654 */
655TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700656 auto challenge = "hello";
657 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700658
Selene Huang6e46f142021-04-20 19:20:11 -0700659 auto subject = "cert subj 2";
660 vector<uint8_t> subject_der(make_name_from_str(subject));
661
662 uint64_t serial_int = 66;
663 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
664
Selene Huang4f64c222021-04-13 19:54:36 -0700665 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700666 vector<uint8_t> key_blob;
667 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700668 ASSERT_EQ(ErrorCode::OK,
669 GenerateKey(AuthorizationSetBuilder()
670 .RsaSigningKey(key_size, 65537)
671 .Digest(Digest::NONE)
672 .Padding(PaddingMode::NONE)
673 .AttestationChallenge(challenge)
674 .AttestationApplicationId(app_id)
675 .Authorization(TAG_NO_AUTH_REQUIRED)
676 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
677 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
678 .SetDefaultValidity(),
679 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700680
681 ASSERT_GT(key_blob.size(), 0U);
682 CheckBaseParams(key_characteristics);
683
684 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
685
686 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
687 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
688 << "Key size " << key_size << "missing";
689 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
690
Selene Huang6e46f142021-04-20 19:20:11 -0700691 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700692 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700693 ASSERT_GT(cert_chain_.size(), 0);
694
695 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
696 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
697 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
698 sw_enforced, hw_enforced, SecLevel(),
699 cert_chain_[0].encodedCertificate));
700
701 CheckedDeleteKey(&key_blob);
702 }
703}
704
705/*
David Drysdale4dc01072021-04-01 12:17:35 +0100706 * NewKeyGenerationTest.RsaWithRpkAttestation
707 *
708 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
709 * that has been generated using an associate IRemotelyProvisionedComponent.
710 */
711TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
712 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
713 // instance.
714 std::shared_ptr<IRemotelyProvisionedComponent> rp;
715 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
716 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
717
718 // Generate a P-256 keypair to use as an attestation key.
719 MacedPublicKey macedPubKey;
720 std::vector<uint8_t> privateKeyBlob;
721 auto status =
722 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
723 ASSERT_TRUE(status.isOk());
724 vector<uint8_t> coseKeyData;
725 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
726
727 AttestationKey attestation_key;
728 attestation_key.keyBlob = std::move(privateKeyBlob);
729 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
730
731 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
732 auto challenge = "hello";
733 auto app_id = "foo";
734
735 vector<uint8_t> key_blob;
736 vector<KeyCharacteristics> key_characteristics;
737 ASSERT_EQ(ErrorCode::OK,
738 GenerateKey(AuthorizationSetBuilder()
739 .RsaSigningKey(key_size, 65537)
740 .Digest(Digest::NONE)
741 .Padding(PaddingMode::NONE)
742 .AttestationChallenge(challenge)
743 .AttestationApplicationId(app_id)
744 .Authorization(TAG_NO_AUTH_REQUIRED)
745 .SetDefaultValidity(),
746 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
747
748 ASSERT_GT(key_blob.size(), 0U);
749 CheckBaseParams(key_characteristics);
750
751 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
752
753 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
754 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
755 << "Key size " << key_size << "missing";
756 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
757
758 // Attestation by itself is not valid (last entry is not self-signed).
759 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
760
761 // The signature over the attested key should correspond to the P256 public key.
762 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
763 ASSERT_TRUE(key_cert.get());
764 EVP_PKEY_Ptr signing_pubkey;
765 p256_pub_key(coseKeyData, &signing_pubkey);
766 ASSERT_TRUE(signing_pubkey.get());
767
768 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
769 << "Verification of attested certificate failed "
770 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
771
772 CheckedDeleteKey(&key_blob);
773 }
774}
775
776/*
Selene Huang4f64c222021-04-13 19:54:36 -0700777 * NewKeyGenerationTest.RsaEncryptionWithAttestation
778 *
779 * Verifies that keymint attestation for RSA encryption keys with challenge and
780 * app id is also successful.
781 */
782TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
783 auto key_size = 2048;
784 auto challenge = "hello";
785 auto app_id = "foo";
786
Selene Huang6e46f142021-04-20 19:20:11 -0700787 auto subject = "subj 2";
788 vector<uint8_t> subject_der(make_name_from_str(subject));
789
790 uint64_t serial_int = 111166;
791 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
792
Selene Huang4f64c222021-04-13 19:54:36 -0700793 vector<uint8_t> key_blob;
794 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700795 ASSERT_EQ(ErrorCode::OK,
796 GenerateKey(AuthorizationSetBuilder()
797 .RsaEncryptionKey(key_size, 65537)
798 .Padding(PaddingMode::NONE)
799 .AttestationChallenge(challenge)
800 .AttestationApplicationId(app_id)
801 .Authorization(TAG_NO_AUTH_REQUIRED)
802 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
803 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
804 .SetDefaultValidity(),
805 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700806
807 ASSERT_GT(key_blob.size(), 0U);
808 AuthorizationSet auths;
809 for (auto& entry : key_characteristics) {
810 auths.push_back(AuthorizationSet(entry.authorizations));
811 }
812
813 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
814 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
815
816 // Verify that App data and ROT are NOT included.
817 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
818 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
819
820 // Check that some unexpected tags/values are NOT present.
821 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
822 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
823
824 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
825
826 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
827 ASSERT_TRUE(os_ver);
828 EXPECT_EQ(*os_ver, os_version());
829
830 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
831
832 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
833 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
834 << "Key size " << key_size << "missing";
835 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
836
Selene Huang6e46f142021-04-20 19:20:11 -0700837 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700838 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
839 ASSERT_GT(cert_chain_.size(), 0);
840
841 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
842 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
843 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
844 sw_enforced, hw_enforced, SecLevel(),
845 cert_chain_[0].encodedCertificate));
846
847 CheckedDeleteKey(&key_blob);
848}
849
850/*
851 * NewKeyGenerationTest.RsaWithSelfSign
852 *
853 * Verifies that attesting to RSA key generation is successful, and returns
854 * self signed certificate if no challenge is provided. And signing etc
855 * works as expected.
856 */
857TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -0700858 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
859 vector<uint8_t> subject_der(make_name_from_str(subject));
860
861 uint64_t serial_int = 0;
862 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
863
Selene Huang4f64c222021-04-13 19:54:36 -0700864 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
865 vector<uint8_t> key_blob;
866 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700867 ASSERT_EQ(ErrorCode::OK,
868 GenerateKey(AuthorizationSetBuilder()
869 .RsaSigningKey(key_size, 65537)
870 .Digest(Digest::NONE)
871 .Padding(PaddingMode::NONE)
872 .Authorization(TAG_NO_AUTH_REQUIRED)
873 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
874 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
875 .SetDefaultValidity(),
876 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700877
878 ASSERT_GT(key_blob.size(), 0U);
879 CheckBaseParams(key_characteristics);
880
881 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
882
883 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
884 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
885 << "Key size " << key_size << "missing";
886 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
887
Selene Huang6e46f142021-04-20 19:20:11 -0700888 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700889 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
890 ASSERT_EQ(cert_chain_.size(), 1);
891
892 CheckedDeleteKey(&key_blob);
893 }
894}
895
896/*
897 * NewKeyGenerationTest.RsaWithAttestationMissAppId
898 *
899 * Verifies that attesting to RSA checks for missing app ID.
900 */
901TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
902 auto challenge = "hello";
903 vector<uint8_t> key_blob;
904 vector<KeyCharacteristics> key_characteristics;
905
906 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
907 GenerateKey(AuthorizationSetBuilder()
908 .RsaSigningKey(2048, 65537)
909 .Digest(Digest::NONE)
910 .Padding(PaddingMode::NONE)
911 .AttestationChallenge(challenge)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
913 .SetDefaultValidity(),
914 &key_blob, &key_characteristics));
915}
916
917/*
918 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
919 *
920 * Verifies that attesting to RSA ignores app id if challenge is missing.
921 */
922TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
923 auto key_size = 2048;
924 auto app_id = "foo";
925
Selene Huang6e46f142021-04-20 19:20:11 -0700926 auto subject = "cert subj 2";
927 vector<uint8_t> subject_der(make_name_from_str(subject));
928
929 uint64_t serial_int = 1;
930 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
931
Selene Huang4f64c222021-04-13 19:54:36 -0700932 vector<uint8_t> key_blob;
933 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700934 ASSERT_EQ(ErrorCode::OK,
935 GenerateKey(AuthorizationSetBuilder()
936 .RsaSigningKey(key_size, 65537)
937 .Digest(Digest::NONE)
938 .Padding(PaddingMode::NONE)
939 .AttestationApplicationId(app_id)
940 .Authorization(TAG_NO_AUTH_REQUIRED)
941 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
942 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
943 .SetDefaultValidity(),
944 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700945
946 ASSERT_GT(key_blob.size(), 0U);
947 CheckBaseParams(key_characteristics);
948
949 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
950
951 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
952 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
953 << "Key size " << key_size << "missing";
954 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
955
Selene Huang6e46f142021-04-20 19:20:11 -0700956 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700957 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
958 ASSERT_EQ(cert_chain_.size(), 1);
959
960 CheckedDeleteKey(&key_blob);
961}
962
963/*
Qi Wud22ec842020-11-26 13:27:53 +0800964 * NewKeyGenerationTest.LimitedUsageRsa
965 *
966 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
967 * resulting keys have correct characteristics.
968 */
969TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
970 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
971 vector<uint8_t> key_blob;
972 vector<KeyCharacteristics> key_characteristics;
973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
974 .RsaSigningKey(key_size, 65537)
975 .Digest(Digest::NONE)
976 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800977 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
978 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800979 &key_blob, &key_characteristics));
980
981 ASSERT_GT(key_blob.size(), 0U);
982 CheckBaseParams(key_characteristics);
983
984 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
985
986 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
987 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
988 << "Key size " << key_size << "missing";
989 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
990
991 // Check the usage count limit tag appears in the authorizations.
992 AuthorizationSet auths;
993 for (auto& entry : key_characteristics) {
994 auths.push_back(AuthorizationSet(entry.authorizations));
995 }
996 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
997 << "key usage count limit " << 1U << " missing";
998
999 CheckedDeleteKey(&key_blob);
1000 }
1001}
1002
1003/*
Qi Wubeefae42021-01-28 23:16:37 +08001004 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1005 *
1006 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1007 * resulting keys have correct characteristics and attestation.
1008 */
1009TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001010 auto challenge = "hello";
1011 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001012
Selene Huang6e46f142021-04-20 19:20:11 -07001013 auto subject = "cert subj 2";
1014 vector<uint8_t> subject_der(make_name_from_str(subject));
1015
1016 uint64_t serial_int = 66;
1017 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1018
Selene Huang4f64c222021-04-13 19:54:36 -07001019 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001020 vector<uint8_t> key_blob;
1021 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001022 ASSERT_EQ(ErrorCode::OK,
1023 GenerateKey(AuthorizationSetBuilder()
1024 .RsaSigningKey(key_size, 65537)
1025 .Digest(Digest::NONE)
1026 .Padding(PaddingMode::NONE)
1027 .AttestationChallenge(challenge)
1028 .AttestationApplicationId(app_id)
1029 .Authorization(TAG_NO_AUTH_REQUIRED)
1030 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1031 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1032 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1033 .SetDefaultValidity(),
1034 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001035
1036 ASSERT_GT(key_blob.size(), 0U);
1037 CheckBaseParams(key_characteristics);
1038
1039 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1040
1041 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1042 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1043 << "Key size " << key_size << "missing";
1044 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1045
1046 // Check the usage count limit tag appears in the authorizations.
1047 AuthorizationSet auths;
1048 for (auto& entry : key_characteristics) {
1049 auths.push_back(AuthorizationSet(entry.authorizations));
1050 }
1051 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1052 << "key usage count limit " << 1U << " missing";
1053
1054 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001055 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001056 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001057 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001058
1059 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1060 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1061 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1062 sw_enforced, hw_enforced, SecLevel(),
1063 cert_chain_[0].encodedCertificate));
1064
1065 CheckedDeleteKey(&key_blob);
1066 }
1067}
1068
1069/*
Selene Huang31ab4042020-04-29 04:22:39 -07001070 * NewKeyGenerationTest.NoInvalidRsaSizes
1071 *
1072 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1073 */
1074TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1075 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1076 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001077 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001078 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1079 GenerateKey(AuthorizationSetBuilder()
1080 .RsaSigningKey(key_size, 65537)
1081 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001082 .Padding(PaddingMode::NONE)
1083 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001084 &key_blob, &key_characteristics));
1085 }
1086}
1087
1088/*
1089 * NewKeyGenerationTest.RsaNoDefaultSize
1090 *
1091 * Verifies that failing to specify a key size for RSA key generation returns
1092 * UNSUPPORTED_KEY_SIZE.
1093 */
1094TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1095 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1096 GenerateKey(AuthorizationSetBuilder()
1097 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1098 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001099 .SigningKey()
1100 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001101}
1102
1103/*
1104 * NewKeyGenerationTest.Ecdsa
1105 *
1106 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1107 * have correct characteristics.
1108 */
1109TEST_P(NewKeyGenerationTest, Ecdsa) {
1110 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1111 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001112 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1114 .EcdsaSigningKey(key_size)
1115 .Digest(Digest::NONE)
1116 .SetDefaultValidity(),
1117 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001118 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);
Selene Huang31ab4042020-04-29 04:22:39 -07001122
1123 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1124 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1125 << "Key size " << key_size << "missing";
1126
1127 CheckedDeleteKey(&key_blob);
1128 }
1129}
1130
1131/*
Selene Huang4f64c222021-04-13 19:54:36 -07001132 * NewKeyGenerationTest.EcdsaAttestation
1133 *
1134 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1135 * an attestation will be generated.
1136 */
1137TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1138 auto challenge = "hello";
1139 auto app_id = "foo";
1140
Selene Huang6e46f142021-04-20 19:20:11 -07001141 auto subject = "cert subj 2";
1142 vector<uint8_t> subject_der(make_name_from_str(subject));
1143
1144 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1145 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1146
Selene Huang4f64c222021-04-13 19:54:36 -07001147 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1148 vector<uint8_t> key_blob;
1149 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001150 ASSERT_EQ(ErrorCode::OK,
1151 GenerateKey(AuthorizationSetBuilder()
1152 .Authorization(TAG_NO_AUTH_REQUIRED)
1153 .EcdsaSigningKey(key_size)
1154 .Digest(Digest::NONE)
1155 .AttestationChallenge(challenge)
1156 .AttestationApplicationId(app_id)
1157 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1158 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1159 .SetDefaultValidity(),
1160 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001161 ASSERT_GT(key_blob.size(), 0U);
1162 CheckBaseParams(key_characteristics);
1163
1164 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1165
1166 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1167 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1168 << "Key size " << key_size << "missing";
1169
1170 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1171 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001172 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001173
1174 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1175 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1176 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1177 sw_enforced, hw_enforced, SecLevel(),
1178 cert_chain_[0].encodedCertificate));
1179
1180 CheckedDeleteKey(&key_blob);
1181 }
1182}
1183
1184/*
1185 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1186 *
1187 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1188 * the key will generate a self signed attestation.
1189 */
1190TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001191 auto subject = "cert subj 2";
1192 vector<uint8_t> subject_der(make_name_from_str(subject));
1193
1194 uint64_t serial_int = 0x123456FFF1234;
1195 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1196
Selene Huang4f64c222021-04-13 19:54:36 -07001197 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1198 vector<uint8_t> key_blob;
1199 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001200 ASSERT_EQ(ErrorCode::OK,
1201 GenerateKey(AuthorizationSetBuilder()
1202 .EcdsaSigningKey(key_size)
1203 .Digest(Digest::NONE)
1204 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1205 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1206 .SetDefaultValidity(),
1207 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001208 ASSERT_GT(key_blob.size(), 0U);
1209 CheckBaseParams(key_characteristics);
1210
1211 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1212
1213 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1214 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1215 << "Key size " << key_size << "missing";
1216
1217 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001218 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001219 ASSERT_EQ(cert_chain_.size(), 1);
1220
1221 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1222 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1223
1224 CheckedDeleteKey(&key_blob);
1225 }
1226}
1227
1228/*
1229 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1230 *
1231 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1232 * app id must also be provided or else it will fail.
1233 */
1234TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1235 auto challenge = "hello";
1236 vector<uint8_t> key_blob;
1237 vector<KeyCharacteristics> key_characteristics;
1238
1239 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1240 GenerateKey(AuthorizationSetBuilder()
1241 .EcdsaSigningKey(EcCurve::P_256)
1242 .Digest(Digest::NONE)
1243 .AttestationChallenge(challenge)
1244 .SetDefaultValidity(),
1245 &key_blob, &key_characteristics));
1246}
1247
1248/*
1249 * NewKeyGenerationTest.EcdsaIgnoreAppId
1250 *
1251 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1252 * any appid will be ignored, and keymint will generate a self sign certificate.
1253 */
1254TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1255 auto app_id = "foo";
1256
1257 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1258 vector<uint8_t> key_blob;
1259 vector<KeyCharacteristics> key_characteristics;
1260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1261 .EcdsaSigningKey(key_size)
1262 .Digest(Digest::NONE)
1263 .AttestationApplicationId(app_id)
1264 .SetDefaultValidity(),
1265 &key_blob, &key_characteristics));
1266
1267 ASSERT_GT(key_blob.size(), 0U);
1268 CheckBaseParams(key_characteristics);
1269
1270 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1271
1272 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1273 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1274 << "Key size " << key_size << "missing";
1275
1276 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1277 ASSERT_EQ(cert_chain_.size(), 1);
1278
1279 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1280 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1281
1282 CheckedDeleteKey(&key_blob);
1283 }
1284}
1285
1286/*
1287 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1288 *
1289 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1290 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1291 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1292 * to specify how many following bytes will be used to encode the length.
1293 */
1294TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1295 auto challenge = "hello";
1296 auto key_size = 256;
1297 std::vector<uint32_t> app_id_lengths{143, 258};
1298
1299 for (uint32_t length : app_id_lengths) {
1300 const string app_id(length, 'a');
1301 vector<uint8_t> key_blob;
1302 vector<KeyCharacteristics> key_characteristics;
1303 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1304 .Authorization(TAG_NO_AUTH_REQUIRED)
1305 .EcdsaSigningKey(key_size)
1306 .Digest(Digest::NONE)
1307 .AttestationChallenge(challenge)
1308 .AttestationApplicationId(app_id)
1309 .SetDefaultValidity(),
1310 &key_blob, &key_characteristics));
1311 ASSERT_GT(key_blob.size(), 0U);
1312 CheckBaseParams(key_characteristics);
1313
1314 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1315
1316 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1317 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1318 << "Key size " << key_size << "missing";
1319
1320 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1321 ASSERT_GT(cert_chain_.size(), 0);
1322
1323 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1324 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1325 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1326 sw_enforced, hw_enforced, SecLevel(),
1327 cert_chain_[0].encodedCertificate));
1328
1329 CheckedDeleteKey(&key_blob);
1330 }
1331}
1332
1333/*
Qi Wud22ec842020-11-26 13:27:53 +08001334 * NewKeyGenerationTest.LimitedUsageEcdsa
1335 *
1336 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1337 * resulting keys have correct characteristics.
1338 */
1339TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1340 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1341 vector<uint8_t> key_blob;
1342 vector<KeyCharacteristics> key_characteristics;
1343 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1344 .EcdsaSigningKey(key_size)
1345 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001346 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1347 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001348 &key_blob, &key_characteristics));
1349
1350 ASSERT_GT(key_blob.size(), 0U);
1351 CheckBaseParams(key_characteristics);
1352
1353 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1354
1355 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1356 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1357 << "Key size " << key_size << "missing";
1358
1359 // Check the usage count limit tag appears in the authorizations.
1360 AuthorizationSet auths;
1361 for (auto& entry : key_characteristics) {
1362 auths.push_back(AuthorizationSet(entry.authorizations));
1363 }
1364 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1365 << "key usage count limit " << 1U << " missing";
1366
1367 CheckedDeleteKey(&key_blob);
1368 }
1369}
1370
1371/*
Selene Huang31ab4042020-04-29 04:22:39 -07001372 * NewKeyGenerationTest.EcdsaDefaultSize
1373 *
1374 * Verifies that failing to specify a key size for EC key generation returns
1375 * UNSUPPORTED_KEY_SIZE.
1376 */
1377TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1378 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1379 GenerateKey(AuthorizationSetBuilder()
1380 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1381 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001382 .Digest(Digest::NONE)
1383 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001384}
1385
1386/*
1387 * NewKeyGenerationTest.EcdsaInvalidSize
1388 *
1389 * Verifies that specifying an invalid key size for EC key generation returns
1390 * UNSUPPORTED_KEY_SIZE.
1391 */
1392TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1393 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1394 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001395 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001396 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1397 .EcdsaSigningKey(key_size)
1398 .Digest(Digest::NONE)
1399 .SetDefaultValidity(),
1400 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001401 }
1402
Janis Danisevskis164bb872021-02-09 11:30:25 -08001403 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1404 .EcdsaSigningKey(190)
1405 .Digest(Digest::NONE)
1406 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001407}
1408
1409/*
1410 * NewKeyGenerationTest.EcdsaMismatchKeySize
1411 *
1412 * Verifies that specifying mismatched key size and curve for EC key generation returns
1413 * INVALID_ARGUMENT.
1414 */
1415TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1416 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1417
1418 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1419 GenerateKey(AuthorizationSetBuilder()
1420 .EcdsaSigningKey(224)
1421 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001422 .Digest(Digest::NONE)
1423 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001424}
1425
1426/*
1427 * NewKeyGenerationTest.EcdsaAllValidSizes
1428 *
1429 * Verifies that keymint supports all required EC key sizes.
1430 */
1431TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1432 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1433 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001434 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1435 .EcdsaSigningKey(size)
1436 .Digest(Digest::NONE)
1437 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001438 << "Failed to generate size: " << size;
1439 CheckedDeleteKey();
1440 }
1441}
1442
1443/*
1444 * NewKeyGenerationTest.EcdsaInvalidCurves
1445 *
1446 * Verifies that keymint does not support any curve designated as unsupported.
1447 */
1448TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1449 Digest digest;
1450 if (SecLevel() == SecurityLevel::STRONGBOX) {
1451 digest = Digest::SHA_2_256;
1452 } else {
1453 digest = Digest::SHA_2_512;
1454 }
1455 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001456 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1457 .EcdsaSigningKey(curve)
1458 .Digest(digest)
1459 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001460 << "Failed to generate key on curve: " << curve;
1461 CheckedDeleteKey();
1462 }
1463}
1464
1465/*
1466 * NewKeyGenerationTest.Hmac
1467 *
1468 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1469 * characteristics.
1470 */
1471TEST_P(NewKeyGenerationTest, Hmac) {
1472 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1473 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001474 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001475 constexpr size_t key_size = 128;
1476 ASSERT_EQ(ErrorCode::OK,
1477 GenerateKey(
1478 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1479 TAG_MIN_MAC_LENGTH, 128),
1480 &key_blob, &key_characteristics));
1481
1482 ASSERT_GT(key_blob.size(), 0U);
1483 CheckBaseParams(key_characteristics);
1484
Shawn Willden7f424372021-01-10 18:06:50 -07001485 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1486 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1487 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1488 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001489
1490 CheckedDeleteKey(&key_blob);
1491 }
1492}
1493
1494/*
Selene Huang4f64c222021-04-13 19:54:36 -07001495 * NewKeyGenerationTest.HmacNoAttestation
1496 *
1497 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1498 * and app id are provided.
1499 */
1500TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1501 auto challenge = "hello";
1502 auto app_id = "foo";
1503
1504 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1505 vector<uint8_t> key_blob;
1506 vector<KeyCharacteristics> key_characteristics;
1507 constexpr size_t key_size = 128;
1508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1509 .HmacKey(key_size)
1510 .Digest(digest)
1511 .AttestationChallenge(challenge)
1512 .AttestationApplicationId(app_id)
1513 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1514 &key_blob, &key_characteristics));
1515
1516 ASSERT_GT(key_blob.size(), 0U);
1517 ASSERT_EQ(cert_chain_.size(), 0);
1518 CheckBaseParams(key_characteristics);
1519
1520 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1521 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1522 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1523 << "Key size " << key_size << "missing";
1524
1525 CheckedDeleteKey(&key_blob);
1526 }
1527}
1528
1529/*
Qi Wud22ec842020-11-26 13:27:53 +08001530 * NewKeyGenerationTest.LimitedUsageHmac
1531 *
1532 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1533 * resulting keys have correct characteristics.
1534 */
1535TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1536 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1537 vector<uint8_t> key_blob;
1538 vector<KeyCharacteristics> key_characteristics;
1539 constexpr size_t key_size = 128;
1540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1541 .HmacKey(key_size)
1542 .Digest(digest)
1543 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1544 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1545 &key_blob, &key_characteristics));
1546
1547 ASSERT_GT(key_blob.size(), 0U);
1548 CheckBaseParams(key_characteristics);
1549
1550 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1551 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1552 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1553 << "Key size " << key_size << "missing";
1554
1555 // Check the usage count limit tag appears in the authorizations.
1556 AuthorizationSet auths;
1557 for (auto& entry : key_characteristics) {
1558 auths.push_back(AuthorizationSet(entry.authorizations));
1559 }
1560 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1561 << "key usage count limit " << 1U << " missing";
1562
1563 CheckedDeleteKey(&key_blob);
1564 }
1565}
1566
1567/*
Selene Huang31ab4042020-04-29 04:22:39 -07001568 * NewKeyGenerationTest.HmacCheckKeySizes
1569 *
1570 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1571 */
1572TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1573 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1574 if (key_size < 64 || key_size % 8 != 0) {
1575 // To keep this test from being very slow, we only test a random fraction of
1576 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1577 // them, we expect to run ~40 of them in each run.
1578 if (key_size % 8 == 0 || random() % 10 == 0) {
1579 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1580 GenerateKey(AuthorizationSetBuilder()
1581 .HmacKey(key_size)
1582 .Digest(Digest::SHA_2_256)
1583 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1584 << "HMAC key size " << key_size << " invalid";
1585 }
1586 } else {
1587 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1588 .HmacKey(key_size)
1589 .Digest(Digest::SHA_2_256)
1590 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1591 << "Failed to generate HMAC key of size " << key_size;
1592 CheckedDeleteKey();
1593 }
1594 }
1595}
1596
1597/*
1598 * NewKeyGenerationTest.HmacCheckMinMacLengths
1599 *
1600 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1601 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1602 * specific MAC length that failed, so reproducing a failed run will be easy.
1603 */
1604TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1605 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1606 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1607 // To keep this test from being very long, we only test a random fraction of
1608 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1609 // we expect to run ~17 of them in each run.
1610 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1611 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1612 GenerateKey(AuthorizationSetBuilder()
1613 .HmacKey(128)
1614 .Digest(Digest::SHA_2_256)
1615 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1616 << "HMAC min mac length " << min_mac_length << " invalid.";
1617 }
1618 } else {
1619 EXPECT_EQ(ErrorCode::OK,
1620 GenerateKey(AuthorizationSetBuilder()
1621 .HmacKey(128)
1622 .Digest(Digest::SHA_2_256)
1623 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1624 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1625 CheckedDeleteKey();
1626 }
1627 }
1628}
1629
1630/*
1631 * NewKeyGenerationTest.HmacMultipleDigests
1632 *
1633 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1634 */
1635TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1636 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1637
1638 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1639 GenerateKey(AuthorizationSetBuilder()
1640 .HmacKey(128)
1641 .Digest(Digest::SHA1)
1642 .Digest(Digest::SHA_2_256)
1643 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1644}
1645
1646/*
1647 * NewKeyGenerationTest.HmacDigestNone
1648 *
1649 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1650 */
1651TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1652 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1653 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1654 128)));
1655
1656 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1657 GenerateKey(AuthorizationSetBuilder()
1658 .HmacKey(128)
1659 .Digest(Digest::NONE)
1660 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1661}
1662
Selene Huang4f64c222021-04-13 19:54:36 -07001663/*
1664 * NewKeyGenerationTest.AesNoAttestation
1665 *
1666 * Verifies that attestation parameters to AES keys are ignored and generateKey
1667 * will succeed.
1668 */
1669TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1670 auto challenge = "hello";
1671 auto app_id = "foo";
1672
1673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1674 .Authorization(TAG_NO_AUTH_REQUIRED)
1675 .AesEncryptionKey(128)
1676 .EcbMode()
1677 .Padding(PaddingMode::PKCS7)
1678 .AttestationChallenge(challenge)
1679 .AttestationApplicationId(app_id)));
1680
1681 ASSERT_EQ(cert_chain_.size(), 0);
1682}
1683
1684/*
1685 * NewKeyGenerationTest.TripleDesNoAttestation
1686 *
1687 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1688 * will be successful. No attestation should be generated.
1689 */
1690TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1691 auto challenge = "hello";
1692 auto app_id = "foo";
1693
1694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1695 .TripleDesEncryptionKey(168)
1696 .BlockMode(BlockMode::ECB)
1697 .Authorization(TAG_NO_AUTH_REQUIRED)
1698 .Padding(PaddingMode::NONE)
1699 .AttestationChallenge(challenge)
1700 .AttestationApplicationId(app_id)));
1701 ASSERT_EQ(cert_chain_.size(), 0);
1702}
1703
Selene Huang31ab4042020-04-29 04:22:39 -07001704INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1705
1706typedef KeyMintAidlTestBase SigningOperationsTest;
1707
1708/*
1709 * SigningOperationsTest.RsaSuccess
1710 *
1711 * Verifies that raw RSA signature operations succeed.
1712 */
1713TEST_P(SigningOperationsTest, RsaSuccess) {
1714 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1715 .RsaSigningKey(2048, 65537)
1716 .Digest(Digest::NONE)
1717 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001718 .Authorization(TAG_NO_AUTH_REQUIRED)
1719 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001720 string message = "12345678901234567890123456789012";
1721 string signature = SignMessage(
1722 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1723}
1724
1725/*
1726 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1727 *
Shawn Willden7f424372021-01-10 18:06:50 -07001728 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001729 */
1730TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1731 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1732 .Authorization(TAG_NO_AUTH_REQUIRED)
1733 .RsaSigningKey(2048, 65537)
1734 .Digest(Digest::NONE)
1735 .Padding(PaddingMode::NONE)
1736 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001737 .Authorization(TAG_APPLICATION_DATA, "appdata")
1738 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001739 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1740 Begin(KeyPurpose::SIGN,
1741 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1742 AbortIfNeeded();
1743 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1744 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1745 .Digest(Digest::NONE)
1746 .Padding(PaddingMode::NONE)
1747 .Authorization(TAG_APPLICATION_ID, "clientid")));
1748 AbortIfNeeded();
1749 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1750 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1751 .Digest(Digest::NONE)
1752 .Padding(PaddingMode::NONE)
1753 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1754 AbortIfNeeded();
1755 EXPECT_EQ(ErrorCode::OK,
1756 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1757 .Digest(Digest::NONE)
1758 .Padding(PaddingMode::NONE)
1759 .Authorization(TAG_APPLICATION_DATA, "appdata")
1760 .Authorization(TAG_APPLICATION_ID, "clientid")));
1761 AbortIfNeeded();
1762}
1763
1764/*
1765 * SigningOperationsTest.RsaPssSha256Success
1766 *
1767 * Verifies that RSA-PSS signature operations succeed.
1768 */
1769TEST_P(SigningOperationsTest, RsaPssSha256Success) {
1770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1771 .RsaSigningKey(2048, 65537)
1772 .Digest(Digest::SHA_2_256)
1773 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001774 .Authorization(TAG_NO_AUTH_REQUIRED)
1775 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001776 // Use large message, which won't work without digesting.
1777 string message(1024, 'a');
1778 string signature = SignMessage(
1779 message,
1780 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1781}
1782
1783/*
1784 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1785 *
1786 * Verifies that keymint rejects signature operations that specify a padding mode when the key
1787 * supports only unpadded operations.
1788 */
1789TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1790 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1791 .RsaSigningKey(2048, 65537)
1792 .Digest(Digest::NONE)
1793 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001794 .Padding(PaddingMode::NONE)
1795 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001796 string message = "12345678901234567890123456789012";
1797 string signature;
1798
1799 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1800 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1801 .Digest(Digest::NONE)
1802 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1803}
1804
1805/*
1806 * SigningOperationsTest.NoUserConfirmation
1807 *
1808 * Verifies that keymint rejects signing operations for keys with
1809 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1810 * presented.
1811 */
1812TEST_P(SigningOperationsTest, NoUserConfirmation) {
1813 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001814 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1815 .RsaSigningKey(1024, 65537)
1816 .Digest(Digest::NONE)
1817 .Padding(PaddingMode::NONE)
1818 .Authorization(TAG_NO_AUTH_REQUIRED)
1819 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1820 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001821
1822 const string message = "12345678901234567890123456789012";
1823 EXPECT_EQ(ErrorCode::OK,
1824 Begin(KeyPurpose::SIGN,
1825 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1826 string signature;
1827 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1828}
1829
1830/*
1831 * SigningOperationsTest.RsaPkcs1Sha256Success
1832 *
1833 * Verifies that digested RSA-PKCS1 signature operations succeed.
1834 */
1835TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1836 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1837 .RsaSigningKey(2048, 65537)
1838 .Digest(Digest::SHA_2_256)
1839 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001840 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1841 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001842 string message(1024, 'a');
1843 string signature = SignMessage(message, AuthorizationSetBuilder()
1844 .Digest(Digest::SHA_2_256)
1845 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1846}
1847
1848/*
1849 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1850 *
1851 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1852 */
1853TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1854 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1855 .RsaSigningKey(2048, 65537)
1856 .Digest(Digest::NONE)
1857 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001858 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1859 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001860 string message(53, 'a');
1861 string signature = SignMessage(message, AuthorizationSetBuilder()
1862 .Digest(Digest::NONE)
1863 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1864}
1865
1866/*
1867 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1868 *
1869 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1870 * given a too-long message.
1871 */
1872TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1874 .RsaSigningKey(2048, 65537)
1875 .Digest(Digest::NONE)
1876 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001877 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1878 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001879 string message(257, 'a');
1880
1881 EXPECT_EQ(ErrorCode::OK,
1882 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1883 .Digest(Digest::NONE)
1884 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1885 string signature;
1886 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1887}
1888
1889/*
1890 * SigningOperationsTest.RsaPssSha512TooSmallKey
1891 *
1892 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1893 * used with a key that is too small for the message.
1894 *
1895 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
1896 * keymint specification requires that salt_size == digest_size, so the message will be
1897 * digest_size * 2 +
1898 * 16. Such a message can only be signed by a given key if the key is at least that size. This
1899 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
1900 * for a 1024-bit key.
1901 */
1902TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1903 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1905 .RsaSigningKey(1024, 65537)
1906 .Digest(Digest::SHA_2_512)
1907 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001908 .Padding(PaddingMode::RSA_PSS)
1909 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001910 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1911 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1912 .Digest(Digest::SHA_2_512)
1913 .Padding(PaddingMode::RSA_PSS)));
1914}
1915
1916/*
1917 * SigningOperationsTest.RsaNoPaddingTooLong
1918 *
1919 * Verifies that raw RSA signature operations fail with the correct error code when
1920 * given a too-long message.
1921 */
1922TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1924 .RsaSigningKey(2048, 65537)
1925 .Digest(Digest::NONE)
1926 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001927 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1928 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001929 // One byte too long
1930 string message(2048 / 8 + 1, 'a');
1931 ASSERT_EQ(ErrorCode::OK,
1932 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1933 .Digest(Digest::NONE)
1934 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1935 string result;
1936 ErrorCode finish_error_code = Finish(message, &result);
1937 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1938 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1939
1940 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1941 message = string(128 * 1024, 'a');
1942 ASSERT_EQ(ErrorCode::OK,
1943 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1944 .Digest(Digest::NONE)
1945 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1946 finish_error_code = Finish(message, &result);
1947 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1948 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1949}
1950
1951/*
1952 * SigningOperationsTest.RsaAbort
1953 *
1954 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1955 * test, but the behavior should be algorithm and purpose-independent.
1956 */
1957TEST_P(SigningOperationsTest, RsaAbort) {
1958 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1959 .RsaSigningKey(2048, 65537)
1960 .Digest(Digest::NONE)
1961 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001962 .Padding(PaddingMode::NONE)
1963 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001964
1965 ASSERT_EQ(ErrorCode::OK,
1966 Begin(KeyPurpose::SIGN,
1967 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1968 EXPECT_EQ(ErrorCode::OK, Abort());
1969
1970 // Another abort should fail
1971 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1972
1973 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001974 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001975}
1976
1977/*
1978 * SigningOperationsTest.RsaUnsupportedPadding
1979 *
1980 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1981 * with a padding mode inappropriate for RSA.
1982 */
1983TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1985 .RsaSigningKey(2048, 65537)
1986 .Authorization(TAG_NO_AUTH_REQUIRED)
1987 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001988 .Padding(PaddingMode::PKCS7)
1989 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001990 ASSERT_EQ(
1991 ErrorCode::UNSUPPORTED_PADDING_MODE,
1992 Begin(KeyPurpose::SIGN,
1993 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1994}
1995
1996/*
1997 * SigningOperationsTest.RsaPssNoDigest
1998 *
1999 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2000 */
2001TEST_P(SigningOperationsTest, RsaNoDigest) {
2002 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2003 .RsaSigningKey(2048, 65537)
2004 .Authorization(TAG_NO_AUTH_REQUIRED)
2005 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002006 .Padding(PaddingMode::RSA_PSS)
2007 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002008 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2009 Begin(KeyPurpose::SIGN,
2010 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2011
2012 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2013 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2014}
2015
2016/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002017 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002018 *
2019 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2020 * supported in some cases (as validated in other tests), but a mode must be specified.
2021 */
2022TEST_P(SigningOperationsTest, RsaNoPadding) {
2023 // Padding must be specified
2024 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2025 .RsaKey(2048, 65537)
2026 .Authorization(TAG_NO_AUTH_REQUIRED)
2027 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002028 .Digest(Digest::NONE)
2029 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002030 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2031 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2032}
2033
2034/*
2035 * SigningOperationsTest.RsaShortMessage
2036 *
2037 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2038 */
2039TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2041 .Authorization(TAG_NO_AUTH_REQUIRED)
2042 .RsaSigningKey(2048, 65537)
2043 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002044 .Padding(PaddingMode::NONE)
2045 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002046
2047 // Barely shorter
2048 string message(2048 / 8 - 1, 'a');
2049 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2050
2051 // Much shorter
2052 message = "a";
2053 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2054}
2055
2056/*
2057 * SigningOperationsTest.RsaSignWithEncryptionKey
2058 *
2059 * Verifies that RSA encryption keys cannot be used to sign.
2060 */
2061TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2062 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2063 .Authorization(TAG_NO_AUTH_REQUIRED)
2064 .RsaEncryptionKey(2048, 65537)
2065 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002066 .Padding(PaddingMode::NONE)
2067 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002068 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2069 Begin(KeyPurpose::SIGN,
2070 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2071}
2072
2073/*
2074 * SigningOperationsTest.RsaSignTooLargeMessage
2075 *
2076 * Verifies that attempting a raw signature of a message which is the same length as the key,
2077 * but numerically larger than the public modulus, fails with the correct error.
2078 */
2079TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2081 .Authorization(TAG_NO_AUTH_REQUIRED)
2082 .RsaSigningKey(2048, 65537)
2083 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002084 .Padding(PaddingMode::NONE)
2085 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002086
2087 // Largest possible message will always be larger than the public modulus.
2088 string message(2048 / 8, static_cast<char>(0xff));
2089 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2090 .Authorization(TAG_NO_AUTH_REQUIRED)
2091 .Digest(Digest::NONE)
2092 .Padding(PaddingMode::NONE)));
2093 string signature;
2094 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2095}
2096
2097/*
2098 * SigningOperationsTest.EcdsaAllSizesAndHashes
2099 *
2100 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2101 */
2102TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2103 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2104 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2105 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2106 .Authorization(TAG_NO_AUTH_REQUIRED)
2107 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002108 .Digest(digest)
2109 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002110 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2111 << " and digest " << digest;
2112 if (error != ErrorCode::OK) continue;
2113
2114 string message(1024, 'a');
2115 if (digest == Digest::NONE) message.resize(key_size / 8);
2116 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2117 CheckedDeleteKey();
2118 }
2119 }
2120}
2121
2122/*
2123 * SigningOperationsTest.EcdsaAllCurves
2124 *
2125 * Verifies that ECDSA operations succeed with all possible curves.
2126 */
2127TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2128 for (auto curve : ValidCurves()) {
2129 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2130 .Authorization(TAG_NO_AUTH_REQUIRED)
2131 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002132 .Digest(Digest::SHA_2_256)
2133 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002134 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2135 if (error != ErrorCode::OK) continue;
2136
2137 string message(1024, 'a');
2138 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2139 CheckedDeleteKey();
2140 }
2141}
2142
2143/*
2144 * SigningOperationsTest.EcdsaNoDigestHugeData
2145 *
2146 * Verifies that ECDSA operations support very large messages, even without digesting. This
2147 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2148 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2149 * the framework.
2150 */
2151TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2153 .Authorization(TAG_NO_AUTH_REQUIRED)
2154 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002155 .Digest(Digest::NONE)
2156 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002157 string message(1 * 1024, 'a');
2158 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2159}
2160
2161/*
2162 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2163 *
2164 * Verifies that using an EC key requires the correct app ID/data.
2165 */
2166TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2167 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2168 .Authorization(TAG_NO_AUTH_REQUIRED)
2169 .EcdsaSigningKey(256)
2170 .Digest(Digest::NONE)
2171 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002172 .Authorization(TAG_APPLICATION_DATA, "appdata")
2173 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002174 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2175 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2176 AbortIfNeeded();
2177 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2178 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2179 .Digest(Digest::NONE)
2180 .Authorization(TAG_APPLICATION_ID, "clientid")));
2181 AbortIfNeeded();
2182 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2183 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2184 .Digest(Digest::NONE)
2185 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2186 AbortIfNeeded();
2187 EXPECT_EQ(ErrorCode::OK,
2188 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2189 .Digest(Digest::NONE)
2190 .Authorization(TAG_APPLICATION_DATA, "appdata")
2191 .Authorization(TAG_APPLICATION_ID, "clientid")));
2192 AbortIfNeeded();
2193}
2194
2195/*
2196 * SigningOperationsTest.AesEcbSign
2197 *
2198 * Verifies that attempts to use AES keys to sign fail in the correct way.
2199 */
2200TEST_P(SigningOperationsTest, AesEcbSign) {
2201 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2202 .Authorization(TAG_NO_AUTH_REQUIRED)
2203 .SigningKey()
2204 .AesEncryptionKey(128)
2205 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2206
2207 AuthorizationSet out_params;
2208 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2209 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2210 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2211 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2212}
2213
2214/*
2215 * SigningOperationsTest.HmacAllDigests
2216 *
2217 * Verifies that HMAC works with all digests.
2218 */
2219TEST_P(SigningOperationsTest, HmacAllDigests) {
2220 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2221 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2222 .Authorization(TAG_NO_AUTH_REQUIRED)
2223 .HmacKey(128)
2224 .Digest(digest)
2225 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2226 << "Failed to create HMAC key with digest " << digest;
2227 string message = "12345678901234567890123456789012";
2228 string signature = MacMessage(message, digest, 160);
2229 EXPECT_EQ(160U / 8U, signature.size())
2230 << "Failed to sign with HMAC key with digest " << digest;
2231 CheckedDeleteKey();
2232 }
2233}
2234
2235/*
2236 * SigningOperationsTest.HmacSha256TooLargeMacLength
2237 *
2238 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2239 * digest size.
2240 */
2241TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2242 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2243 .Authorization(TAG_NO_AUTH_REQUIRED)
2244 .HmacKey(128)
2245 .Digest(Digest::SHA_2_256)
2246 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2247 AuthorizationSet output_params;
2248 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2249 AuthorizationSetBuilder()
2250 .Digest(Digest::SHA_2_256)
2251 .Authorization(TAG_MAC_LENGTH, 264),
2252 &output_params));
2253}
2254
2255/*
2256 * SigningOperationsTest.HmacSha256TooSmallMacLength
2257 *
2258 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2259 * specified minimum MAC length.
2260 */
2261TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2262 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2263 .Authorization(TAG_NO_AUTH_REQUIRED)
2264 .HmacKey(128)
2265 .Digest(Digest::SHA_2_256)
2266 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2267 AuthorizationSet output_params;
2268 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2269 AuthorizationSetBuilder()
2270 .Digest(Digest::SHA_2_256)
2271 .Authorization(TAG_MAC_LENGTH, 120),
2272 &output_params));
2273}
2274
2275/*
2276 * SigningOperationsTest.HmacRfc4231TestCase3
2277 *
2278 * Validates against the test vectors from RFC 4231 test case 3.
2279 */
2280TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2281 string key(20, 0xaa);
2282 string message(50, 0xdd);
2283 uint8_t sha_224_expected[] = {
2284 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2285 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2286 };
2287 uint8_t sha_256_expected[] = {
2288 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2289 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2290 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2291 };
2292 uint8_t sha_384_expected[] = {
2293 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2294 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2295 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2296 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2297 };
2298 uint8_t sha_512_expected[] = {
2299 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2300 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2301 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2302 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2303 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2304 };
2305
2306 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2307 if (SecLevel() != SecurityLevel::STRONGBOX) {
2308 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2309 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2310 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2311 }
2312}
2313
2314/*
2315 * SigningOperationsTest.HmacRfc4231TestCase5
2316 *
2317 * Validates against the test vectors from RFC 4231 test case 5.
2318 */
2319TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2320 string key(20, 0x0c);
2321 string message = "Test With Truncation";
2322
2323 uint8_t sha_224_expected[] = {
2324 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2325 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2326 };
2327 uint8_t sha_256_expected[] = {
2328 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2329 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2330 };
2331 uint8_t sha_384_expected[] = {
2332 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2333 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2334 };
2335 uint8_t sha_512_expected[] = {
2336 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2337 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2338 };
2339
2340 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2341 if (SecLevel() != SecurityLevel::STRONGBOX) {
2342 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2343 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2344 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2345 }
2346}
2347
2348INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2349
2350typedef KeyMintAidlTestBase VerificationOperationsTest;
2351
2352/*
2353 * VerificationOperationsTest.RsaSuccess
2354 *
2355 * Verifies that a simple RSA signature/verification sequence succeeds.
2356 */
2357TEST_P(VerificationOperationsTest, RsaSuccess) {
2358 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2359 .Authorization(TAG_NO_AUTH_REQUIRED)
2360 .RsaSigningKey(2048, 65537)
2361 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002362 .Padding(PaddingMode::NONE)
2363 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002364 string message = "12345678901234567890123456789012";
2365 string signature = SignMessage(
2366 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2367 VerifyMessage(message, signature,
2368 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2369}
2370
2371/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002372 * VerificationOperationsTest.RsaAllPaddingsAndDigests
Selene Huang31ab4042020-04-29 04:22:39 -07002373 *
2374 * Verifies RSA signature/verification for all padding modes and digests.
2375 */
2376TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2377 auto authorizations = AuthorizationSetBuilder()
2378 .Authorization(TAG_NO_AUTH_REQUIRED)
2379 .RsaSigningKey(2048, 65537)
2380 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2381 .Padding(PaddingMode::NONE)
2382 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002383 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2384 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002385
2386 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2387
2388 string message(128, 'a');
2389 string corrupt_message(message);
2390 ++corrupt_message[corrupt_message.size() / 2];
2391
2392 for (auto padding :
2393 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2394 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2395 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2396 // Digesting only makes sense with padding.
2397 continue;
2398 }
2399
2400 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2401 // PSS requires digesting.
2402 continue;
2403 }
2404
2405 string signature =
2406 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2407 VerifyMessage(message, signature,
2408 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2409
2410 /* TODO(seleneh) add exportkey tests back later when we have decided on
2411 * the new api.
2412 if (digest != Digest::NONE) {
2413 // Verify with OpenSSL.
2414 vector<uint8_t> pubkey;
2415 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2416
2417 const uint8_t* p = pubkey.data();
2418 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2419 ASSERT_TRUE(pkey.get());
2420
2421 EVP_MD_CTX digest_ctx;
2422 EVP_MD_CTX_init(&digest_ctx);
2423 EVP_PKEY_CTX* pkey_ctx;
2424 const EVP_MD* md = openssl_digest(digest);
2425 ASSERT_NE(md, nullptr);
2426 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2427 nullptr, pkey.get()));
2428
2429 switch (padding) {
2430 case PaddingMode::RSA_PSS:
2431 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2432 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2433 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2434 // PKCS1 is the default; don't need to set anything.
2435 break;
2436 default:
2437 FAIL();
2438 break;
2439 }
2440
2441 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2442 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2443 reinterpret_cast<const
2444 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2445 }
2446 */
2447
2448 // Corrupt signature shouldn't verify.
2449 string corrupt_signature(signature);
2450 ++corrupt_signature[corrupt_signature.size() / 2];
2451
2452 EXPECT_EQ(ErrorCode::OK,
2453 Begin(KeyPurpose::VERIFY,
2454 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2455 string result;
2456 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2457
2458 // Corrupt message shouldn't verify
2459 EXPECT_EQ(ErrorCode::OK,
2460 Begin(KeyPurpose::VERIFY,
2461 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2462 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2463 }
2464 }
2465}
2466
2467/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002468 * VerificationOperationsTest.RsaAllDigestsAndCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002469 *
2470 * Verifies ECDSA signature/verification for all digests and curves.
2471 */
2472TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2473 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2474
2475 string message = "1234567890";
2476 string corrupt_message = "2234567890";
2477 for (auto curve : ValidCurves()) {
2478 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2479 .Authorization(TAG_NO_AUTH_REQUIRED)
2480 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002481 .Digest(digests)
2482 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002483 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2484 if (error != ErrorCode::OK) {
2485 continue;
2486 }
2487
2488 for (auto digest : digests) {
2489 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2490 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2491
2492 /* TODO(seleneh) add exportkey tests back later when we have decided on
2493 * the new api.
2494
2495 // Verify with OpenSSL
2496 if (digest != Digest::NONE) {
2497 vector<uint8_t> pubkey;
2498 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2499 << curve << ' ' << digest;
2500
2501 const uint8_t* p = pubkey.data();
2502 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2503 ASSERT_TRUE(pkey.get());
2504
2505 EVP_MD_CTX digest_ctx;
2506 EVP_MD_CTX_init(&digest_ctx);
2507 EVP_PKEY_CTX* pkey_ctx;
2508 const EVP_MD* md = openssl_digest(digest);
2509
2510 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2511 nullptr, pkey.get()))
2512 << curve << ' ' << digest;
2513
2514 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2515 message.size()))
2516 << curve << ' ' << digest;
2517
2518 EXPECT_EQ(1,
2519 EVP_DigestVerifyFinal(&digest_ctx,
2520 reinterpret_cast<const
2521 uint8_t*>(signature.data()), signature.size()))
2522 << curve << ' ' << digest;
2523
2524 EVP_MD_CTX_cleanup(&digest_ctx);
2525 }
2526 */
2527 // Corrupt signature shouldn't verify.
2528 string corrupt_signature(signature);
2529 ++corrupt_signature[corrupt_signature.size() / 2];
2530
2531 EXPECT_EQ(ErrorCode::OK,
2532 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2533 << curve << ' ' << digest;
2534
2535 string result;
2536 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2537 << curve << ' ' << digest;
2538
2539 // Corrupt message shouldn't verify
2540 EXPECT_EQ(ErrorCode::OK,
2541 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2542 << curve << ' ' << digest;
2543
2544 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2545 << curve << ' ' << digest;
2546 }
2547
2548 auto rc = DeleteKey();
2549 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2550 }
2551}
2552
2553/*
2554 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2555 *
2556 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2557 */
2558TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2559 string key_material = "HelloThisIsAKey";
2560
2561 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002562 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002563 EXPECT_EQ(ErrorCode::OK,
2564 ImportKey(AuthorizationSetBuilder()
2565 .Authorization(TAG_NO_AUTH_REQUIRED)
2566 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2567 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2568 .Digest(Digest::SHA_2_256)
2569 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2570 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2571 EXPECT_EQ(ErrorCode::OK,
2572 ImportKey(AuthorizationSetBuilder()
2573 .Authorization(TAG_NO_AUTH_REQUIRED)
2574 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2575 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2576 .Digest(Digest::SHA_2_256)
2577 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2578 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2579
2580 string message = "This is a message.";
2581 string signature = SignMessage(
2582 signing_key, message,
2583 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2584
2585 // Signing key should not work.
2586 AuthorizationSet out_params;
2587 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2588 Begin(KeyPurpose::VERIFY, signing_key,
2589 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2590
2591 // Verification key should work.
2592 VerifyMessage(verification_key, message, signature,
2593 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2594
2595 CheckedDeleteKey(&signing_key);
2596 CheckedDeleteKey(&verification_key);
2597}
2598
2599INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2600
2601typedef KeyMintAidlTestBase ExportKeyTest;
2602
2603/*
2604 * ExportKeyTest.RsaUnsupportedKeyFormat
2605 *
2606 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2607 */
2608// TODO(seleneh) add ExportKey to GenerateKey
2609// check result
2610
2611class ImportKeyTest : public KeyMintAidlTestBase {
2612 public:
2613 template <TagType tag_type, Tag tag, typename ValueT>
2614 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2615 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002616 for (auto& entry : key_characteristics_) {
2617 if (entry.securityLevel == SecLevel()) {
2618 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2619 << "Tag " << tag << " with value " << expected
2620 << " not found at security level" << entry.securityLevel;
2621 } else {
2622 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2623 << "Tag " << tag << " found at security level " << entry.securityLevel;
2624 }
Selene Huang31ab4042020-04-29 04:22:39 -07002625 }
2626 }
2627
2628 void CheckOrigin() {
2629 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002630 // Origin isn't a crypto param, but it always lives with them.
2631 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002632 }
2633};
2634
2635/*
2636 * ImportKeyTest.RsaSuccess
2637 *
2638 * Verifies that importing and using an RSA key pair works correctly.
2639 */
2640TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002641 uint32_t key_size;
2642 string key;
2643
2644 if (SecLevel() == SecurityLevel::STRONGBOX) {
2645 key_size = 2048;
2646 key = rsa_2048_key;
2647 } else {
2648 key_size = 1024;
2649 key = rsa_key;
2650 }
2651
Selene Huang31ab4042020-04-29 04:22:39 -07002652 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2653 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07002654 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07002655 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002656 .Padding(PaddingMode::RSA_PSS)
2657 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07002658 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07002659
2660 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07002661 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002662 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2663 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2664 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2665 CheckOrigin();
2666
2667 string message(1024 / 8, 'a');
2668 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2669 string signature = SignMessage(message, params);
2670 VerifyMessage(message, signature, params);
2671}
2672
2673/*
2674 * ImportKeyTest.RsaKeySizeMismatch
2675 *
2676 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2677 * correct way.
2678 */
2679TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2680 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2681 ImportKey(AuthorizationSetBuilder()
2682 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2683 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002684 .Padding(PaddingMode::NONE)
2685 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002686 KeyFormat::PKCS8, rsa_key));
2687}
2688
2689/*
2690 * ImportKeyTest.RsaPublicExponentMismatch
2691 *
2692 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
2693 * fails in the correct way.
2694 */
2695TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2696 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2697 ImportKey(AuthorizationSetBuilder()
2698 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2699 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002700 .Padding(PaddingMode::NONE)
2701 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002702 KeyFormat::PKCS8, rsa_key));
2703}
2704
2705/*
2706 * ImportKeyTest.EcdsaSuccess
2707 *
2708 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2709 */
2710TEST_P(ImportKeyTest, EcdsaSuccess) {
2711 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2712 .Authorization(TAG_NO_AUTH_REQUIRED)
2713 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002714 .Digest(Digest::SHA_2_256)
2715 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002716 KeyFormat::PKCS8, ec_256_key));
2717
2718 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2719 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2720 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2721 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2722
2723 CheckOrigin();
2724
2725 string message(32, 'a');
2726 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2727 string signature = SignMessage(message, params);
2728 VerifyMessage(message, signature, params);
2729}
2730
2731/*
2732 * ImportKeyTest.EcdsaP256RFC5915Success
2733 *
2734 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
2735 * correctly.
2736 */
2737TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
2738 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2739 .Authorization(TAG_NO_AUTH_REQUIRED)
2740 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002741 .Digest(Digest::SHA_2_256)
2742 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002743 KeyFormat::PKCS8, ec_256_key_rfc5915));
2744
2745 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2746 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2747 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2748 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2749
2750 CheckOrigin();
2751
2752 string message(32, 'a');
2753 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2754 string signature = SignMessage(message, params);
2755 VerifyMessage(message, signature, params);
2756}
2757
2758/*
2759 * ImportKeyTest.EcdsaP256SEC1Success
2760 *
2761 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
2762 */
2763TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
2764 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2765 .Authorization(TAG_NO_AUTH_REQUIRED)
2766 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002767 .Digest(Digest::SHA_2_256)
2768 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002769 KeyFormat::PKCS8, ec_256_key_sec1));
2770
2771 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2772 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2773 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2774 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2775
2776 CheckOrigin();
2777
2778 string message(32, 'a');
2779 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2780 string signature = SignMessage(message, params);
2781 VerifyMessage(message, signature, params);
2782}
2783
2784/*
2785 * ImportKeyTest.Ecdsa521Success
2786 *
2787 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2788 */
2789TEST_P(ImportKeyTest, Ecdsa521Success) {
2790 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2791 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2792 .Authorization(TAG_NO_AUTH_REQUIRED)
2793 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002794 .Digest(Digest::SHA_2_256)
2795 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002796 KeyFormat::PKCS8, ec_521_key));
2797
2798 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2799 CheckCryptoParam(TAG_KEY_SIZE, 521U);
2800 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2801 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2802 CheckOrigin();
2803
2804 string message(32, 'a');
2805 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2806 string signature = SignMessage(message, params);
2807 VerifyMessage(message, signature, params);
2808}
2809
2810/*
2811 * ImportKeyTest.EcdsaSizeMismatch
2812 *
2813 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2814 * correct way.
2815 */
2816TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2817 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2818 ImportKey(AuthorizationSetBuilder()
2819 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002820 .Digest(Digest::NONE)
2821 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002822 KeyFormat::PKCS8, ec_256_key));
2823}
2824
2825/*
2826 * ImportKeyTest.EcdsaCurveMismatch
2827 *
2828 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
2829 * the correct way.
2830 */
2831TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2832 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2833 ImportKey(AuthorizationSetBuilder()
2834 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002835 .Digest(Digest::NONE)
2836 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002837 KeyFormat::PKCS8, ec_256_key));
2838}
2839
2840/*
2841 * ImportKeyTest.AesSuccess
2842 *
2843 * Verifies that importing and using an AES key works.
2844 */
2845TEST_P(ImportKeyTest, AesSuccess) {
2846 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2847 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2848 .Authorization(TAG_NO_AUTH_REQUIRED)
2849 .AesEncryptionKey(key.size() * 8)
2850 .EcbMode()
2851 .Padding(PaddingMode::PKCS7),
2852 KeyFormat::RAW, key));
2853
2854 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2855 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2856 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2857 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2858 CheckOrigin();
2859
2860 string message = "Hello World!";
2861 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2862 string ciphertext = EncryptMessage(message, params);
2863 string plaintext = DecryptMessage(ciphertext, params);
2864 EXPECT_EQ(message, plaintext);
2865}
2866
2867/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002868 * ImportKeyTest.AesFailure
2869 *
2870 * Verifies that importing an invalid AES key fails.
2871 */
2872TEST_P(ImportKeyTest, AesFailure) {
2873 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2874 uint32_t bitlen = key.size() * 8;
2875 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
2876 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2877 ImportKey(AuthorizationSetBuilder()
2878 .Authorization(TAG_NO_AUTH_REQUIRED)
2879 .AesEncryptionKey(key_size)
2880 .EcbMode()
2881 .Padding(PaddingMode::PKCS7),
2882 KeyFormat::RAW, key));
2883 }
2884}
2885
2886/*
2887 * ImportKeyTest.TripleDesSuccess
2888 *
2889 * Verifies that importing and using a 3DES key works.
2890 */
2891TEST_P(ImportKeyTest, TripleDesSuccess) {
2892 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
2893 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2894 .Authorization(TAG_NO_AUTH_REQUIRED)
2895 .TripleDesEncryptionKey(168)
2896 .EcbMode()
2897 .Padding(PaddingMode::PKCS7),
2898 KeyFormat::RAW, key));
2899
2900 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
2901 CheckCryptoParam(TAG_KEY_SIZE, 168U);
2902 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2903 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2904 CheckOrigin();
2905
2906 string message = "Hello World!";
2907 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2908 string ciphertext = EncryptMessage(message, params);
2909 string plaintext = DecryptMessage(ciphertext, params);
2910 EXPECT_EQ(message, plaintext);
2911}
2912
2913/*
2914 * ImportKeyTest.TripleDesFailure
2915 *
2916 * Verifies that importing an invalid 3DES key fails.
2917 */
2918TEST_P(ImportKeyTest, TripleDesFailure) {
2919 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
2920 uint32_t bitlen = key.size() * 8;
2921 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
2922 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2923 ImportKey(AuthorizationSetBuilder()
2924 .Authorization(TAG_NO_AUTH_REQUIRED)
2925 .TripleDesEncryptionKey(key_size)
2926 .EcbMode()
2927 .Padding(PaddingMode::PKCS7),
2928 KeyFormat::RAW, key));
2929 }
2930}
2931
2932/*
2933 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07002934 *
2935 * Verifies that importing and using an HMAC key works.
2936 */
2937TEST_P(ImportKeyTest, HmacKeySuccess) {
2938 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2939 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2940 .Authorization(TAG_NO_AUTH_REQUIRED)
2941 .HmacKey(key.size() * 8)
2942 .Digest(Digest::SHA_2_256)
2943 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2944 KeyFormat::RAW, key));
2945
2946 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2947 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2948 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2949 CheckOrigin();
2950
2951 string message = "Hello World!";
2952 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2953 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2954}
2955
2956INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
2957
2958auto wrapped_key = hex2str(
2959 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
2960 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
2961 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
2962 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
2963 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
2964 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
2965 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
2966 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
2967 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
2968
2969auto wrapped_key_masked = hex2str(
2970 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
2971 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
2972 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
2973 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
2974 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
2975 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
2976 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
2977 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
2978 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
2979
2980auto wrapping_key = hex2str(
2981 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
2982 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
2983 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
2984 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
2985 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
2986 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
2987 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
2988 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
2989 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
2990 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
2991 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
2992 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
2993 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
2994 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
2995 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
2996 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
2997 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
2998 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
2999 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
3000 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
3001 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
3002 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
3003 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
3004 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
3005 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
3006 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
3007 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
3008 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
3009 "f27ba61be6ad02dfddda8f4e6822");
3010
3011string zero_masking_key =
3012 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3013string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3014
3015class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3016
3017TEST_P(ImportWrappedKeyTest, Success) {
3018 auto wrapping_key_desc = AuthorizationSetBuilder()
3019 .RsaEncryptionKey(2048, 65537)
3020 .Digest(Digest::SHA_2_256)
3021 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003022 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3023 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003024
3025 ASSERT_EQ(ErrorCode::OK,
3026 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3027 AuthorizationSetBuilder()
3028 .Digest(Digest::SHA_2_256)
3029 .Padding(PaddingMode::RSA_OAEP)));
3030
3031 string message = "Hello World!";
3032 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3033 string ciphertext = EncryptMessage(message, params);
3034 string plaintext = DecryptMessage(ciphertext, params);
3035 EXPECT_EQ(message, plaintext);
3036}
3037
3038TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3039 auto wrapping_key_desc = AuthorizationSetBuilder()
3040 .RsaEncryptionKey(2048, 65537)
3041 .Digest(Digest::SHA_2_256)
3042 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003043 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3044 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003045
3046 ASSERT_EQ(ErrorCode::OK,
3047 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3048 AuthorizationSetBuilder()
3049 .Digest(Digest::SHA_2_256)
3050 .Padding(PaddingMode::RSA_OAEP)));
3051}
3052
3053TEST_P(ImportWrappedKeyTest, WrongMask) {
3054 auto wrapping_key_desc = AuthorizationSetBuilder()
3055 .RsaEncryptionKey(2048, 65537)
3056 .Digest(Digest::SHA_2_256)
3057 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003058 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3059 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003060
3061 ASSERT_EQ(
3062 ErrorCode::VERIFICATION_FAILED,
3063 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3064 AuthorizationSetBuilder()
3065 .Digest(Digest::SHA_2_256)
3066 .Padding(PaddingMode::RSA_OAEP)));
3067}
3068
3069TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3070 auto wrapping_key_desc = AuthorizationSetBuilder()
3071 .RsaEncryptionKey(2048, 65537)
3072 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003073 .Padding(PaddingMode::RSA_OAEP)
3074 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003075
3076 ASSERT_EQ(
3077 ErrorCode::INCOMPATIBLE_PURPOSE,
3078 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3079 AuthorizationSetBuilder()
3080 .Digest(Digest::SHA_2_256)
3081 .Padding(PaddingMode::RSA_OAEP)));
3082}
3083
3084INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3085
3086typedef KeyMintAidlTestBase EncryptionOperationsTest;
3087
3088/*
3089 * EncryptionOperationsTest.RsaNoPaddingSuccess
3090 *
3091 * Verifies that raw RSA encryption works.
3092 */
3093TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
3094 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3095 .Authorization(TAG_NO_AUTH_REQUIRED)
3096 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003097 .Padding(PaddingMode::NONE)
3098 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003099
3100 string message = string(2048 / 8, 'a');
3101 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3102 string ciphertext1 = EncryptMessage(message, params);
3103 EXPECT_EQ(2048U / 8, ciphertext1.size());
3104
3105 string ciphertext2 = EncryptMessage(message, params);
3106 EXPECT_EQ(2048U / 8, ciphertext2.size());
3107
3108 // Unpadded RSA is deterministic
3109 EXPECT_EQ(ciphertext1, ciphertext2);
3110}
3111
3112/*
3113 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3114 *
3115 * Verifies that raw RSA encryption of short messages works.
3116 */
3117TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3118 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3119 .Authorization(TAG_NO_AUTH_REQUIRED)
3120 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003121 .Padding(PaddingMode::NONE)
3122 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003123
3124 string message = "1";
3125 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3126
3127 string ciphertext = EncryptMessage(message, params);
3128 EXPECT_EQ(2048U / 8, ciphertext.size());
3129
3130 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3131 string plaintext = DecryptMessage(ciphertext, params);
3132
3133 EXPECT_EQ(expected_plaintext, plaintext);
3134
3135 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
3136 message = static_cast<char>(1);
3137 ciphertext = EncryptMessage(message, params);
3138 EXPECT_EQ(2048U / 8, ciphertext.size());
3139 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
3140}
3141
3142/*
3143 * EncryptionOperationsTest.RsaNoPaddingTooLong
3144 *
3145 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
3146 */
3147TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
3148 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3149 .Authorization(TAG_NO_AUTH_REQUIRED)
3150 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003151 .Padding(PaddingMode::NONE)
3152 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003153
3154 string message(2048 / 8 + 1, 'a');
3155
3156 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3157 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3158
3159 string result;
3160 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
3161}
3162
3163/*
3164 * EncryptionOperationsTest.RsaNoPaddingTooLarge
3165 *
3166 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
3167 * way.
3168 */
3169// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
3170// version of ExportKey inside generateKey
3171
3172/*
3173 * EncryptionOperationsTest.RsaOaepSuccess
3174 *
3175 * Verifies that RSA-OAEP encryption operations work, with all digests.
3176 */
3177TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3178 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3179
3180 size_t key_size = 2048; // Need largish key for SHA-512 test.
3181 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3182 .Authorization(TAG_NO_AUTH_REQUIRED)
3183 .RsaEncryptionKey(key_size, 65537)
3184 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003185 .Digest(digests)
3186 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003187
3188 string message = "Hello";
3189
3190 for (auto digest : digests) {
3191 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
3192 string ciphertext1 = EncryptMessage(message, params);
3193 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3194 EXPECT_EQ(key_size / 8, ciphertext1.size());
3195
3196 string ciphertext2 = EncryptMessage(message, params);
3197 EXPECT_EQ(key_size / 8, ciphertext2.size());
3198
3199 // OAEP randomizes padding so every result should be different (with astronomically high
3200 // probability).
3201 EXPECT_NE(ciphertext1, ciphertext2);
3202
3203 string plaintext1 = DecryptMessage(ciphertext1, params);
3204 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3205 string plaintext2 = DecryptMessage(ciphertext2, params);
3206 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3207
3208 // Decrypting corrupted ciphertext should fail.
3209 size_t offset_to_corrupt = random() % ciphertext1.size();
3210 char corrupt_byte;
3211 do {
3212 corrupt_byte = static_cast<char>(random() % 256);
3213 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3214 ciphertext1[offset_to_corrupt] = corrupt_byte;
3215
3216 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3217 string result;
3218 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3219 EXPECT_EQ(0U, result.size());
3220 }
3221}
3222
3223/*
3224 * EncryptionOperationsTest.RsaOaepInvalidDigest
3225 *
3226 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3227 * without a digest.
3228 */
3229TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3230 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3231 .Authorization(TAG_NO_AUTH_REQUIRED)
3232 .RsaEncryptionKey(2048, 65537)
3233 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003234 .Digest(Digest::NONE)
3235 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003236 string message = "Hello World!";
3237
3238 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
3239 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3240}
3241
3242/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003243 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003244 *
3245 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
3246 * with a different digest than was used to encrypt.
3247 */
3248TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3249 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3250
3251 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3252 .Authorization(TAG_NO_AUTH_REQUIRED)
3253 .RsaEncryptionKey(1024, 65537)
3254 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003255 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3256 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003257 string message = "Hello World!";
3258 string ciphertext = EncryptMessage(
3259 message,
3260 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3261
3262 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3263 .Digest(Digest::SHA_2_256)
3264 .Padding(PaddingMode::RSA_OAEP)));
3265 string result;
3266 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3267 EXPECT_EQ(0U, result.size());
3268}
3269
3270/*
3271 * EncryptionOperationsTest.RsaOaepTooLarge
3272 *
3273 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
3274 * too-large message.
3275 */
3276TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
3277 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3278 .Authorization(TAG_NO_AUTH_REQUIRED)
3279 .RsaEncryptionKey(2048, 65537)
3280 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003281 .Digest(Digest::SHA_2_256)
3282 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003283 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
3284 constexpr size_t oaep_overhead = 2 * digest_size + 2;
3285 string message(2048 / 8 - oaep_overhead + 1, 'a');
3286 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3287 .Padding(PaddingMode::RSA_OAEP)
3288 .Digest(Digest::SHA_2_256)));
3289 string result;
3290 ErrorCode error = Finish(message, &result);
3291 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3292 EXPECT_EQ(0U, result.size());
3293}
3294
3295/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003296 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3297 *
3298 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
3299 * digests.
3300 */
3301TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3302 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3303
3304 size_t key_size = 2048; // Need largish key for SHA-512 test.
3305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3306 .OaepMGFDigest(digests)
3307 .Authorization(TAG_NO_AUTH_REQUIRED)
3308 .RsaEncryptionKey(key_size, 65537)
3309 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003310 .Digest(Digest::SHA_2_256)
3311 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003312
3313 string message = "Hello";
3314
3315 for (auto digest : digests) {
3316 auto params = AuthorizationSetBuilder()
3317 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3318 .Digest(Digest::SHA_2_256)
3319 .Padding(PaddingMode::RSA_OAEP);
3320 string ciphertext1 = EncryptMessage(message, params);
3321 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3322 EXPECT_EQ(key_size / 8, ciphertext1.size());
3323
3324 string ciphertext2 = EncryptMessage(message, params);
3325 EXPECT_EQ(key_size / 8, ciphertext2.size());
3326
3327 // OAEP randomizes padding so every result should be different (with astronomically high
3328 // probability).
3329 EXPECT_NE(ciphertext1, ciphertext2);
3330
3331 string plaintext1 = DecryptMessage(ciphertext1, params);
3332 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3333 string plaintext2 = DecryptMessage(ciphertext2, params);
3334 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3335
3336 // Decrypting corrupted ciphertext should fail.
3337 size_t offset_to_corrupt = random() % ciphertext1.size();
3338 char corrupt_byte;
3339 do {
3340 corrupt_byte = static_cast<char>(random() % 256);
3341 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3342 ciphertext1[offset_to_corrupt] = corrupt_byte;
3343
3344 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3345 string result;
3346 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3347 EXPECT_EQ(0U, result.size());
3348 }
3349}
3350
3351/*
3352 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3353 *
3354 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3355 * with incompatible MGF digest.
3356 */
3357TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3358 ASSERT_EQ(ErrorCode::OK,
3359 GenerateKey(AuthorizationSetBuilder()
3360 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3361 .Authorization(TAG_NO_AUTH_REQUIRED)
3362 .RsaEncryptionKey(2048, 65537)
3363 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003364 .Digest(Digest::SHA_2_256)
3365 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003366 string message = "Hello World!";
3367
3368 auto params = AuthorizationSetBuilder()
3369 .Padding(PaddingMode::RSA_OAEP)
3370 .Digest(Digest::SHA_2_256)
3371 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
3372 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3373}
3374
3375/*
3376 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
3377 *
3378 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3379 * with unsupported MGF digest.
3380 */
3381TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
3382 ASSERT_EQ(ErrorCode::OK,
3383 GenerateKey(AuthorizationSetBuilder()
3384 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3385 .Authorization(TAG_NO_AUTH_REQUIRED)
3386 .RsaEncryptionKey(2048, 65537)
3387 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003388 .Digest(Digest::SHA_2_256)
3389 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003390 string message = "Hello World!";
3391
3392 auto params = AuthorizationSetBuilder()
3393 .Padding(PaddingMode::RSA_OAEP)
3394 .Digest(Digest::SHA_2_256)
3395 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
3396 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3397}
3398
3399/*
Selene Huang31ab4042020-04-29 04:22:39 -07003400 * EncryptionOperationsTest.RsaPkcs1Success
3401 *
3402 * Verifies that RSA PKCS encryption/decrypts works.
3403 */
3404TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
3405 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3406 .Authorization(TAG_NO_AUTH_REQUIRED)
3407 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003408 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3409 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003410
3411 string message = "Hello World!";
3412 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3413 string ciphertext1 = EncryptMessage(message, params);
3414 EXPECT_EQ(2048U / 8, ciphertext1.size());
3415
3416 string ciphertext2 = EncryptMessage(message, params);
3417 EXPECT_EQ(2048U / 8, ciphertext2.size());
3418
3419 // PKCS1 v1.5 randomizes padding so every result should be different.
3420 EXPECT_NE(ciphertext1, ciphertext2);
3421
3422 string plaintext = DecryptMessage(ciphertext1, params);
3423 EXPECT_EQ(message, plaintext);
3424
3425 // Decrypting corrupted ciphertext should fail.
3426 size_t offset_to_corrupt = random() % ciphertext1.size();
3427 char corrupt_byte;
3428 do {
3429 corrupt_byte = static_cast<char>(random() % 256);
3430 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3431 ciphertext1[offset_to_corrupt] = corrupt_byte;
3432
3433 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3434 string result;
3435 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3436 EXPECT_EQ(0U, result.size());
3437}
3438
3439/*
3440 * EncryptionOperationsTest.RsaPkcs1TooLarge
3441 *
3442 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
3443 */
3444TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
3445 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3446 .Authorization(TAG_NO_AUTH_REQUIRED)
3447 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003448 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3449 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003450 string message(2048 / 8 - 10, 'a');
3451
3452 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3453 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3454 string result;
3455 ErrorCode error = Finish(message, &result);
3456 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3457 EXPECT_EQ(0U, result.size());
3458}
3459
3460/*
3461 * EncryptionOperationsTest.EcdsaEncrypt
3462 *
3463 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
3464 */
3465TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
3466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3467 .Authorization(TAG_NO_AUTH_REQUIRED)
3468 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003469 .Digest(Digest::NONE)
3470 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003471 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3472 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3473 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3474}
3475
3476/*
3477 * EncryptionOperationsTest.HmacEncrypt
3478 *
3479 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
3480 */
3481TEST_P(EncryptionOperationsTest, HmacEncrypt) {
3482 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3483 .Authorization(TAG_NO_AUTH_REQUIRED)
3484 .HmacKey(128)
3485 .Digest(Digest::SHA_2_256)
3486 .Padding(PaddingMode::NONE)
3487 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3488 auto params = AuthorizationSetBuilder()
3489 .Digest(Digest::SHA_2_256)
3490 .Padding(PaddingMode::NONE)
3491 .Authorization(TAG_MAC_LENGTH, 128);
3492 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3493 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3494}
3495
3496/*
3497 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3498 *
3499 * Verifies that AES ECB mode works.
3500 */
3501TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
3502 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3503 .Authorization(TAG_NO_AUTH_REQUIRED)
3504 .AesEncryptionKey(128)
3505 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3506 .Padding(PaddingMode::NONE)));
3507
3508 ASSERT_GT(key_blob_.size(), 0U);
3509 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3510
3511 // Two-block message.
3512 string message = "12345678901234567890123456789012";
3513 string ciphertext1 = EncryptMessage(message, params);
3514 EXPECT_EQ(message.size(), ciphertext1.size());
3515
3516 string ciphertext2 = EncryptMessage(string(message), params);
3517 EXPECT_EQ(message.size(), ciphertext2.size());
3518
3519 // ECB is deterministic.
3520 EXPECT_EQ(ciphertext1, ciphertext2);
3521
3522 string plaintext = DecryptMessage(ciphertext1, params);
3523 EXPECT_EQ(message, plaintext);
3524}
3525
3526/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003527 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07003528 *
3529 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
3530 */
3531TEST_P(EncryptionOperationsTest, AesWrongMode) {
3532 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3533 .Authorization(TAG_NO_AUTH_REQUIRED)
3534 .AesEncryptionKey(128)
3535 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3536 .Padding(PaddingMode::NONE)));
3537
3538 ASSERT_GT(key_blob_.size(), 0U);
3539
3540 // Two-block message.
3541 string message = "12345678901234567890123456789012";
3542 EXPECT_EQ(
3543 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
3544 Begin(KeyPurpose::ENCRYPT,
3545 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
3546}
3547
3548/*
3549 * EncryptionOperationsTest.AesWrongPurpose
3550 *
3551 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
3552 * specified.
3553 */
3554TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
3555 auto err = GenerateKey(AuthorizationSetBuilder()
3556 .Authorization(TAG_NO_AUTH_REQUIRED)
3557 .AesKey(128)
3558 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
3559 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3560 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3561 .Padding(PaddingMode::NONE));
3562 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
3563 ASSERT_GT(key_blob_.size(), 0U);
3564
3565 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3566 .BlockMode(BlockMode::GCM)
3567 .Padding(PaddingMode::NONE)
3568 .Authorization(TAG_MAC_LENGTH, 128));
3569 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3570
3571 CheckedDeleteKey();
3572
3573 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3574 .Authorization(TAG_NO_AUTH_REQUIRED)
3575 .AesKey(128)
3576 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
3577 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3578 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3579 .Padding(PaddingMode::NONE)));
3580
3581 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3582 .BlockMode(BlockMode::GCM)
3583 .Padding(PaddingMode::NONE)
3584 .Authorization(TAG_MAC_LENGTH, 128));
3585 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3586}
3587
3588/*
3589 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
3590 *
3591 * Verifies that AES encryption fails in the correct way when provided an input that is not a
3592 * multiple of the block size and no padding is specified.
3593 */
3594TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
3595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3596 .Authorization(TAG_NO_AUTH_REQUIRED)
3597 .AesEncryptionKey(128)
3598 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3599 .Padding(PaddingMode::NONE)));
3600 // Message is slightly shorter than two blocks.
3601 string message(16 * 2 - 1, 'a');
3602
3603 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3604 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3605 string ciphertext;
3606 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
3607 EXPECT_EQ(0U, ciphertext.size());
3608}
3609
3610/*
3611 * EncryptionOperationsTest.AesEcbPkcs7Padding
3612 *
3613 * Verifies that AES PKCS7 padding works for any message length.
3614 */
3615TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
3616 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3617 .Authorization(TAG_NO_AUTH_REQUIRED)
3618 .AesEncryptionKey(128)
3619 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3620 .Padding(PaddingMode::PKCS7)));
3621
3622 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3623
3624 // Try various message lengths; all should work.
3625 for (size_t i = 0; i < 32; ++i) {
3626 string message(i, 'a');
3627 string ciphertext = EncryptMessage(message, params);
3628 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
3629 string plaintext = DecryptMessage(ciphertext, params);
3630 EXPECT_EQ(message, plaintext);
3631 }
3632}
3633
3634/*
3635 * EncryptionOperationsTest.AesEcbWrongPadding
3636 *
3637 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
3638 * specified.
3639 */
3640TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
3641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3642 .Authorization(TAG_NO_AUTH_REQUIRED)
3643 .AesEncryptionKey(128)
3644 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3645 .Padding(PaddingMode::NONE)));
3646
3647 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3648
3649 // Try various message lengths; all should fail
3650 for (size_t i = 0; i < 32; ++i) {
3651 string message(i, 'a');
3652 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3653 }
3654}
3655
3656/*
3657 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
3658 *
3659 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
3660 */
3661TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
3662 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3663 .Authorization(TAG_NO_AUTH_REQUIRED)
3664 .AesEncryptionKey(128)
3665 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3666 .Padding(PaddingMode::PKCS7)));
3667
3668 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3669
3670 string message = "a";
3671 string ciphertext = EncryptMessage(message, params);
3672 EXPECT_EQ(16U, ciphertext.size());
3673 EXPECT_NE(ciphertext, message);
3674 ++ciphertext[ciphertext.size() / 2];
3675
3676 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3677 string plaintext;
3678 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3679}
3680
3681vector<uint8_t> CopyIv(const AuthorizationSet& set) {
3682 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003683 EXPECT_TRUE(iv);
3684 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07003685}
3686
3687/*
3688 * EncryptionOperationsTest.AesCtrRoundTripSuccess
3689 *
3690 * Verifies that AES CTR mode works.
3691 */
3692TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3693 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3694 .Authorization(TAG_NO_AUTH_REQUIRED)
3695 .AesEncryptionKey(128)
3696 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3697 .Padding(PaddingMode::NONE)));
3698
3699 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3700
3701 string message = "123";
3702 AuthorizationSet out_params;
3703 string ciphertext1 = EncryptMessage(message, params, &out_params);
3704 vector<uint8_t> iv1 = CopyIv(out_params);
3705 EXPECT_EQ(16U, iv1.size());
3706
3707 EXPECT_EQ(message.size(), ciphertext1.size());
3708
3709 out_params.Clear();
3710 string ciphertext2 = EncryptMessage(message, params, &out_params);
3711 vector<uint8_t> iv2 = CopyIv(out_params);
3712 EXPECT_EQ(16U, iv2.size());
3713
3714 // IVs should be random, so ciphertexts should differ.
3715 EXPECT_NE(ciphertext1, ciphertext2);
3716
3717 auto params_iv1 =
3718 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3719 auto params_iv2 =
3720 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3721
3722 string plaintext = DecryptMessage(ciphertext1, params_iv1);
3723 EXPECT_EQ(message, plaintext);
3724 plaintext = DecryptMessage(ciphertext2, params_iv2);
3725 EXPECT_EQ(message, plaintext);
3726
3727 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3728 plaintext = DecryptMessage(ciphertext1, params_iv2);
3729 EXPECT_NE(message, plaintext);
3730 plaintext = DecryptMessage(ciphertext2, params_iv1);
3731 EXPECT_NE(message, plaintext);
3732}
3733
3734/*
3735 * EncryptionOperationsTest.AesIncremental
3736 *
3737 * Verifies that AES works, all modes, when provided data in various size increments.
3738 */
3739TEST_P(EncryptionOperationsTest, AesIncremental) {
3740 auto block_modes = {
3741 BlockMode::ECB,
3742 BlockMode::CBC,
3743 BlockMode::CTR,
3744 BlockMode::GCM,
3745 };
3746
3747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3748 .Authorization(TAG_NO_AUTH_REQUIRED)
3749 .AesEncryptionKey(128)
3750 .BlockMode(block_modes)
3751 .Padding(PaddingMode::NONE)
3752 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3753
3754 for (int increment = 1; increment <= 240; ++increment) {
3755 for (auto block_mode : block_modes) {
3756 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07003757 auto params =
3758 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
3759 if (block_mode == BlockMode::GCM) {
3760 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3761 }
Selene Huang31ab4042020-04-29 04:22:39 -07003762
3763 AuthorizationSet output_params;
3764 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3765
3766 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07003767 string to_send;
3768 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003769 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003770 }
Shawn Willden92d79c02021-02-19 07:31:55 -07003771 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
3772 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07003773
3774 switch (block_mode) {
3775 case BlockMode::GCM:
3776 EXPECT_EQ(message.size() + 16, ciphertext.size());
3777 break;
3778 case BlockMode::CTR:
3779 EXPECT_EQ(message.size(), ciphertext.size());
3780 break;
3781 case BlockMode::CBC:
3782 case BlockMode::ECB:
3783 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3784 break;
3785 }
3786
3787 auto iv = output_params.GetTagValue(TAG_NONCE);
3788 switch (block_mode) {
3789 case BlockMode::CBC:
3790 case BlockMode::GCM:
3791 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003792 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
3793 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
3794 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003795 break;
3796
3797 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003798 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07003799 break;
3800 }
3801
3802 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3803 << "Decrypt begin() failed for block mode " << block_mode;
3804
3805 string plaintext;
3806 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003807 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003808 }
3809 ErrorCode error = Finish(to_send, &plaintext);
3810 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
3811 << " and increment " << increment;
3812 if (error == ErrorCode::OK) {
3813 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3814 << block_mode << " and increment " << increment;
3815 }
3816 }
3817 }
3818}
3819
3820struct AesCtrSp80038aTestVector {
3821 const char* key;
3822 const char* nonce;
3823 const char* plaintext;
3824 const char* ciphertext;
3825};
3826
3827// These test vectors are taken from
3828// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3829static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3830 // AES-128
3831 {
3832 "2b7e151628aed2a6abf7158809cf4f3c",
3833 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3834 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3835 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3836 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3837 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3838 },
3839 // AES-192
3840 {
3841 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
3842 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3843 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3844 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3845 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3846 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3847 },
3848 // AES-256
3849 {
3850 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3851 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3852 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3853 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3854 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3855 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3856 },
3857};
3858
3859/*
3860 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3861 *
3862 * Verifies AES CTR implementation against SP800-38A test vectors.
3863 */
3864TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3865 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3866 for (size_t i = 0; i < 3; i++) {
3867 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3868 const string key = hex2str(test.key);
3869 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3870 InvalidSizes.end())
3871 continue;
3872 const string nonce = hex2str(test.nonce);
3873 const string plaintext = hex2str(test.plaintext);
3874 const string ciphertext = hex2str(test.ciphertext);
3875 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3876 }
3877}
3878
3879/*
3880 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3881 *
3882 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
3883 */
3884TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3885 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3886 .Authorization(TAG_NO_AUTH_REQUIRED)
3887 .AesEncryptionKey(128)
3888 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3889 .Padding(PaddingMode::PKCS7)));
3890 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3891 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3892}
3893
3894/*
3895 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3896 *
3897 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3898 */
3899TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3901 .Authorization(TAG_NO_AUTH_REQUIRED)
3902 .AesEncryptionKey(128)
3903 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3904 .Authorization(TAG_CALLER_NONCE)
3905 .Padding(PaddingMode::NONE)));
3906
3907 auto params = AuthorizationSetBuilder()
3908 .BlockMode(BlockMode::CTR)
3909 .Padding(PaddingMode::NONE)
3910 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
3911 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3912
3913 params = AuthorizationSetBuilder()
3914 .BlockMode(BlockMode::CTR)
3915 .Padding(PaddingMode::NONE)
3916 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
3917 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3918
3919 params = AuthorizationSetBuilder()
3920 .BlockMode(BlockMode::CTR)
3921 .Padding(PaddingMode::NONE)
3922 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
3923 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3924}
3925
3926/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003927 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003928 *
3929 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3930 */
3931TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3932 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3933 .Authorization(TAG_NO_AUTH_REQUIRED)
3934 .AesEncryptionKey(128)
3935 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3936 .Padding(PaddingMode::NONE)));
3937 // Two-block message.
3938 string message = "12345678901234567890123456789012";
3939 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3940 AuthorizationSet out_params;
3941 string ciphertext1 = EncryptMessage(message, params, &out_params);
3942 vector<uint8_t> iv1 = CopyIv(out_params);
3943 EXPECT_EQ(message.size(), ciphertext1.size());
3944
3945 out_params.Clear();
3946
3947 string ciphertext2 = EncryptMessage(message, params, &out_params);
3948 vector<uint8_t> iv2 = CopyIv(out_params);
3949 EXPECT_EQ(message.size(), ciphertext2.size());
3950
3951 // IVs should be random, so ciphertexts should differ.
3952 EXPECT_NE(ciphertext1, ciphertext2);
3953
3954 params.push_back(TAG_NONCE, iv1);
3955 string plaintext = DecryptMessage(ciphertext1, params);
3956 EXPECT_EQ(message, plaintext);
3957}
3958
3959/*
3960 * EncryptionOperationsTest.AesCallerNonce
3961 *
3962 * Verifies that AES caller-provided nonces work correctly.
3963 */
3964TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3965 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3966 .Authorization(TAG_NO_AUTH_REQUIRED)
3967 .AesEncryptionKey(128)
3968 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3969 .Authorization(TAG_CALLER_NONCE)
3970 .Padding(PaddingMode::NONE)));
3971
3972 string message = "12345678901234567890123456789012";
3973
3974 // Don't specify nonce, should get a random one.
3975 AuthorizationSetBuilder params =
3976 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3977 AuthorizationSet out_params;
3978 string ciphertext = EncryptMessage(message, params, &out_params);
3979 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003980 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003981
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003982 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003983 string plaintext = DecryptMessage(ciphertext, params);
3984 EXPECT_EQ(message, plaintext);
3985
3986 // Now specify a nonce, should also work.
3987 params = AuthorizationSetBuilder()
3988 .BlockMode(BlockMode::CBC)
3989 .Padding(PaddingMode::NONE)
3990 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3991 out_params.Clear();
3992 ciphertext = EncryptMessage(message, params, &out_params);
3993
3994 // Decrypt with correct nonce.
3995 plaintext = DecryptMessage(ciphertext, params);
3996 EXPECT_EQ(message, plaintext);
3997
3998 // Try with wrong nonce.
3999 params = AuthorizationSetBuilder()
4000 .BlockMode(BlockMode::CBC)
4001 .Padding(PaddingMode::NONE)
4002 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4003 plaintext = DecryptMessage(ciphertext, params);
4004 EXPECT_NE(message, plaintext);
4005}
4006
4007/*
4008 * EncryptionOperationsTest.AesCallerNonceProhibited
4009 *
4010 * Verifies that caller-provided nonces are not permitted when not specified in the key
4011 * authorizations.
4012 */
4013TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4015 .Authorization(TAG_NO_AUTH_REQUIRED)
4016 .AesEncryptionKey(128)
4017 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4018 .Padding(PaddingMode::NONE)));
4019
4020 string message = "12345678901234567890123456789012";
4021
4022 // Don't specify nonce, should get a random one.
4023 AuthorizationSetBuilder params =
4024 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4025 AuthorizationSet out_params;
4026 string ciphertext = EncryptMessage(message, params, &out_params);
4027 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004028 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004029
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004030 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004031 string plaintext = DecryptMessage(ciphertext, params);
4032 EXPECT_EQ(message, plaintext);
4033
4034 // Now specify a nonce, should fail
4035 params = AuthorizationSetBuilder()
4036 .BlockMode(BlockMode::CBC)
4037 .Padding(PaddingMode::NONE)
4038 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4039 out_params.Clear();
4040 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4041}
4042
4043/*
4044 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4045 *
4046 * Verifies that AES GCM mode works.
4047 */
4048TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4049 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4050 .Authorization(TAG_NO_AUTH_REQUIRED)
4051 .AesEncryptionKey(128)
4052 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4053 .Padding(PaddingMode::NONE)
4054 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4055
4056 string aad = "foobar";
4057 string message = "123456789012345678901234567890123456";
4058
4059 auto begin_params = AuthorizationSetBuilder()
4060 .BlockMode(BlockMode::GCM)
4061 .Padding(PaddingMode::NONE)
4062 .Authorization(TAG_MAC_LENGTH, 128);
4063
Selene Huang31ab4042020-04-29 04:22:39 -07004064 // Encrypt
4065 AuthorizationSet begin_out_params;
4066 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4067 << "Begin encrypt";
4068 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004069 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4070 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004071 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4072
4073 // Grab nonce
4074 begin_params.push_back(begin_out_params);
4075
4076 // Decrypt.
4077 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004078 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004079 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004080 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004081 EXPECT_EQ(message.length(), plaintext.length());
4082 EXPECT_EQ(message, plaintext);
4083}
4084
4085/*
4086 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4087 *
4088 * Verifies that AES GCM mode works, even when there's a long delay
4089 * between operations.
4090 */
4091TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4093 .Authorization(TAG_NO_AUTH_REQUIRED)
4094 .AesEncryptionKey(128)
4095 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4096 .Padding(PaddingMode::NONE)
4097 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4098
4099 string aad = "foobar";
4100 string message = "123456789012345678901234567890123456";
4101
4102 auto begin_params = AuthorizationSetBuilder()
4103 .BlockMode(BlockMode::GCM)
4104 .Padding(PaddingMode::NONE)
4105 .Authorization(TAG_MAC_LENGTH, 128);
4106
Selene Huang31ab4042020-04-29 04:22:39 -07004107 // Encrypt
4108 AuthorizationSet begin_out_params;
4109 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4110 << "Begin encrypt";
4111 string ciphertext;
4112 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004113 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004114 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004115 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004116
4117 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4118
4119 // Grab nonce
4120 begin_params.push_back(begin_out_params);
4121
4122 // Decrypt.
4123 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4124 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004125 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004126 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004127 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004128 sleep(5);
4129 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4130 EXPECT_EQ(message.length(), plaintext.length());
4131 EXPECT_EQ(message, plaintext);
4132}
4133
4134/*
4135 * EncryptionOperationsTest.AesGcmDifferentNonces
4136 *
4137 * Verifies that encrypting the same data with different nonces produces different outputs.
4138 */
4139TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4141 .Authorization(TAG_NO_AUTH_REQUIRED)
4142 .AesEncryptionKey(128)
4143 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4144 .Padding(PaddingMode::NONE)
4145 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4146 .Authorization(TAG_CALLER_NONCE)));
4147
4148 string aad = "foobar";
4149 string message = "123456789012345678901234567890123456";
4150 string nonce1 = "000000000000";
4151 string nonce2 = "111111111111";
4152 string nonce3 = "222222222222";
4153
4154 string ciphertext1 =
4155 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4156 string ciphertext2 =
4157 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4158 string ciphertext3 =
4159 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4160
4161 ASSERT_NE(ciphertext1, ciphertext2);
4162 ASSERT_NE(ciphertext1, ciphertext3);
4163 ASSERT_NE(ciphertext2, ciphertext3);
4164}
4165
4166/*
4167 * EncryptionOperationsTest.AesGcmTooShortTag
4168 *
4169 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4170 */
4171TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4172 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4173 .Authorization(TAG_NO_AUTH_REQUIRED)
4174 .AesEncryptionKey(128)
4175 .BlockMode(BlockMode::GCM)
4176 .Padding(PaddingMode::NONE)
4177 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4178 string message = "123456789012345678901234567890123456";
4179 auto params = AuthorizationSetBuilder()
4180 .BlockMode(BlockMode::GCM)
4181 .Padding(PaddingMode::NONE)
4182 .Authorization(TAG_MAC_LENGTH, 96);
4183
4184 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4185}
4186
4187/*
4188 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4189 *
4190 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4191 */
4192TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4193 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4194 .Authorization(TAG_NO_AUTH_REQUIRED)
4195 .AesEncryptionKey(128)
4196 .BlockMode(BlockMode::GCM)
4197 .Padding(PaddingMode::NONE)
4198 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4199 string aad = "foobar";
4200 string message = "123456789012345678901234567890123456";
4201 auto params = AuthorizationSetBuilder()
4202 .BlockMode(BlockMode::GCM)
4203 .Padding(PaddingMode::NONE)
4204 .Authorization(TAG_MAC_LENGTH, 128);
4205
Selene Huang31ab4042020-04-29 04:22:39 -07004206 // Encrypt
4207 AuthorizationSet begin_out_params;
4208 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4209 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004210 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004211
4212 AuthorizationSet finish_out_params;
4213 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004214 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4215 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004216
4217 params = AuthorizationSetBuilder()
4218 .Authorizations(begin_out_params)
4219 .BlockMode(BlockMode::GCM)
4220 .Padding(PaddingMode::NONE)
4221 .Authorization(TAG_MAC_LENGTH, 96);
4222
4223 // Decrypt.
4224 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4225}
4226
4227/*
4228 * EncryptionOperationsTest.AesGcmCorruptKey
4229 *
4230 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4231 */
4232TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4233 const uint8_t nonce_bytes[] = {
4234 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4235 };
4236 string nonce = make_string(nonce_bytes);
4237 const uint8_t ciphertext_bytes[] = {
4238 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4239 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4240 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4241 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4242 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4243 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4244 };
4245 string ciphertext = make_string(ciphertext_bytes);
4246
4247 auto params = AuthorizationSetBuilder()
4248 .BlockMode(BlockMode::GCM)
4249 .Padding(PaddingMode::NONE)
4250 .Authorization(TAG_MAC_LENGTH, 128)
4251 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4252
4253 auto import_params = AuthorizationSetBuilder()
4254 .Authorization(TAG_NO_AUTH_REQUIRED)
4255 .AesEncryptionKey(128)
4256 .BlockMode(BlockMode::GCM)
4257 .Padding(PaddingMode::NONE)
4258 .Authorization(TAG_CALLER_NONCE)
4259 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4260
4261 // Import correct key and decrypt
4262 const uint8_t key_bytes[] = {
4263 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4264 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4265 };
4266 string key = make_string(key_bytes);
4267 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4268 string plaintext = DecryptMessage(ciphertext, params);
4269 CheckedDeleteKey();
4270
4271 // Corrupt key and attempt to decrypt
4272 key[0] = 0;
4273 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4274 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4275 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
4276 CheckedDeleteKey();
4277}
4278
4279/*
4280 * EncryptionOperationsTest.AesGcmAadNoData
4281 *
4282 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
4283 * encrypt.
4284 */
4285TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
4286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4287 .Authorization(TAG_NO_AUTH_REQUIRED)
4288 .AesEncryptionKey(128)
4289 .BlockMode(BlockMode::GCM)
4290 .Padding(PaddingMode::NONE)
4291 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4292
4293 string aad = "1234567890123456";
4294 auto params = AuthorizationSetBuilder()
4295 .BlockMode(BlockMode::GCM)
4296 .Padding(PaddingMode::NONE)
4297 .Authorization(TAG_MAC_LENGTH, 128);
4298
Selene Huang31ab4042020-04-29 04:22:39 -07004299 // Encrypt
4300 AuthorizationSet begin_out_params;
4301 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4302 string ciphertext;
4303 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004304 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4305 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004306 EXPECT_TRUE(finish_out_params.empty());
4307
4308 // Grab nonce
4309 params.push_back(begin_out_params);
4310
4311 // Decrypt.
4312 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004313 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004314 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004315 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004316
4317 EXPECT_TRUE(finish_out_params.empty());
4318
4319 EXPECT_EQ("", plaintext);
4320}
4321
4322/*
4323 * EncryptionOperationsTest.AesGcmMultiPartAad
4324 *
4325 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
4326 * chunks.
4327 */
4328TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
4329 const size_t tag_bits = 128;
4330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4331 .Authorization(TAG_NO_AUTH_REQUIRED)
4332 .AesEncryptionKey(128)
4333 .BlockMode(BlockMode::GCM)
4334 .Padding(PaddingMode::NONE)
4335 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4336
4337 string message = "123456789012345678901234567890123456";
4338 auto begin_params = AuthorizationSetBuilder()
4339 .BlockMode(BlockMode::GCM)
4340 .Padding(PaddingMode::NONE)
4341 .Authorization(TAG_MAC_LENGTH, tag_bits);
4342 AuthorizationSet begin_out_params;
4343
Selene Huang31ab4042020-04-29 04:22:39 -07004344 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4345
4346 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07004347 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
4348 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004349 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004350 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4351 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004352
Selene Huang31ab4042020-04-29 04:22:39 -07004353 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07004354 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004355
4356 // Grab nonce.
4357 begin_params.push_back(begin_out_params);
4358
4359 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004360 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004361 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004362 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004363 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004364 EXPECT_EQ(message, plaintext);
4365}
4366
4367/*
4368 * EncryptionOperationsTest.AesGcmAadOutOfOrder
4369 *
4370 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
4371 */
4372TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
4373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4374 .Authorization(TAG_NO_AUTH_REQUIRED)
4375 .AesEncryptionKey(128)
4376 .BlockMode(BlockMode::GCM)
4377 .Padding(PaddingMode::NONE)
4378 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4379
4380 string message = "123456789012345678901234567890123456";
4381 auto begin_params = AuthorizationSetBuilder()
4382 .BlockMode(BlockMode::GCM)
4383 .Padding(PaddingMode::NONE)
4384 .Authorization(TAG_MAC_LENGTH, 128);
4385 AuthorizationSet begin_out_params;
4386
Selene Huang31ab4042020-04-29 04:22:39 -07004387 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4388
Shawn Willden92d79c02021-02-19 07:31:55 -07004389 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004390 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004391 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4392 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004393
Shawn Willden92d79c02021-02-19 07:31:55 -07004394 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07004395}
4396
4397/*
4398 * EncryptionOperationsTest.AesGcmBadAad
4399 *
4400 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
4401 */
4402TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
4403 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4404 .Authorization(TAG_NO_AUTH_REQUIRED)
4405 .AesEncryptionKey(128)
4406 .BlockMode(BlockMode::GCM)
4407 .Padding(PaddingMode::NONE)
4408 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4409
4410 string message = "12345678901234567890123456789012";
4411 auto begin_params = AuthorizationSetBuilder()
4412 .BlockMode(BlockMode::GCM)
4413 .Padding(PaddingMode::NONE)
4414 .Authorization(TAG_MAC_LENGTH, 128);
4415
Selene Huang31ab4042020-04-29 04:22:39 -07004416 // Encrypt
4417 AuthorizationSet begin_out_params;
4418 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004419 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004420 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004421 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004422
4423 // Grab nonce
4424 begin_params.push_back(begin_out_params);
4425
Selene Huang31ab4042020-04-29 04:22:39 -07004426 // Decrypt.
4427 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004428 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004429 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004430 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004431}
4432
4433/*
4434 * EncryptionOperationsTest.AesGcmWrongNonce
4435 *
4436 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
4437 */
4438TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
4439 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4440 .Authorization(TAG_NO_AUTH_REQUIRED)
4441 .AesEncryptionKey(128)
4442 .BlockMode(BlockMode::GCM)
4443 .Padding(PaddingMode::NONE)
4444 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4445
4446 string message = "12345678901234567890123456789012";
4447 auto begin_params = AuthorizationSetBuilder()
4448 .BlockMode(BlockMode::GCM)
4449 .Padding(PaddingMode::NONE)
4450 .Authorization(TAG_MAC_LENGTH, 128);
4451
Selene Huang31ab4042020-04-29 04:22:39 -07004452 // Encrypt
4453 AuthorizationSet begin_out_params;
4454 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004455 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004456 string ciphertext;
4457 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004458 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004459
4460 // Wrong nonce
4461 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
4462
4463 // Decrypt.
4464 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004465 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004466 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004467 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004468
4469 // With wrong nonce, should have gotten garbage plaintext (or none).
4470 EXPECT_NE(message, plaintext);
4471}
4472
4473/*
4474 * EncryptionOperationsTest.AesGcmCorruptTag
4475 *
4476 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
4477 */
4478TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
4479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4480 .Authorization(TAG_NO_AUTH_REQUIRED)
4481 .AesEncryptionKey(128)
4482 .BlockMode(BlockMode::GCM)
4483 .Padding(PaddingMode::NONE)
4484 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4485
4486 string aad = "1234567890123456";
4487 string message = "123456789012345678901234567890123456";
4488
4489 auto params = AuthorizationSetBuilder()
4490 .BlockMode(BlockMode::GCM)
4491 .Padding(PaddingMode::NONE)
4492 .Authorization(TAG_MAC_LENGTH, 128);
4493
Selene Huang31ab4042020-04-29 04:22:39 -07004494 // Encrypt
4495 AuthorizationSet begin_out_params;
4496 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004497 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004498 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004499 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004500
4501 // Corrupt tag
4502 ++(*ciphertext.rbegin());
4503
4504 // Grab nonce
4505 params.push_back(begin_out_params);
4506
4507 // Decrypt.
4508 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004509 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004510 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004511 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004512}
4513
4514/*
4515 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
4516 *
4517 * Verifies that 3DES is basically functional.
4518 */
4519TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
4520 auto auths = AuthorizationSetBuilder()
4521 .TripleDesEncryptionKey(168)
4522 .BlockMode(BlockMode::ECB)
4523 .Authorization(TAG_NO_AUTH_REQUIRED)
4524 .Padding(PaddingMode::NONE);
4525
4526 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
4527 // Two-block message.
4528 string message = "1234567890123456";
4529 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4530 string ciphertext1 = EncryptMessage(message, inParams);
4531 EXPECT_EQ(message.size(), ciphertext1.size());
4532
4533 string ciphertext2 = EncryptMessage(string(message), inParams);
4534 EXPECT_EQ(message.size(), ciphertext2.size());
4535
4536 // ECB is deterministic.
4537 EXPECT_EQ(ciphertext1, ciphertext2);
4538
4539 string plaintext = DecryptMessage(ciphertext1, inParams);
4540 EXPECT_EQ(message, plaintext);
4541}
4542
4543/*
4544 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
4545 *
4546 * Verifies that CBC keys reject ECB usage.
4547 */
4548TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
4549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4550 .TripleDesEncryptionKey(168)
4551 .BlockMode(BlockMode::CBC)
4552 .Authorization(TAG_NO_AUTH_REQUIRED)
4553 .Padding(PaddingMode::NONE)));
4554
4555 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4556 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4557}
4558
4559/*
4560 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
4561 *
4562 * Tests ECB mode with PKCS#7 padding, various message sizes.
4563 */
4564TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
4565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4566 .TripleDesEncryptionKey(168)
4567 .BlockMode(BlockMode::ECB)
4568 .Authorization(TAG_NO_AUTH_REQUIRED)
4569 .Padding(PaddingMode::PKCS7)));
4570
4571 for (size_t i = 0; i < 32; ++i) {
4572 string message(i, 'a');
4573 auto inParams =
4574 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4575 string ciphertext = EncryptMessage(message, inParams);
4576 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4577 string plaintext = DecryptMessage(ciphertext, inParams);
4578 EXPECT_EQ(message, plaintext);
4579 }
4580}
4581
4582/*
4583 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
4584 *
4585 * Verifies that keys configured for no padding reject PKCS7 padding
4586 */
4587TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
4588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4589 .TripleDesEncryptionKey(168)
4590 .BlockMode(BlockMode::ECB)
4591 .Authorization(TAG_NO_AUTH_REQUIRED)
4592 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00004593 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4594 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07004595}
4596
4597/*
4598 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
4599 *
4600 * Verifies that corrupted padding is detected.
4601 */
4602TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
4603 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4604 .TripleDesEncryptionKey(168)
4605 .BlockMode(BlockMode::ECB)
4606 .Authorization(TAG_NO_AUTH_REQUIRED)
4607 .Padding(PaddingMode::PKCS7)));
4608
4609 string message = "a";
4610 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
4611 EXPECT_EQ(8U, ciphertext.size());
4612 EXPECT_NE(ciphertext, message);
4613 ++ciphertext[ciphertext.size() / 2];
4614
4615 AuthorizationSetBuilder begin_params;
4616 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
4617 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
4618 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4619 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004620 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004621 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4622}
4623
4624struct TripleDesTestVector {
4625 const char* name;
4626 const KeyPurpose purpose;
4627 const BlockMode block_mode;
4628 const PaddingMode padding_mode;
4629 const char* key;
4630 const char* iv;
4631 const char* input;
4632 const char* output;
4633};
4634
4635// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
4636// of the NIST vectors are multiples of the block size.
4637static const TripleDesTestVector kTripleDesTestVectors[] = {
4638 {
4639 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4640 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
4641 "", // IV
4642 "329d86bdf1bc5af4", // input
4643 "d946c2756d78633f", // output
4644 },
4645 {
4646 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4647 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
4648 "", // IV
4649 "6b1540781b01ce1997adae102dbf3c5b", // input
4650 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
4651 },
4652 {
4653 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4654 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
4655 "", // IV
4656 "6daad94ce08acfe7", // input
4657 "660e7d32dcc90e79", // output
4658 },
4659 {
4660 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4661 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
4662 "", // IV
4663 "e9653a0a1f05d31b9acd12d73aa9879d", // input
4664 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
4665 },
4666 {
4667 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4668 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
4669 "43f791134c5647ba", // IV
4670 "dcc153cef81d6f24", // input
4671 "92538bd8af18d3ba", // output
4672 },
4673 {
4674 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4675 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4676 "c2e999cb6249023c", // IV
4677 "c689aee38a301bb316da75db36f110b5", // input
4678 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
4679 },
4680 {
4681 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
4682 PaddingMode::PKCS7,
4683 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4684 "c2e999cb6249023c", // IV
4685 "c689aee38a301bb316da75db36f110b500", // input
4686 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
4687 },
4688 {
4689 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
4690 PaddingMode::PKCS7,
4691 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4692 "c2e999cb6249023c", // IV
4693 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
4694 "c689aee38a301bb316da75db36f110b500", // output
4695 },
4696 {
4697 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4698 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
4699 "41746c7e442d3681", // IV
4700 "c53a7b0ec40600fe", // input
4701 "d4f00eb455de1034", // output
4702 },
4703 {
4704 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4705 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
4706 "3982bc02c3727d45", // IV
4707 "6006f10adef52991fcc777a1238bbb65", // input
4708 "edae09288e9e3bc05746d872b48e3b29", // output
4709 },
4710};
4711
4712/*
4713 * EncryptionOperationsTest.TripleDesTestVector
4714 *
4715 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
4716 */
4717TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
4718 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
4719 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
4720 SCOPED_TRACE(test->name);
4721 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
4722 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
4723 hex2str(test->output));
4724 }
4725}
4726
4727/*
4728 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
4729 *
4730 * Validates CBC mode functionality.
4731 */
4732TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
4733 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4734 .TripleDesEncryptionKey(168)
4735 .BlockMode(BlockMode::CBC)
4736 .Authorization(TAG_NO_AUTH_REQUIRED)
4737 .Padding(PaddingMode::NONE)));
4738
4739 ASSERT_GT(key_blob_.size(), 0U);
4740
4741 // Two-block message.
4742 string message = "1234567890123456";
4743 vector<uint8_t> iv1;
4744 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
4745 EXPECT_EQ(message.size(), ciphertext1.size());
4746
4747 vector<uint8_t> iv2;
4748 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
4749 EXPECT_EQ(message.size(), ciphertext2.size());
4750
4751 // IVs should be random, so ciphertexts should differ.
4752 EXPECT_NE(iv1, iv2);
4753 EXPECT_NE(ciphertext1, ciphertext2);
4754
4755 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
4756 EXPECT_EQ(message, plaintext);
4757}
4758
4759/*
4760 * EncryptionOperationsTest.TripleDesCallerIv
4761 *
4762 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
4763 */
4764TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
4765 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4766 .TripleDesEncryptionKey(168)
4767 .BlockMode(BlockMode::CBC)
4768 .Authorization(TAG_NO_AUTH_REQUIRED)
4769 .Authorization(TAG_CALLER_NONCE)
4770 .Padding(PaddingMode::NONE)));
4771 string message = "1234567890123456";
4772 vector<uint8_t> iv;
4773 // Don't specify IV, should get a random one.
4774 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4775 EXPECT_EQ(message.size(), ciphertext1.size());
4776 EXPECT_EQ(8U, iv.size());
4777
4778 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4779 EXPECT_EQ(message, plaintext);
4780
4781 // Now specify an IV, should also work.
4782 iv = AidlBuf("abcdefgh");
4783 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
4784
4785 // Decrypt with correct IV.
4786 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
4787 EXPECT_EQ(message, plaintext);
4788
4789 // Now try with wrong IV.
4790 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
4791 EXPECT_NE(message, plaintext);
4792}
4793
4794/*
4795 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
4796 *
4797 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
4798 */
4799TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
4800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4801 .TripleDesEncryptionKey(168)
4802 .BlockMode(BlockMode::CBC)
4803 .Authorization(TAG_NO_AUTH_REQUIRED)
4804 .Padding(PaddingMode::NONE)));
4805
4806 string message = "12345678901234567890123456789012";
4807 vector<uint8_t> iv;
4808 // Don't specify nonce, should get a random one.
4809 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4810 EXPECT_EQ(message.size(), ciphertext1.size());
4811 EXPECT_EQ(8U, iv.size());
4812
4813 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4814 EXPECT_EQ(message, plaintext);
4815
4816 // Now specify a nonce, should fail.
4817 auto input_params = AuthorizationSetBuilder()
4818 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
4819 .BlockMode(BlockMode::CBC)
4820 .Padding(PaddingMode::NONE);
4821 AuthorizationSet output_params;
4822 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
4823 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4824}
4825
4826/*
4827 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
4828 *
4829 * Verifies that 3DES ECB-only keys do not allow CBC usage.
4830 */
4831TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
4832 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4833 .TripleDesEncryptionKey(168)
4834 .BlockMode(BlockMode::ECB)
4835 .Authorization(TAG_NO_AUTH_REQUIRED)
4836 .Padding(PaddingMode::NONE)));
4837 // Two-block message.
4838 string message = "1234567890123456";
4839 auto begin_params =
4840 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4841 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4842}
4843
4844/*
4845 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4846 *
4847 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4848 */
4849TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4851 .TripleDesEncryptionKey(168)
4852 .BlockMode(BlockMode::CBC)
4853 .Authorization(TAG_NO_AUTH_REQUIRED)
4854 .Padding(PaddingMode::NONE)));
4855 // Message is slightly shorter than two blocks.
4856 string message = "123456789012345";
4857
4858 auto begin_params =
4859 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4860 AuthorizationSet output_params;
4861 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4862 string ciphertext;
4863 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4864}
4865
4866/*
4867 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4868 *
4869 * Verifies that PKCS7 padding works correctly in CBC mode.
4870 */
4871TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4873 .TripleDesEncryptionKey(168)
4874 .BlockMode(BlockMode::CBC)
4875 .Authorization(TAG_NO_AUTH_REQUIRED)
4876 .Padding(PaddingMode::PKCS7)));
4877
4878 // Try various message lengths; all should work.
4879 for (size_t i = 0; i < 32; ++i) {
4880 string message(i, 'a');
4881 vector<uint8_t> iv;
4882 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4883 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4884 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4885 EXPECT_EQ(message, plaintext);
4886 }
4887}
4888
4889/*
4890 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4891 *
4892 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4893 */
4894TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4895 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4896 .TripleDesEncryptionKey(168)
4897 .BlockMode(BlockMode::CBC)
4898 .Authorization(TAG_NO_AUTH_REQUIRED)
4899 .Padding(PaddingMode::NONE)));
4900
4901 // Try various message lengths; all should fail.
4902 for (size_t i = 0; i < 32; ++i) {
4903 auto begin_params =
4904 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4905 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4906 }
4907}
4908
4909/*
4910 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4911 *
4912 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4913 */
4914TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4916 .TripleDesEncryptionKey(168)
4917 .BlockMode(BlockMode::CBC)
4918 .Authorization(TAG_NO_AUTH_REQUIRED)
4919 .Padding(PaddingMode::PKCS7)));
4920
4921 string message = "a";
4922 vector<uint8_t> iv;
4923 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4924 EXPECT_EQ(8U, ciphertext.size());
4925 EXPECT_NE(ciphertext, message);
4926 ++ciphertext[ciphertext.size() / 2];
4927
4928 auto begin_params = AuthorizationSetBuilder()
4929 .BlockMode(BlockMode::CBC)
4930 .Padding(PaddingMode::PKCS7)
4931 .Authorization(TAG_NONCE, iv);
4932 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4933 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004934 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004935 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4936}
4937
4938/*
4939 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4940 *
4941 * Verifies that 3DES CBC works with many different input sizes.
4942 */
4943TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4944 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4945 .TripleDesEncryptionKey(168)
4946 .BlockMode(BlockMode::CBC)
4947 .Authorization(TAG_NO_AUTH_REQUIRED)
4948 .Padding(PaddingMode::NONE)));
4949
4950 int increment = 7;
4951 string message(240, 'a');
4952 AuthorizationSet input_params =
4953 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4954 AuthorizationSet output_params;
4955 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4956
4957 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004958 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004959 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004960 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4961 EXPECT_EQ(message.size(), ciphertext.size());
4962
4963 // Move TAG_NONCE into input_params
4964 input_params = output_params;
4965 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4966 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4967 output_params.Clear();
4968
4969 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4970 string plaintext;
4971 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004972 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004973 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4974 EXPECT_EQ(ciphertext.size(), plaintext.size());
4975 EXPECT_EQ(message, plaintext);
4976}
4977
4978INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4979
4980typedef KeyMintAidlTestBase MaxOperationsTest;
4981
4982/*
4983 * MaxOperationsTest.TestLimitAes
4984 *
4985 * Verifies that the max uses per boot tag works correctly with AES keys.
4986 */
4987TEST_P(MaxOperationsTest, TestLimitAes) {
4988 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4989
4990 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4991 .Authorization(TAG_NO_AUTH_REQUIRED)
4992 .AesEncryptionKey(128)
4993 .EcbMode()
4994 .Padding(PaddingMode::NONE)
4995 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4996
4997 string message = "1234567890123456";
4998
4999 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5000
5001 EncryptMessage(message, params);
5002 EncryptMessage(message, params);
5003 EncryptMessage(message, params);
5004
5005 // Fourth time should fail.
5006 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5007}
5008
5009/*
Qi Wud22ec842020-11-26 13:27:53 +08005010 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005011 *
5012 * Verifies that the max uses per boot tag works correctly with RSA keys.
5013 */
5014TEST_P(MaxOperationsTest, TestLimitRsa) {
5015 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5016
5017 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5018 .Authorization(TAG_NO_AUTH_REQUIRED)
5019 .RsaSigningKey(1024, 65537)
5020 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005021 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5022 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005023
5024 string message = "1234567890123456";
5025
5026 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5027
5028 SignMessage(message, params);
5029 SignMessage(message, params);
5030 SignMessage(message, params);
5031
5032 // Fourth time should fail.
5033 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5034}
5035
5036INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5037
Qi Wud22ec842020-11-26 13:27:53 +08005038typedef KeyMintAidlTestBase UsageCountLimitTest;
5039
5040/*
Qi Wubeefae42021-01-28 23:16:37 +08005041 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005042 *
Qi Wubeefae42021-01-28 23:16:37 +08005043 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005044 */
Qi Wubeefae42021-01-28 23:16:37 +08005045TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005046 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5047
5048 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5049 .Authorization(TAG_NO_AUTH_REQUIRED)
5050 .AesEncryptionKey(128)
5051 .EcbMode()
5052 .Padding(PaddingMode::NONE)
5053 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5054
5055 // Check the usage count limit tag appears in the authorizations.
5056 AuthorizationSet auths;
5057 for (auto& entry : key_characteristics_) {
5058 auths.push_back(AuthorizationSet(entry.authorizations));
5059 }
5060 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5061 << "key usage count limit " << 1U << " missing";
5062
5063 string message = "1234567890123456";
5064 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5065
Qi Wubeefae42021-01-28 23:16:37 +08005066 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5067 AuthorizationSet keystore_auths =
5068 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5069
Qi Wud22ec842020-11-26 13:27:53 +08005070 // First usage of AES key should work.
5071 EncryptMessage(message, params);
5072
Qi Wud22ec842020-11-26 13:27:53 +08005073 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5074 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5075 // must be invalidated from secure storage (such as RPMB partition).
5076 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5077 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005078 // Usage count limit tag is enforced by keystore, keymint does nothing.
5079 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005080 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5081 }
5082}
5083
5084/*
Qi Wubeefae42021-01-28 23:16:37 +08005085 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005086 *
Qi Wubeefae42021-01-28 23:16:37 +08005087 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005088 */
Qi Wubeefae42021-01-28 23:16:37 +08005089TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5090 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5091
5092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5093 .Authorization(TAG_NO_AUTH_REQUIRED)
5094 .AesEncryptionKey(128)
5095 .EcbMode()
5096 .Padding(PaddingMode::NONE)
5097 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5098
5099 // Check the usage count limit tag appears in the authorizations.
5100 AuthorizationSet auths;
5101 for (auto& entry : key_characteristics_) {
5102 auths.push_back(AuthorizationSet(entry.authorizations));
5103 }
5104 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5105 << "key usage count limit " << 3U << " missing";
5106
5107 string message = "1234567890123456";
5108 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5109
5110 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5111 AuthorizationSet keystore_auths =
5112 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5113
5114 EncryptMessage(message, params);
5115 EncryptMessage(message, params);
5116 EncryptMessage(message, params);
5117
5118 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5119 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5120 // must be invalidated from secure storage (such as RPMB partition).
5121 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5122 } else {
5123 // Usage count limit tag is enforced by keystore, keymint does nothing.
5124 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5125 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5126 }
5127}
5128
5129/*
5130 * UsageCountLimitTest.TestSingleUseRsa
5131 *
5132 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5133 */
5134TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005135 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5136
5137 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5138 .Authorization(TAG_NO_AUTH_REQUIRED)
5139 .RsaSigningKey(1024, 65537)
5140 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005141 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5142 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005143
5144 // Check the usage count limit tag appears in the authorizations.
5145 AuthorizationSet auths;
5146 for (auto& entry : key_characteristics_) {
5147 auths.push_back(AuthorizationSet(entry.authorizations));
5148 }
5149 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5150 << "key usage count limit " << 1U << " missing";
5151
5152 string message = "1234567890123456";
5153 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5154
Qi Wubeefae42021-01-28 23:16:37 +08005155 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5156 AuthorizationSet keystore_auths =
5157 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5158
Qi Wud22ec842020-11-26 13:27:53 +08005159 // First usage of RSA key should work.
5160 SignMessage(message, params);
5161
Qi Wud22ec842020-11-26 13:27:53 +08005162 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5163 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5164 // must be invalidated from secure storage (such as RPMB partition).
5165 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5166 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005167 // Usage count limit tag is enforced by keystore, keymint does nothing.
5168 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5169 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5170 }
5171}
5172
5173/*
5174 * UsageCountLimitTest.TestLimitUseRsa
5175 *
5176 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5177 */
5178TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5179 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5180
5181 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5182 .Authorization(TAG_NO_AUTH_REQUIRED)
5183 .RsaSigningKey(1024, 65537)
5184 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005185 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5186 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005187
5188 // Check the usage count limit tag appears in the authorizations.
5189 AuthorizationSet auths;
5190 for (auto& entry : key_characteristics_) {
5191 auths.push_back(AuthorizationSet(entry.authorizations));
5192 }
5193 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5194 << "key usage count limit " << 3U << " missing";
5195
5196 string message = "1234567890123456";
5197 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5198
5199 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5200 AuthorizationSet keystore_auths =
5201 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5202
5203 SignMessage(message, params);
5204 SignMessage(message, params);
5205 SignMessage(message, params);
5206
5207 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5208 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5209 // must be invalidated from secure storage (such as RPMB partition).
5210 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5211 } else {
5212 // Usage count limit tag is enforced by keystore, keymint does nothing.
5213 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005214 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5215 }
5216}
5217
Qi Wu8e727f72021-02-11 02:49:33 +08005218/*
5219 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5220 *
5221 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5222 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5223 * in hardware.
5224 */
5225TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5226 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5227
5228 auto error = GenerateKey(AuthorizationSetBuilder()
5229 .RsaSigningKey(2048, 65537)
5230 .Digest(Digest::NONE)
5231 .Padding(PaddingMode::NONE)
5232 .Authorization(TAG_NO_AUTH_REQUIRED)
5233 .Authorization(TAG_ROLLBACK_RESISTANCE)
5234 .SetDefaultValidity());
5235 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5236
5237 if (error == ErrorCode::OK) {
5238 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5239 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5240 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5241 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5242
5243 // The KeyMint should also enforce single use key in hardware when it supports rollback
5244 // resistance.
5245 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5246 .Authorization(TAG_NO_AUTH_REQUIRED)
5247 .RsaSigningKey(1024, 65537)
5248 .NoDigestOrPadding()
5249 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5250 .SetDefaultValidity()));
5251
5252 // Check the usage count limit tag appears in the hardware authorizations.
5253 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5254 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5255 << "key usage count limit " << 1U << " missing";
5256
5257 string message = "1234567890123456";
5258 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5259
5260 // First usage of RSA key should work.
5261 SignMessage(message, params);
5262
5263 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5264 // must be invalidated from secure storage (such as RPMB partition).
5265 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5266 }
5267}
5268
Qi Wud22ec842020-11-26 13:27:53 +08005269INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
5270
David Drysdale7de9feb2021-03-05 14:56:19 +00005271typedef KeyMintAidlTestBase GetHardwareInfoTest;
5272
5273TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
5274 // Retrieving hardware info should give the same result each time.
5275 KeyMintHardwareInfo info;
5276 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
5277 KeyMintHardwareInfo info2;
5278 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
5279 EXPECT_EQ(info, info2);
5280}
5281
5282INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
5283
Selene Huang31ab4042020-04-29 04:22:39 -07005284typedef KeyMintAidlTestBase AddEntropyTest;
5285
5286/*
5287 * AddEntropyTest.AddEntropy
5288 *
5289 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
5290 * is actually added.
5291 */
5292TEST_P(AddEntropyTest, AddEntropy) {
5293 string data = "foo";
5294 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
5295}
5296
5297/*
5298 * AddEntropyTest.AddEmptyEntropy
5299 *
5300 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
5301 */
5302TEST_P(AddEntropyTest, AddEmptyEntropy) {
5303 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
5304}
5305
5306/*
5307 * AddEntropyTest.AddLargeEntropy
5308 *
5309 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
5310 */
5311TEST_P(AddEntropyTest, AddLargeEntropy) {
5312 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
5313}
5314
5315INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
5316
Selene Huang31ab4042020-04-29 04:22:39 -07005317typedef KeyMintAidlTestBase KeyDeletionTest;
5318
5319/**
5320 * KeyDeletionTest.DeleteKey
5321 *
5322 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
5323 * valid key blob.
5324 */
5325TEST_P(KeyDeletionTest, DeleteKey) {
5326 auto error = GenerateKey(AuthorizationSetBuilder()
5327 .RsaSigningKey(2048, 65537)
5328 .Digest(Digest::NONE)
5329 .Padding(PaddingMode::NONE)
5330 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005331 .Authorization(TAG_ROLLBACK_RESISTANCE)
5332 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005333 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5334
5335 // Delete must work if rollback protection is implemented
5336 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005337 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005338 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5339
5340 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
5341
5342 string message = "12345678901234567890123456789012";
5343 AuthorizationSet begin_out_params;
5344 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5345 Begin(KeyPurpose::SIGN, key_blob_,
5346 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5347 &begin_out_params));
5348 AbortIfNeeded();
5349 key_blob_ = AidlBuf();
5350 }
5351}
5352
5353/**
5354 * KeyDeletionTest.DeleteInvalidKey
5355 *
5356 * This test checks that the HAL excepts invalid key blobs..
5357 */
5358TEST_P(KeyDeletionTest, DeleteInvalidKey) {
5359 // Generate key just to check if rollback protection is implemented
5360 auto error = GenerateKey(AuthorizationSetBuilder()
5361 .RsaSigningKey(2048, 65537)
5362 .Digest(Digest::NONE)
5363 .Padding(PaddingMode::NONE)
5364 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005365 .Authorization(TAG_ROLLBACK_RESISTANCE)
5366 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005367 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5368
5369 // Delete must work if rollback protection is implemented
5370 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005371 AuthorizationSet enforced(SecLevelAuthorizations());
5372 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005373
5374 // Delete the key we don't care about the result at this point.
5375 DeleteKey();
5376
5377 // Now create an invalid key blob and delete it.
5378 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
5379
5380 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5381 }
5382}
5383
5384/**
5385 * KeyDeletionTest.DeleteAllKeys
5386 *
5387 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
5388 *
5389 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
5390 * FBE/FDE encryption keys, which means that the device will not even boot until after the
5391 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
5392 * been provisioned. Use this test only on dedicated testing devices that have no valuable
5393 * credentials stored in Keystore/Keymint.
5394 */
5395TEST_P(KeyDeletionTest, DeleteAllKeys) {
5396 if (!arm_deleteAllKeys) return;
5397 auto error = GenerateKey(AuthorizationSetBuilder()
5398 .RsaSigningKey(2048, 65537)
5399 .Digest(Digest::NONE)
5400 .Padding(PaddingMode::NONE)
5401 .Authorization(TAG_NO_AUTH_REQUIRED)
5402 .Authorization(TAG_ROLLBACK_RESISTANCE));
5403 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5404
5405 // Delete must work if rollback protection is implemented
5406 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005407 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005408 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5409
5410 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
5411
5412 string message = "12345678901234567890123456789012";
5413 AuthorizationSet begin_out_params;
5414
5415 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5416 Begin(KeyPurpose::SIGN, key_blob_,
5417 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5418 &begin_out_params));
5419 AbortIfNeeded();
5420 key_blob_ = AidlBuf();
5421 }
5422}
5423
5424INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
5425
5426using UpgradeKeyTest = KeyMintAidlTestBase;
5427
5428/*
5429 * UpgradeKeyTest.UpgradeKey
5430 *
5431 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
5432 */
5433TEST_P(UpgradeKeyTest, UpgradeKey) {
5434 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5435 .AesEncryptionKey(128)
5436 .Padding(PaddingMode::NONE)
5437 .Authorization(TAG_NO_AUTH_REQUIRED)));
5438
5439 auto result = UpgradeKey(key_blob_);
5440
5441 // Key doesn't need upgrading. Should get okay, but no new key blob.
5442 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
5443}
5444
5445INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
5446
5447using ClearOperationsTest = KeyMintAidlTestBase;
5448
5449/*
5450 * ClearSlotsTest.TooManyOperations
5451 *
5452 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
5453 * operations are started without being finished or aborted. Also verifies
5454 * that aborting the operations clears the operations.
5455 *
5456 */
5457TEST_P(ClearOperationsTest, TooManyOperations) {
5458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5459 .Authorization(TAG_NO_AUTH_REQUIRED)
5460 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005461 .Padding(PaddingMode::NONE)
5462 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005463
5464 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5465 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08005466 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07005467 AuthorizationSet out_params;
5468 ErrorCode result;
5469 size_t i;
5470
5471 for (i = 0; i < max_operations; i++) {
5472 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
5473 if (ErrorCode::OK != result) {
5474 break;
5475 }
5476 }
5477 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
5478 // Try again just in case there's a weird overflow bug
5479 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
5480 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5481 for (size_t j = 0; j < i; j++) {
5482 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
5483 << "Aboort failed for i = " << j << std::endl;
5484 }
5485 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5486 AbortIfNeeded();
5487}
5488
5489INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
5490
5491typedef KeyMintAidlTestBase TransportLimitTest;
5492
5493/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005494 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07005495 *
5496 * Verifies that passing input data to finish succeeds as expected.
5497 */
5498TEST_P(TransportLimitTest, LargeFinishInput) {
5499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5500 .Authorization(TAG_NO_AUTH_REQUIRED)
5501 .AesEncryptionKey(128)
5502 .BlockMode(BlockMode::ECB)
5503 .Padding(PaddingMode::NONE)));
5504
5505 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
5506 auto cipher_params =
5507 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5508
5509 AuthorizationSet out_params;
5510 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
5511
5512 string plain_message = std::string(1 << msg_size, 'x');
5513 string encrypted_message;
5514 auto rc = Finish(plain_message, &encrypted_message);
5515
5516 EXPECT_EQ(ErrorCode::OK, rc);
5517 EXPECT_EQ(plain_message.size(), encrypted_message.size())
5518 << "Encrypt finish returned OK, but did not consume all of the given input";
5519 cipher_params.push_back(out_params);
5520
5521 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
5522
5523 string decrypted_message;
5524 rc = Finish(encrypted_message, &decrypted_message);
5525 EXPECT_EQ(ErrorCode::OK, rc);
5526 EXPECT_EQ(plain_message.size(), decrypted_message.size())
5527 << "Decrypt finish returned OK, did not consume all of the given input";
5528 }
5529}
5530
5531INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
5532
David Zeuthene0c40892021-01-08 12:54:11 -05005533typedef KeyMintAidlTestBase KeyAgreementTest;
5534
5535int CurveToOpenSslCurveName(EcCurve curve) {
5536 switch (curve) {
5537 case EcCurve::P_224:
5538 return NID_secp224r1;
5539 case EcCurve::P_256:
5540 return NID_X9_62_prime256v1;
5541 case EcCurve::P_384:
5542 return NID_secp384r1;
5543 case EcCurve::P_521:
5544 return NID_secp521r1;
5545 }
5546}
5547
5548/*
5549 * KeyAgreementTest.Ecdh
5550 *
5551 * Verifies that ECDH works for all curves
5552 */
5553TEST_P(KeyAgreementTest, Ecdh) {
5554 // Because it's possible to use this API with keys on different curves, we
5555 // check all N^2 combinations where N is the number of supported
5556 // curves.
5557 //
5558 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
5559 // lot more curves we can be smart about things and just pick |otherCurve| so
5560 // it's not |curve| and that way we end up with only 2*N runs
5561 //
5562 for (auto curve : ValidCurves()) {
5563 for (auto localCurve : ValidCurves()) {
5564 // Generate EC key locally (with access to private key material)
5565 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
5566 int curveName = CurveToOpenSslCurveName(localCurve);
5567 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
5568 ASSERT_NE(group, nullptr);
5569 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
5570 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
5571 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
5572 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
5573
5574 // Get encoded form of the public part of the locally generated key...
5575 unsigned char* p = nullptr;
5576 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
5577 ASSERT_GT(encodedPublicKeySize, 0);
5578 vector<uint8_t> encodedPublicKey(
5579 reinterpret_cast<const uint8_t*>(p),
5580 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
5581 OPENSSL_free(p);
5582
5583 // Generate EC key in KeyMint (only access to public key material)
5584 vector<uint8_t> challenge = {0x41, 0x42};
5585 EXPECT_EQ(
5586 ErrorCode::OK,
5587 GenerateKey(AuthorizationSetBuilder()
5588 .Authorization(TAG_NO_AUTH_REQUIRED)
5589 .Authorization(TAG_EC_CURVE, curve)
5590 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
5591 .Authorization(TAG_ALGORITHM, Algorithm::EC)
5592 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08005593 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
5594 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05005595 << "Failed to generate key";
5596 ASSERT_GT(cert_chain_.size(), 0);
5597 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
5598 ASSERT_NE(kmKeyCert, nullptr);
5599 // Check that keyAgreement (bit 4) is set in KeyUsage
5600 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
5601 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
5602 ASSERT_NE(kmPkey, nullptr);
5603 if (dump_Attestations) {
5604 for (size_t n = 0; n < cert_chain_.size(); n++) {
5605 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
5606 }
5607 }
5608
5609 // Now that we have the two keys, we ask KeyMint to perform ECDH...
5610 if (curve != localCurve) {
5611 // If the keys are using different curves KeyMint should fail with
5612 // ErrorCode:INVALID_ARGUMENT. Check that.
5613 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5614 string ZabFromKeyMintStr;
5615 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
5616 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5617 &ZabFromKeyMintStr));
5618
5619 } else {
5620 // Otherwise if the keys are using the same curve, it should work.
5621 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5622 string ZabFromKeyMintStr;
5623 EXPECT_EQ(ErrorCode::OK,
5624 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5625 &ZabFromKeyMintStr));
5626 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
5627
5628 // Perform local ECDH between the two keys so we can check if we get the same Zab..
5629 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
5630 ASSERT_NE(ctx, nullptr);
5631 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
5632 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
5633 size_t ZabFromTestLen = 0;
5634 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
5635 vector<uint8_t> ZabFromTest;
5636 ZabFromTest.resize(ZabFromTestLen);
5637 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
5638
5639 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
5640 }
5641
5642 CheckedDeleteKey();
5643 }
5644 }
5645}
5646
5647INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
5648
Shawn Willdend659c7c2021-02-19 14:51:51 -07005649using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005650
5651TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
5652 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5653 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5654
5655 CheckedDeleteKey(&aesKeyData.blob);
5656 CheckedDeleteKey(&hmacKeyData.blob);
5657 CheckedDeleteKey(&rsaKeyData.blob);
5658 CheckedDeleteKey(&ecdsaKeyData.blob);
5659}
5660
5661// This is a more comprenhensive test, but it can only be run on a machine which is still in early
5662// boot stage, which no proper Android device is by the time we can run VTS. To use this,
5663// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
5664// early boot, so you'll have to reboot between runs.
5665TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
5666 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5667 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5668 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
5669 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5670 EXPECT_TRUE(
5671 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5672 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5673 EXPECT_TRUE(
5674 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5675
5676 // Should be able to use keys, since early boot has not ended
5677 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5678 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5679 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5680 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5681
5682 // End early boot
5683 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
5684 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
5685
5686 // Should not be able to use already-created keys.
5687 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
5688 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
5689 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
5690 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
5691
5692 CheckedDeleteKey(&aesKeyData.blob);
5693 CheckedDeleteKey(&hmacKeyData.blob);
5694 CheckedDeleteKey(&rsaKeyData.blob);
5695 CheckedDeleteKey(&ecdsaKeyData.blob);
5696
5697 // Should not be able to create new keys
5698 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
5699 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
5700
5701 CheckedDeleteKey(&aesKeyData.blob);
5702 CheckedDeleteKey(&hmacKeyData.blob);
5703 CheckedDeleteKey(&rsaKeyData.blob);
5704 CheckedDeleteKey(&ecdsaKeyData.blob);
5705}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005706
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005707INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
5708
Shawn Willdend659c7c2021-02-19 14:51:51 -07005709using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005710
5711// This may be a problematic test. It can't be run repeatedly without unlocking the device in
5712// between runs... and on most test devices there are no enrolled credentials so it can't be
5713// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
5714// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
5715// a manual test process, which includes unlocking between runs, which is why it's included here.
5716// Well, that and the fact that it's the only test we can do without also making calls into the
5717// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
5718// implications might be, so that may or may not be a solution.
5719TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
5720 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5721 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
5722
5723 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5724 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5725 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5726 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5727
5728 ErrorCode rc = GetReturnErrorCode(
5729 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
5730 ASSERT_EQ(ErrorCode::OK, rc);
5731 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
5732 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
5733 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
5734 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
5735
5736 CheckedDeleteKey(&aesKeyData.blob);
5737 CheckedDeleteKey(&hmacKeyData.blob);
5738 CheckedDeleteKey(&rsaKeyData.blob);
5739 CheckedDeleteKey(&ecdsaKeyData.blob);
5740}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005741
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005742INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
5743
Janis Danisevskis24c04702020-12-16 18:28:39 -08005744} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07005745
5746int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07005747 std::cout << "Testing ";
5748 auto halInstances =
5749 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
5750 std::cout << "HAL instances:\n";
5751 for (auto& entry : halInstances) {
5752 std::cout << " " << entry << '\n';
5753 }
5754
Selene Huang31ab4042020-04-29 04:22:39 -07005755 ::testing::InitGoogleTest(&argc, argv);
5756 for (int i = 1; i < argc; ++i) {
5757 if (argv[i][0] == '-') {
5758 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07005759 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5760 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07005761 }
5762 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07005763 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5764 dump_Attestations = true;
5765 } else {
5766 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07005767 }
5768 }
5769 }
Shawn Willden08a7e432020-12-11 13:05:27 +00005770 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07005771}