blob: f9a99aaafa9d66823b7f748e555f5dce975ed3b8 [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
David Drysdalebb3d85e2021-04-13 11:15:51 +010070bool check_patchLevels = false;
71
Selene Huang31ab4042020-04-29 04:22:39 -070072template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000073bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
74 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070075 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080076 if (auto p = authorizationValue(ttag, param)) {
77 return *p == expected_value;
78 }
79 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070080 });
81 return (it != set.end());
82}
83
84template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000085bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070086 auto it = std::find_if(set.begin(), set.end(),
87 [&](const KeyParameter& param) { return param.tag == tag; });
88 return (it != set.end());
89}
90
91constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
92 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
93 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
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, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
107
108string hex2str(string a) {
109 string b;
110 size_t num = a.size() / 2;
111 b.resize(num);
112 for (size_t i = 0; i < num; i++) {
113 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
114 }
115 return b;
116}
117
118string rsa_key =
119 hex2str("30820275020100300d06092a864886f70d01010105000482025f3082025b"
120 "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
121 "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
122 "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
123 "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
124 "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
125 "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
126 "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
127 "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
128 "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
129 "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
130 "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
131 "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
132 "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
133 "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
134 "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
135 "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
136 "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
137 "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
138 "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
139 "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
140 "3492d6");
141
Selene Huange5727e62021-04-13 22:41:20 -0700142/*
143 * DER-encoded PKCS#8 format RSA key. Generated using:
144 *
145 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
146 */
147string rsa_2048_key =
148 hex2str("308204BD020100300D06092A864886F70D0101010500048204A7308204A3"
149 "0201000282010100BEBC342B56D443B1299F9A6A7056E80A897E318476A5"
150 "A18029E63B2ED739A61791D339F58DC763D9D14911F2EDEC383DEE11F631"
151 "9B44510E7A3ECD9B79B97382E49500ACF8117DC89CAF0E621F77756554A2"
152 "FD4664BFE7AB8B59AB48340DBFA27B93B5A81F6ECDEB02D0759307128DF3"
153 "E3BAD4055C8B840216DFAA5700670E6C5126F0962FCB70FF308F25049164"
154 "CCF76CC2DA66A7DD9A81A714C2809D69186133D29D84568E892B6FFBF319"
155 "9BDB14383EE224407F190358F111A949552ABA6714227D1BD7F6B20DD0CB"
156 "88F9467B719339F33BFF35B3870B3F62204E4286B0948EA348B524544B5F"
157 "9838F29EE643B079EEF8A713B220D7806924CDF7295070C5020301000102"
158 "82010069F377F35F2F584EF075353CCD1CA99738DB3DBC7C7FF35F9366CE"
159 "176DFD1B135AB10030344ABF5FBECF1D4659FDEF1C0FC430834BE1BE3911"
160 "951377BB3D563A2EA9CA8F4AD9C48A8CE6FD516A735C662686C7B4B3C09A"
161 "7B8354133E6F93F790D59EAEB92E84C9A4339302CCE28FDF04CCCAFA7DE3"
162 "F3A827D4F6F7D38E68B0EC6AB706645BF074A4E4090D06FB163124365FD5"
163 "EE7A20D350E9958CC30D91326E1B292E9EF5DB408EC42DAF737D20149704"
164 "D0A678A0FB5B5446863B099228A352D604BA8091A164D01D5AB05397C71E"
165 "AD20BE2A08FC528FE442817809C787FEE4AB97F97B9130D022153EDC6EB6"
166 "CBE7B0F8E3473F2E901209B5DB10F93604DB0102818100E83C0998214941"
167 "EA4F9293F1B77E2E99E6CF305FAF358238E126124FEAF2EB9724B2EA7B78"
168 "E6032343821A80E55D1D88FB12D220C3F41A56142FEC85796D1917F1E8C7"
169 "74F142B67D3D6E7B7E6B4383E94DB5929089DBB346D5BDAB40CC2D96EE04"
170 "09475E175C63BF78CFD744136740838127EA723FF3FE7FA368C1311B4A4E"
171 "0502818100D240FCC0F5D7715CDE21CB2DC86EA146132EA3B06F61FF2AF5"
172 "4BF38473F59DADCCE32B5F4CC32DD0BA6F509347B4B5B1B58C39F95E4798"
173 "CCBB43E83D0119ACF532F359CA743C85199F0286610E200997D731291717"
174 "9AC9B67558773212EC961E8BCE7A3CC809BC5486A96E4B0E6AF394D94E06"
175 "6A0900B7B70E82A44FB30053C102818100AD15DA1CBD6A492B66851BA8C3"
176 "16D38AB700E2CFDDD926A658003513C54BAA152B30021D667D20078F500F"
177 "8AD3E7F3945D74A891ED1A28EAD0FEEAEC8C14A8E834CF46A13D1378C99D"
178 "18940823CFDD27EC5810D59339E0C34198AC638E09C87CBB1B634A9864AE"
179 "9F4D5EB2D53514F67B4CAEC048C8AB849A02E397618F3271350281801FA2"
180 "C1A5331880A92D8F3E281C617108BF38244F16E352E69ED417C7153F9EC3"
181 "18F211839C643DCF8B4DD67CE2AC312E95178D5D952F06B1BF779F491692"
182 "4B70F582A23F11304E02A5E7565AE22A35E74FECC8B6FDC93F92A1A37703"
183 "E4CF0E63783BD02EB716A7ECBBFA606B10B74D01579522E7EF84D91FC522"
184 "292108D902C1028180796FE3825F9DCC85DF22D58690065D93898ACD65C0"
185 "87BEA8DA3A63BF4549B795E2CD0E3BE08CDEBD9FCF1720D9CDC5070D74F4"
186 "0DED8E1102C52152A31B6165F83A6722AECFCC35A493D7634664B888A08D"
187 "3EB034F12EA28BFEE346E205D334827F778B16ED40872BD29FCB36536B6E"
188 "93FFB06778696B4A9D81BB0A9423E63DE5");
189
Selene Huang31ab4042020-04-29 04:22:39 -0700190string ec_256_key =
191 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
192 "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
193 "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
194 "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
195 "1c6eb00083cf3376d11fd44949e0b2183bfe");
196
197string ec_521_key =
198 hex2str("3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
199 "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
200 "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
201 "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
202 "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
203 "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
204 "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
205 "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
206 "D9");
207
208string ec_256_key_rfc5915 =
209 hex2str("308193020100301306072a8648ce3d020106082a8648ce3d030107047930"
210 "770201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
211 "8e8d21c9fa750c1da00a06082a8648ce3d030107a14403420004e2cc561e"
212 "e701da0ad0ef0d176bb0c919d42e79c393fdc1bd6c4010d85cf2cf8e68c9"
213 "05464666f98dad4f01573ba81078b3428570a439ba3229fbc026c550682f");
214
215string ec_256_key_sec1 =
216 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
217 "6b0201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
218 "8e8d21c9fa750c1da14403420004e2cc561ee701da0ad0ef0d176bb0c919"
219 "d42e79c393fdc1bd6c4010d85cf2cf8e68c905464666f98dad4f01573ba8"
220 "1078b3428570a439ba3229fbc026c550682f");
221
222struct RSA_Delete {
223 void operator()(RSA* p) { RSA_free(p); }
224};
225
Selene Huang31ab4042020-04-29 04:22:39 -0700226std::string make_string(const uint8_t* data, size_t length) {
227 return std::string(reinterpret_cast<const char*>(data), length);
228}
229
230template <size_t N>
231std::string make_string(const uint8_t (&a)[N]) {
232 return make_string(a, N);
233}
234
235class AidlBuf : public vector<uint8_t> {
236 typedef vector<uint8_t> super;
237
238 public:
239 AidlBuf() {}
240 AidlBuf(const super& other) : super(other) {}
241 AidlBuf(super&& other) : super(std::move(other)) {}
242 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
243
244 AidlBuf& operator=(const super& other) {
245 super::operator=(other);
246 return *this;
247 }
248
249 AidlBuf& operator=(super&& other) {
250 super::operator=(std::move(other));
251 return *this;
252 }
253
254 AidlBuf& operator=(const string& other) {
255 resize(other.size());
256 for (size_t i = 0; i < other.size(); ++i) {
257 (*this)[i] = static_cast<uint8_t>(other[i]);
258 }
259 return *this;
260 }
261
262 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
263};
264
David Drysdale4dc01072021-04-01 12:17:35 +0100265string device_suffix(const string& name) {
266 size_t pos = name.find('/');
267 if (pos == string::npos) {
268 return name;
269 }
270 return name.substr(pos + 1);
271}
272
273bool matching_rp_instance(const string& km_name,
274 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
275 string km_suffix = device_suffix(km_name);
276
277 vector<string> rp_names =
278 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
279 for (const string& rp_name : rp_names) {
280 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
281 // KeyMint instance, assume they match.
282 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
283 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
284 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
285 return true;
286 }
287 }
288 return false;
289}
290
Selene Huang31ab4042020-04-29 04:22:39 -0700291} // namespace
292
293class NewKeyGenerationTest : public KeyMintAidlTestBase {
294 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700295 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000296 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700297 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
298 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
299
Selene Huang31ab4042020-04-29 04:22:39 -0700300 // Check that some unexpected tags/values are NOT present.
301 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
302 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000303 }
304
305 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
306 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
307 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
308 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
309
310 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
311 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
312 }
313
314 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
315 // TODO(swillden): Distinguish which params should be in which auth list.
316 AuthorizationSet auths;
317 for (auto& entry : keyCharacteristics) {
318 auths.push_back(AuthorizationSet(entry.authorizations));
319 }
320 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
321
322 // Verify that App data, ROT and auth timeout are NOT included.
323 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
324 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700325 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
326
David Drysdale7de9feb2021-03-05 14:56:19 +0000327 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700328 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000329 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700330 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700331 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000332 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700333 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000334
David Drysdalebb3d85e2021-04-13 11:15:51 +0100335 if (check_patchLevels) {
336 // Should include vendor and boot patchlevels.
337 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
338 EXPECT_TRUE(vendor_pl);
339 EXPECT_EQ(*vendor_pl, vendor_patch_level());
340 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
341 EXPECT_TRUE(boot_pl);
342 }
343
David Drysdale7de9feb2021-03-05 14:56:19 +0000344 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700345 }
346};
347
348/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000349 * NewKeyGenerationTest.Aes
350 *
351 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
352 * have correct characteristics.
353 */
354TEST_P(NewKeyGenerationTest, Aes) {
355 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
356 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
357 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
358 SCOPED_TRACE(testing::Message()
359 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
360 vector<uint8_t> key_blob;
361 vector<KeyCharacteristics> key_characteristics;
362 auto builder = AuthorizationSetBuilder()
363 .AesEncryptionKey(key_size)
364 .BlockMode(block_mode)
365 .Padding(padding_mode)
366 .SetDefaultValidity();
367 if (block_mode == BlockMode::GCM) {
368 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
369 }
370 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
371
372 EXPECT_GT(key_blob.size(), 0U);
373 CheckSymmetricParams(key_characteristics);
374
375 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
376
377 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
378 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
379 << "Key size " << key_size << "missing";
380
381 CheckedDeleteKey(&key_blob);
382 }
383 }
384 }
385}
386
387/*
388 * NewKeyGenerationTest.AesInvalidSize
389 *
390 * Verifies that specifying an invalid key size for AES key generation returns
391 * UNSUPPORTED_KEY_SIZE.
392 */
393TEST_P(NewKeyGenerationTest, AesInvalidSize) {
394 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
395 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
396 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
397 SCOPED_TRACE(testing::Message()
398 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
399 vector<uint8_t> key_blob;
400 vector<KeyCharacteristics> key_characteristics;
401 auto builder = AuthorizationSetBuilder()
402 .AesEncryptionKey(key_size)
403 .BlockMode(block_mode)
404 .Padding(padding_mode)
405 .SetDefaultValidity();
406 if (block_mode == BlockMode::GCM) {
407 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
408 }
409 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
410 GenerateKey(builder, &key_blob, &key_characteristics));
411 }
412 }
413 }
414
415 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
416 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
417 vector<uint8_t> key_blob;
418 vector<KeyCharacteristics> key_characteristics;
419 // No key size specified
420 auto builder = AuthorizationSetBuilder()
421 .Authorization(TAG_ALGORITHM, Algorithm::AES)
422 .BlockMode(block_mode)
423 .Padding(padding_mode)
424 .SetDefaultValidity();
425 if (block_mode == BlockMode::GCM) {
426 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
427 }
428 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
429 GenerateKey(builder, &key_blob, &key_characteristics));
430 }
431 }
432}
433
434/*
435 * NewKeyGenerationTest.AesInvalidPadding
436 *
437 * Verifies that specifying an invalid padding on AES keys gives a failure
438 * somewhere along the way.
439 */
440TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
441 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
442 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
443 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
444 SCOPED_TRACE(testing::Message()
445 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
446 vector<uint8_t> key_blob;
447 vector<KeyCharacteristics> key_characteristics;
448 auto builder = AuthorizationSetBuilder()
449 .AesEncryptionKey(key_size)
450 .BlockMode(block_mode)
451 .Padding(padding_mode)
452 .SetDefaultValidity();
453 if (block_mode == BlockMode::GCM) {
454 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
455 }
456
457 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
458 if (result == ErrorCode::OK) {
459 // Key creation was OK but has generated a key that cannot be used.
460 auto params =
461 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
462 auto result = Begin(KeyPurpose::ENCRYPT, params);
463 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
464 result == ErrorCode::INVALID_KEY_BLOB);
465 } else {
466 // The KeyMint implementation detected that the generated key
467 // is unusable.
468 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
469 }
470 }
471 }
472 }
473}
474
475/*
476 * NewKeyGenerationTest.AesGcmMissingMinMac
477 *
478 * Verifies that specifying an invalid key size for AES key generation returns
479 * UNSUPPORTED_KEY_SIZE.
480 */
481TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
482 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
483 BlockMode block_mode = BlockMode::GCM;
484 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
485 SCOPED_TRACE(testing::Message()
486 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
487 vector<uint8_t> key_blob;
488 vector<KeyCharacteristics> key_characteristics;
489 // No MIN_MAC_LENGTH provided.
490 auto builder = AuthorizationSetBuilder()
491 .AesEncryptionKey(key_size)
492 .BlockMode(block_mode)
493 .Padding(padding_mode)
494 .SetDefaultValidity();
495 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
496 GenerateKey(builder, &key_blob, &key_characteristics));
497 }
498 }
499}
500
501/*
502 * NewKeyGenerationTest.TripleDes
503 *
504 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
505 * have correct characteristics.
506 */
507TEST_P(NewKeyGenerationTest, TripleDes) {
508 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
509 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
510 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
511 SCOPED_TRACE(testing::Message()
512 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
513 vector<uint8_t> key_blob;
514 vector<KeyCharacteristics> key_characteristics;
515 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
516 .TripleDesEncryptionKey(key_size)
517 .BlockMode(block_mode)
518 .Padding(padding_mode)
519 .Authorization(TAG_NO_AUTH_REQUIRED)
520 .SetDefaultValidity(),
521 &key_blob, &key_characteristics));
522
523 EXPECT_GT(key_blob.size(), 0U);
524 CheckSymmetricParams(key_characteristics);
525
526 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
527
528 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
529 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
530 << "Key size " << key_size << "missing";
531
532 CheckedDeleteKey(&key_blob);
533 }
534 }
535 }
536}
537
538/*
539 * NewKeyGenerationTest.TripleDesWithAttestation
540 *
541 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
542 * have correct characteristics.
543 *
544 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
545 * put in a certificate) but which isn't an error.
546 */
547TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
548 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
549 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
550 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
551 SCOPED_TRACE(testing::Message()
552 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
553
554 auto challenge = "hello";
555 auto app_id = "foo";
556
557 vector<uint8_t> key_blob;
558 vector<KeyCharacteristics> key_characteristics;
559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
560 .TripleDesEncryptionKey(key_size)
561 .BlockMode(block_mode)
562 .Padding(padding_mode)
563 .Authorization(TAG_NO_AUTH_REQUIRED)
564 .AttestationChallenge(challenge)
565 .AttestationApplicationId(app_id)
566 .SetDefaultValidity(),
567 &key_blob, &key_characteristics));
568
569 EXPECT_GT(key_blob.size(), 0U);
570 CheckSymmetricParams(key_characteristics);
571
572 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
573
574 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
575 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
576 << "Key size " << key_size << "missing";
577
578 CheckedDeleteKey(&key_blob);
579 }
580 }
581 }
582}
583
584/*
585 * NewKeyGenerationTest.TripleDesInvalidSize
586 *
587 * Verifies that specifying an invalid key size for 3-DES key generation returns
588 * UNSUPPORTED_KEY_SIZE.
589 */
590TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
591 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
592 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
593 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
594 SCOPED_TRACE(testing::Message()
595 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
596 vector<uint8_t> key_blob;
597 vector<KeyCharacteristics> key_characteristics;
598 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
599 GenerateKey(AuthorizationSetBuilder()
600 .TripleDesEncryptionKey(key_size)
601 .BlockMode(block_mode)
602 .Padding(padding_mode)
603 .Authorization(TAG_NO_AUTH_REQUIRED)
604 .SetDefaultValidity(),
605 &key_blob, &key_characteristics));
606 }
607 }
608 }
609
610 // Omitting the key size fails.
611 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
612 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
613 SCOPED_TRACE(testing::Message()
614 << "3DES-default-" << block_mode << "-" << padding_mode);
615 vector<uint8_t> key_blob;
616 vector<KeyCharacteristics> key_characteristics;
617 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
618 GenerateKey(AuthorizationSetBuilder()
619 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
620 .BlockMode(block_mode)
621 .Padding(padding_mode)
622 .Authorization(TAG_NO_AUTH_REQUIRED)
623 .SetDefaultValidity(),
624 &key_blob, &key_characteristics));
625 }
626 }
627}
628
629/*
Selene Huang31ab4042020-04-29 04:22:39 -0700630 * NewKeyGenerationTest.Rsa
631 *
632 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
633 * have correct characteristics.
634 */
635TEST_P(NewKeyGenerationTest, Rsa) {
636 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
637 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700638 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700639 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
640 .RsaSigningKey(key_size, 65537)
641 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800642 .Padding(PaddingMode::NONE)
643 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700644 &key_blob, &key_characteristics));
645
646 ASSERT_GT(key_blob.size(), 0U);
647 CheckBaseParams(key_characteristics);
648
Shawn Willden7f424372021-01-10 18:06:50 -0700649 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700650
651 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
652 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
653 << "Key size " << key_size << "missing";
654 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
655
656 CheckedDeleteKey(&key_blob);
657 }
658}
659
660/*
Qi Wud22ec842020-11-26 13:27:53 +0800661 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700662 *
663 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
664 * have correct characteristics.
665 */
666TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700667 auto challenge = "hello";
668 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700669
Selene Huang6e46f142021-04-20 19:20:11 -0700670 auto subject = "cert subj 2";
671 vector<uint8_t> subject_der(make_name_from_str(subject));
672
673 uint64_t serial_int = 66;
674 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
675
Selene Huang4f64c222021-04-13 19:54:36 -0700676 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700677 vector<uint8_t> key_blob;
678 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700679 ASSERT_EQ(ErrorCode::OK,
680 GenerateKey(AuthorizationSetBuilder()
681 .RsaSigningKey(key_size, 65537)
682 .Digest(Digest::NONE)
683 .Padding(PaddingMode::NONE)
684 .AttestationChallenge(challenge)
685 .AttestationApplicationId(app_id)
686 .Authorization(TAG_NO_AUTH_REQUIRED)
687 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
688 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
689 .SetDefaultValidity(),
690 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700691
692 ASSERT_GT(key_blob.size(), 0U);
693 CheckBaseParams(key_characteristics);
694
695 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
696
697 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
698 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
699 << "Key size " << key_size << "missing";
700 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
701
Selene Huang6e46f142021-04-20 19:20:11 -0700702 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700703 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700704 ASSERT_GT(cert_chain_.size(), 0);
705
706 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
707 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
708 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
709 sw_enforced, hw_enforced, SecLevel(),
710 cert_chain_[0].encodedCertificate));
711
712 CheckedDeleteKey(&key_blob);
713 }
714}
715
716/*
David Drysdale4dc01072021-04-01 12:17:35 +0100717 * NewKeyGenerationTest.RsaWithRpkAttestation
718 *
719 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
720 * that has been generated using an associate IRemotelyProvisionedComponent.
721 */
722TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
723 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
724 // instance.
725 std::shared_ptr<IRemotelyProvisionedComponent> rp;
726 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
727 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
728
729 // Generate a P-256 keypair to use as an attestation key.
730 MacedPublicKey macedPubKey;
731 std::vector<uint8_t> privateKeyBlob;
732 auto status =
733 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
734 ASSERT_TRUE(status.isOk());
735 vector<uint8_t> coseKeyData;
736 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
737
738 AttestationKey attestation_key;
739 attestation_key.keyBlob = std::move(privateKeyBlob);
740 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
741
742 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
743 auto challenge = "hello";
744 auto app_id = "foo";
745
746 vector<uint8_t> key_blob;
747 vector<KeyCharacteristics> key_characteristics;
748 ASSERT_EQ(ErrorCode::OK,
749 GenerateKey(AuthorizationSetBuilder()
750 .RsaSigningKey(key_size, 65537)
751 .Digest(Digest::NONE)
752 .Padding(PaddingMode::NONE)
753 .AttestationChallenge(challenge)
754 .AttestationApplicationId(app_id)
755 .Authorization(TAG_NO_AUTH_REQUIRED)
756 .SetDefaultValidity(),
757 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
758
759 ASSERT_GT(key_blob.size(), 0U);
760 CheckBaseParams(key_characteristics);
761
762 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
763
764 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
765 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
766 << "Key size " << key_size << "missing";
767 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
768
769 // Attestation by itself is not valid (last entry is not self-signed).
770 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
771
772 // The signature over the attested key should correspond to the P256 public key.
773 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
774 ASSERT_TRUE(key_cert.get());
775 EVP_PKEY_Ptr signing_pubkey;
776 p256_pub_key(coseKeyData, &signing_pubkey);
777 ASSERT_TRUE(signing_pubkey.get());
778
779 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
780 << "Verification of attested certificate failed "
781 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
782
783 CheckedDeleteKey(&key_blob);
784 }
785}
786
787/*
Selene Huang4f64c222021-04-13 19:54:36 -0700788 * NewKeyGenerationTest.RsaEncryptionWithAttestation
789 *
790 * Verifies that keymint attestation for RSA encryption keys with challenge and
791 * app id is also successful.
792 */
793TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
794 auto key_size = 2048;
795 auto challenge = "hello";
796 auto app_id = "foo";
797
Selene Huang6e46f142021-04-20 19:20:11 -0700798 auto subject = "subj 2";
799 vector<uint8_t> subject_der(make_name_from_str(subject));
800
801 uint64_t serial_int = 111166;
802 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
803
Selene Huang4f64c222021-04-13 19:54:36 -0700804 vector<uint8_t> key_blob;
805 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700806 ASSERT_EQ(ErrorCode::OK,
807 GenerateKey(AuthorizationSetBuilder()
808 .RsaEncryptionKey(key_size, 65537)
809 .Padding(PaddingMode::NONE)
810 .AttestationChallenge(challenge)
811 .AttestationApplicationId(app_id)
812 .Authorization(TAG_NO_AUTH_REQUIRED)
813 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
814 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
815 .SetDefaultValidity(),
816 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700817
818 ASSERT_GT(key_blob.size(), 0U);
819 AuthorizationSet auths;
820 for (auto& entry : key_characteristics) {
821 auths.push_back(AuthorizationSet(entry.authorizations));
822 }
823
824 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
825 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
826
827 // Verify that App data and ROT are NOT included.
828 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
829 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
830
831 // Check that some unexpected tags/values are NOT present.
832 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
833 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
834
835 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
836
837 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
838 ASSERT_TRUE(os_ver);
839 EXPECT_EQ(*os_ver, os_version());
840
841 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
842
843 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
844 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
845 << "Key size " << key_size << "missing";
846 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
847
Selene Huang6e46f142021-04-20 19:20:11 -0700848 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700849 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
850 ASSERT_GT(cert_chain_.size(), 0);
851
852 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
853 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
854 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
855 sw_enforced, hw_enforced, SecLevel(),
856 cert_chain_[0].encodedCertificate));
857
858 CheckedDeleteKey(&key_blob);
859}
860
861/*
862 * NewKeyGenerationTest.RsaWithSelfSign
863 *
864 * Verifies that attesting to RSA key generation is successful, and returns
865 * self signed certificate if no challenge is provided. And signing etc
866 * works as expected.
867 */
868TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -0700869 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
870 vector<uint8_t> subject_der(make_name_from_str(subject));
871
872 uint64_t serial_int = 0;
873 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
874
Selene Huang4f64c222021-04-13 19:54:36 -0700875 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
876 vector<uint8_t> key_blob;
877 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700878 ASSERT_EQ(ErrorCode::OK,
879 GenerateKey(AuthorizationSetBuilder()
880 .RsaSigningKey(key_size, 65537)
881 .Digest(Digest::NONE)
882 .Padding(PaddingMode::NONE)
883 .Authorization(TAG_NO_AUTH_REQUIRED)
884 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
885 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
886 .SetDefaultValidity(),
887 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700888
889 ASSERT_GT(key_blob.size(), 0U);
890 CheckBaseParams(key_characteristics);
891
892 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
893
894 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
895 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
896 << "Key size " << key_size << "missing";
897 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
898
Selene Huang6e46f142021-04-20 19:20:11 -0700899 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700900 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
901 ASSERT_EQ(cert_chain_.size(), 1);
902
903 CheckedDeleteKey(&key_blob);
904 }
905}
906
907/*
908 * NewKeyGenerationTest.RsaWithAttestationMissAppId
909 *
910 * Verifies that attesting to RSA checks for missing app ID.
911 */
912TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
913 auto challenge = "hello";
914 vector<uint8_t> key_blob;
915 vector<KeyCharacteristics> key_characteristics;
916
917 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
918 GenerateKey(AuthorizationSetBuilder()
919 .RsaSigningKey(2048, 65537)
920 .Digest(Digest::NONE)
921 .Padding(PaddingMode::NONE)
922 .AttestationChallenge(challenge)
923 .Authorization(TAG_NO_AUTH_REQUIRED)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926}
927
928/*
929 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
930 *
931 * Verifies that attesting to RSA ignores app id if challenge is missing.
932 */
933TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
934 auto key_size = 2048;
935 auto app_id = "foo";
936
Selene Huang6e46f142021-04-20 19:20:11 -0700937 auto subject = "cert subj 2";
938 vector<uint8_t> subject_der(make_name_from_str(subject));
939
940 uint64_t serial_int = 1;
941 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
942
Selene Huang4f64c222021-04-13 19:54:36 -0700943 vector<uint8_t> key_blob;
944 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700945 ASSERT_EQ(ErrorCode::OK,
946 GenerateKey(AuthorizationSetBuilder()
947 .RsaSigningKey(key_size, 65537)
948 .Digest(Digest::NONE)
949 .Padding(PaddingMode::NONE)
950 .AttestationApplicationId(app_id)
951 .Authorization(TAG_NO_AUTH_REQUIRED)
952 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
953 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
954 .SetDefaultValidity(),
955 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700956
957 ASSERT_GT(key_blob.size(), 0U);
958 CheckBaseParams(key_characteristics);
959
960 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
961
962 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
963 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
964 << "Key size " << key_size << "missing";
965 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
966
Selene Huang6e46f142021-04-20 19:20:11 -0700967 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700968 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
969 ASSERT_EQ(cert_chain_.size(), 1);
970
971 CheckedDeleteKey(&key_blob);
972}
973
974/*
Qi Wud22ec842020-11-26 13:27:53 +0800975 * NewKeyGenerationTest.LimitedUsageRsa
976 *
977 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
978 * resulting keys have correct characteristics.
979 */
980TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
981 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
982 vector<uint8_t> key_blob;
983 vector<KeyCharacteristics> key_characteristics;
984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
985 .RsaSigningKey(key_size, 65537)
986 .Digest(Digest::NONE)
987 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800988 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
989 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800990 &key_blob, &key_characteristics));
991
992 ASSERT_GT(key_blob.size(), 0U);
993 CheckBaseParams(key_characteristics);
994
995 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
996
997 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
998 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
999 << "Key size " << key_size << "missing";
1000 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1001
1002 // Check the usage count limit tag appears in the authorizations.
1003 AuthorizationSet auths;
1004 for (auto& entry : key_characteristics) {
1005 auths.push_back(AuthorizationSet(entry.authorizations));
1006 }
1007 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1008 << "key usage count limit " << 1U << " missing";
1009
1010 CheckedDeleteKey(&key_blob);
1011 }
1012}
1013
1014/*
Qi Wubeefae42021-01-28 23:16:37 +08001015 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1016 *
1017 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1018 * resulting keys have correct characteristics and attestation.
1019 */
1020TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001021 auto challenge = "hello";
1022 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001023
Selene Huang6e46f142021-04-20 19:20:11 -07001024 auto subject = "cert subj 2";
1025 vector<uint8_t> subject_der(make_name_from_str(subject));
1026
1027 uint64_t serial_int = 66;
1028 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1029
Selene Huang4f64c222021-04-13 19:54:36 -07001030 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001031 vector<uint8_t> key_blob;
1032 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001033 ASSERT_EQ(ErrorCode::OK,
1034 GenerateKey(AuthorizationSetBuilder()
1035 .RsaSigningKey(key_size, 65537)
1036 .Digest(Digest::NONE)
1037 .Padding(PaddingMode::NONE)
1038 .AttestationChallenge(challenge)
1039 .AttestationApplicationId(app_id)
1040 .Authorization(TAG_NO_AUTH_REQUIRED)
1041 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1042 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1043 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1044 .SetDefaultValidity(),
1045 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001046
1047 ASSERT_GT(key_blob.size(), 0U);
1048 CheckBaseParams(key_characteristics);
1049
1050 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1051
1052 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1053 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1054 << "Key size " << key_size << "missing";
1055 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1056
1057 // Check the usage count limit tag appears in the authorizations.
1058 AuthorizationSet auths;
1059 for (auto& entry : key_characteristics) {
1060 auths.push_back(AuthorizationSet(entry.authorizations));
1061 }
1062 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1063 << "key usage count limit " << 1U << " missing";
1064
1065 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001066 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001067 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001068 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001069
1070 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1071 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1072 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1073 sw_enforced, hw_enforced, SecLevel(),
1074 cert_chain_[0].encodedCertificate));
1075
1076 CheckedDeleteKey(&key_blob);
1077 }
1078}
1079
1080/*
Selene Huang31ab4042020-04-29 04:22:39 -07001081 * NewKeyGenerationTest.NoInvalidRsaSizes
1082 *
1083 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1084 */
1085TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1086 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1087 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001088 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001089 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1090 GenerateKey(AuthorizationSetBuilder()
1091 .RsaSigningKey(key_size, 65537)
1092 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001093 .Padding(PaddingMode::NONE)
1094 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001095 &key_blob, &key_characteristics));
1096 }
1097}
1098
1099/*
1100 * NewKeyGenerationTest.RsaNoDefaultSize
1101 *
1102 * Verifies that failing to specify a key size for RSA key generation returns
1103 * UNSUPPORTED_KEY_SIZE.
1104 */
1105TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1106 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1107 GenerateKey(AuthorizationSetBuilder()
1108 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1109 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001110 .SigningKey()
1111 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001112}
1113
1114/*
1115 * NewKeyGenerationTest.Ecdsa
1116 *
1117 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1118 * have correct characteristics.
1119 */
1120TEST_P(NewKeyGenerationTest, Ecdsa) {
1121 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1122 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001123 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001124 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1125 .EcdsaSigningKey(key_size)
1126 .Digest(Digest::NONE)
1127 .SetDefaultValidity(),
1128 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001129 ASSERT_GT(key_blob.size(), 0U);
1130 CheckBaseParams(key_characteristics);
1131
Shawn Willden7f424372021-01-10 18:06:50 -07001132 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001133
1134 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1135 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1136 << "Key size " << key_size << "missing";
1137
1138 CheckedDeleteKey(&key_blob);
1139 }
1140}
1141
1142/*
Selene Huang4f64c222021-04-13 19:54:36 -07001143 * NewKeyGenerationTest.EcdsaAttestation
1144 *
1145 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1146 * an attestation will be generated.
1147 */
1148TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1149 auto challenge = "hello";
1150 auto app_id = "foo";
1151
Selene Huang6e46f142021-04-20 19:20:11 -07001152 auto subject = "cert subj 2";
1153 vector<uint8_t> subject_der(make_name_from_str(subject));
1154
1155 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1156 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1157
Selene Huang4f64c222021-04-13 19:54:36 -07001158 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1159 vector<uint8_t> key_blob;
1160 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001161 ASSERT_EQ(ErrorCode::OK,
1162 GenerateKey(AuthorizationSetBuilder()
1163 .Authorization(TAG_NO_AUTH_REQUIRED)
1164 .EcdsaSigningKey(key_size)
1165 .Digest(Digest::NONE)
1166 .AttestationChallenge(challenge)
1167 .AttestationApplicationId(app_id)
1168 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1169 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1170 .SetDefaultValidity(),
1171 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001172 ASSERT_GT(key_blob.size(), 0U);
1173 CheckBaseParams(key_characteristics);
1174
1175 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1176
1177 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1178 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1179 << "Key size " << key_size << "missing";
1180
1181 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1182 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001183 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001184
1185 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1186 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1187 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1188 sw_enforced, hw_enforced, SecLevel(),
1189 cert_chain_[0].encodedCertificate));
1190
1191 CheckedDeleteKey(&key_blob);
1192 }
1193}
1194
1195/*
1196 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1197 *
1198 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1199 * the key will generate a self signed attestation.
1200 */
1201TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001202 auto subject = "cert subj 2";
1203 vector<uint8_t> subject_der(make_name_from_str(subject));
1204
1205 uint64_t serial_int = 0x123456FFF1234;
1206 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1207
Selene Huang4f64c222021-04-13 19:54:36 -07001208 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1209 vector<uint8_t> key_blob;
1210 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001211 ASSERT_EQ(ErrorCode::OK,
1212 GenerateKey(AuthorizationSetBuilder()
1213 .EcdsaSigningKey(key_size)
1214 .Digest(Digest::NONE)
1215 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1216 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1217 .SetDefaultValidity(),
1218 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001219 ASSERT_GT(key_blob.size(), 0U);
1220 CheckBaseParams(key_characteristics);
1221
1222 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1223
1224 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1225 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1226 << "Key size " << key_size << "missing";
1227
1228 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001229 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001230 ASSERT_EQ(cert_chain_.size(), 1);
1231
1232 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1233 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1234
1235 CheckedDeleteKey(&key_blob);
1236 }
1237}
1238
1239/*
1240 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1241 *
1242 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1243 * app id must also be provided or else it will fail.
1244 */
1245TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1246 auto challenge = "hello";
1247 vector<uint8_t> key_blob;
1248 vector<KeyCharacteristics> key_characteristics;
1249
1250 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1251 GenerateKey(AuthorizationSetBuilder()
1252 .EcdsaSigningKey(EcCurve::P_256)
1253 .Digest(Digest::NONE)
1254 .AttestationChallenge(challenge)
1255 .SetDefaultValidity(),
1256 &key_blob, &key_characteristics));
1257}
1258
1259/*
1260 * NewKeyGenerationTest.EcdsaIgnoreAppId
1261 *
1262 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1263 * any appid will be ignored, and keymint will generate a self sign certificate.
1264 */
1265TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1266 auto app_id = "foo";
1267
1268 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1269 vector<uint8_t> key_blob;
1270 vector<KeyCharacteristics> key_characteristics;
1271 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1272 .EcdsaSigningKey(key_size)
1273 .Digest(Digest::NONE)
1274 .AttestationApplicationId(app_id)
1275 .SetDefaultValidity(),
1276 &key_blob, &key_characteristics));
1277
1278 ASSERT_GT(key_blob.size(), 0U);
1279 CheckBaseParams(key_characteristics);
1280
1281 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1282
1283 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1284 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1285 << "Key size " << key_size << "missing";
1286
1287 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1288 ASSERT_EQ(cert_chain_.size(), 1);
1289
1290 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1291 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1292
1293 CheckedDeleteKey(&key_blob);
1294 }
1295}
1296
1297/*
1298 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1299 *
1300 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1301 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1302 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1303 * to specify how many following bytes will be used to encode the length.
1304 */
1305TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1306 auto challenge = "hello";
1307 auto key_size = 256;
1308 std::vector<uint32_t> app_id_lengths{143, 258};
1309
1310 for (uint32_t length : app_id_lengths) {
1311 const string app_id(length, 'a');
1312 vector<uint8_t> key_blob;
1313 vector<KeyCharacteristics> key_characteristics;
1314 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1315 .Authorization(TAG_NO_AUTH_REQUIRED)
1316 .EcdsaSigningKey(key_size)
1317 .Digest(Digest::NONE)
1318 .AttestationChallenge(challenge)
1319 .AttestationApplicationId(app_id)
1320 .SetDefaultValidity(),
1321 &key_blob, &key_characteristics));
1322 ASSERT_GT(key_blob.size(), 0U);
1323 CheckBaseParams(key_characteristics);
1324
1325 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1326
1327 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1328 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1329 << "Key size " << key_size << "missing";
1330
1331 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1332 ASSERT_GT(cert_chain_.size(), 0);
1333
1334 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1335 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1336 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1337 sw_enforced, hw_enforced, SecLevel(),
1338 cert_chain_[0].encodedCertificate));
1339
1340 CheckedDeleteKey(&key_blob);
1341 }
1342}
1343
1344/*
Qi Wud22ec842020-11-26 13:27:53 +08001345 * NewKeyGenerationTest.LimitedUsageEcdsa
1346 *
1347 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1348 * resulting keys have correct characteristics.
1349 */
1350TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1351 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1352 vector<uint8_t> key_blob;
1353 vector<KeyCharacteristics> key_characteristics;
1354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1355 .EcdsaSigningKey(key_size)
1356 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001357 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1358 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001359 &key_blob, &key_characteristics));
1360
1361 ASSERT_GT(key_blob.size(), 0U);
1362 CheckBaseParams(key_characteristics);
1363
1364 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1365
1366 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1367 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1368 << "Key size " << key_size << "missing";
1369
1370 // Check the usage count limit tag appears in the authorizations.
1371 AuthorizationSet auths;
1372 for (auto& entry : key_characteristics) {
1373 auths.push_back(AuthorizationSet(entry.authorizations));
1374 }
1375 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1376 << "key usage count limit " << 1U << " missing";
1377
1378 CheckedDeleteKey(&key_blob);
1379 }
1380}
1381
1382/*
Selene Huang31ab4042020-04-29 04:22:39 -07001383 * NewKeyGenerationTest.EcdsaDefaultSize
1384 *
1385 * Verifies that failing to specify a key size for EC key generation returns
1386 * UNSUPPORTED_KEY_SIZE.
1387 */
1388TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1389 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1390 GenerateKey(AuthorizationSetBuilder()
1391 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1392 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001393 .Digest(Digest::NONE)
1394 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001395}
1396
1397/*
1398 * NewKeyGenerationTest.EcdsaInvalidSize
1399 *
1400 * Verifies that specifying an invalid key size for EC key generation returns
1401 * UNSUPPORTED_KEY_SIZE.
1402 */
1403TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1404 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1405 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001406 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001407 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1408 .EcdsaSigningKey(key_size)
1409 .Digest(Digest::NONE)
1410 .SetDefaultValidity(),
1411 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001412 }
1413
Janis Danisevskis164bb872021-02-09 11:30:25 -08001414 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1415 .EcdsaSigningKey(190)
1416 .Digest(Digest::NONE)
1417 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001418}
1419
1420/*
1421 * NewKeyGenerationTest.EcdsaMismatchKeySize
1422 *
1423 * Verifies that specifying mismatched key size and curve for EC key generation returns
1424 * INVALID_ARGUMENT.
1425 */
1426TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1427 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1428
1429 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1430 GenerateKey(AuthorizationSetBuilder()
1431 .EcdsaSigningKey(224)
1432 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001433 .Digest(Digest::NONE)
1434 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001435}
1436
1437/*
1438 * NewKeyGenerationTest.EcdsaAllValidSizes
1439 *
1440 * Verifies that keymint supports all required EC key sizes.
1441 */
1442TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1443 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1444 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001445 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1446 .EcdsaSigningKey(size)
1447 .Digest(Digest::NONE)
1448 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001449 << "Failed to generate size: " << size;
1450 CheckedDeleteKey();
1451 }
1452}
1453
1454/*
1455 * NewKeyGenerationTest.EcdsaInvalidCurves
1456 *
1457 * Verifies that keymint does not support any curve designated as unsupported.
1458 */
1459TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1460 Digest digest;
1461 if (SecLevel() == SecurityLevel::STRONGBOX) {
1462 digest = Digest::SHA_2_256;
1463 } else {
1464 digest = Digest::SHA_2_512;
1465 }
1466 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001467 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1468 .EcdsaSigningKey(curve)
1469 .Digest(digest)
1470 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001471 << "Failed to generate key on curve: " << curve;
1472 CheckedDeleteKey();
1473 }
1474}
1475
1476/*
1477 * NewKeyGenerationTest.Hmac
1478 *
1479 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1480 * characteristics.
1481 */
1482TEST_P(NewKeyGenerationTest, Hmac) {
1483 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1484 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001485 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001486 constexpr size_t key_size = 128;
1487 ASSERT_EQ(ErrorCode::OK,
1488 GenerateKey(
1489 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1490 TAG_MIN_MAC_LENGTH, 128),
1491 &key_blob, &key_characteristics));
1492
1493 ASSERT_GT(key_blob.size(), 0U);
1494 CheckBaseParams(key_characteristics);
1495
Shawn Willden7f424372021-01-10 18:06:50 -07001496 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1497 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1498 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1499 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001500
1501 CheckedDeleteKey(&key_blob);
1502 }
1503}
1504
1505/*
Selene Huang4f64c222021-04-13 19:54:36 -07001506 * NewKeyGenerationTest.HmacNoAttestation
1507 *
1508 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1509 * and app id are provided.
1510 */
1511TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1512 auto challenge = "hello";
1513 auto app_id = "foo";
1514
1515 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1516 vector<uint8_t> key_blob;
1517 vector<KeyCharacteristics> key_characteristics;
1518 constexpr size_t key_size = 128;
1519 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1520 .HmacKey(key_size)
1521 .Digest(digest)
1522 .AttestationChallenge(challenge)
1523 .AttestationApplicationId(app_id)
1524 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1525 &key_blob, &key_characteristics));
1526
1527 ASSERT_GT(key_blob.size(), 0U);
1528 ASSERT_EQ(cert_chain_.size(), 0);
1529 CheckBaseParams(key_characteristics);
1530
1531 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1532 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1533 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1534 << "Key size " << key_size << "missing";
1535
1536 CheckedDeleteKey(&key_blob);
1537 }
1538}
1539
1540/*
Qi Wud22ec842020-11-26 13:27:53 +08001541 * NewKeyGenerationTest.LimitedUsageHmac
1542 *
1543 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1544 * resulting keys have correct characteristics.
1545 */
1546TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1547 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1548 vector<uint8_t> key_blob;
1549 vector<KeyCharacteristics> key_characteristics;
1550 constexpr size_t key_size = 128;
1551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1552 .HmacKey(key_size)
1553 .Digest(digest)
1554 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1555 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1556 &key_blob, &key_characteristics));
1557
1558 ASSERT_GT(key_blob.size(), 0U);
1559 CheckBaseParams(key_characteristics);
1560
1561 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1562 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1563 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1564 << "Key size " << key_size << "missing";
1565
1566 // Check the usage count limit tag appears in the authorizations.
1567 AuthorizationSet auths;
1568 for (auto& entry : key_characteristics) {
1569 auths.push_back(AuthorizationSet(entry.authorizations));
1570 }
1571 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1572 << "key usage count limit " << 1U << " missing";
1573
1574 CheckedDeleteKey(&key_blob);
1575 }
1576}
1577
1578/*
Selene Huang31ab4042020-04-29 04:22:39 -07001579 * NewKeyGenerationTest.HmacCheckKeySizes
1580 *
1581 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1582 */
1583TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1584 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1585 if (key_size < 64 || key_size % 8 != 0) {
1586 // To keep this test from being very slow, we only test a random fraction of
1587 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1588 // them, we expect to run ~40 of them in each run.
1589 if (key_size % 8 == 0 || random() % 10 == 0) {
1590 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1591 GenerateKey(AuthorizationSetBuilder()
1592 .HmacKey(key_size)
1593 .Digest(Digest::SHA_2_256)
1594 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1595 << "HMAC key size " << key_size << " invalid";
1596 }
1597 } else {
1598 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1599 .HmacKey(key_size)
1600 .Digest(Digest::SHA_2_256)
1601 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1602 << "Failed to generate HMAC key of size " << key_size;
1603 CheckedDeleteKey();
1604 }
1605 }
1606}
1607
1608/*
1609 * NewKeyGenerationTest.HmacCheckMinMacLengths
1610 *
1611 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1612 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1613 * specific MAC length that failed, so reproducing a failed run will be easy.
1614 */
1615TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1616 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1617 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1618 // To keep this test from being very long, we only test a random fraction of
1619 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1620 // we expect to run ~17 of them in each run.
1621 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1622 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1623 GenerateKey(AuthorizationSetBuilder()
1624 .HmacKey(128)
1625 .Digest(Digest::SHA_2_256)
1626 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1627 << "HMAC min mac length " << min_mac_length << " invalid.";
1628 }
1629 } else {
1630 EXPECT_EQ(ErrorCode::OK,
1631 GenerateKey(AuthorizationSetBuilder()
1632 .HmacKey(128)
1633 .Digest(Digest::SHA_2_256)
1634 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1635 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1636 CheckedDeleteKey();
1637 }
1638 }
1639}
1640
1641/*
1642 * NewKeyGenerationTest.HmacMultipleDigests
1643 *
1644 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1645 */
1646TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1647 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1648
1649 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1650 GenerateKey(AuthorizationSetBuilder()
1651 .HmacKey(128)
1652 .Digest(Digest::SHA1)
1653 .Digest(Digest::SHA_2_256)
1654 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1655}
1656
1657/*
1658 * NewKeyGenerationTest.HmacDigestNone
1659 *
1660 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1661 */
1662TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1663 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1664 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1665 128)));
1666
1667 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1668 GenerateKey(AuthorizationSetBuilder()
1669 .HmacKey(128)
1670 .Digest(Digest::NONE)
1671 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1672}
1673
Selene Huang4f64c222021-04-13 19:54:36 -07001674/*
1675 * NewKeyGenerationTest.AesNoAttestation
1676 *
1677 * Verifies that attestation parameters to AES keys are ignored and generateKey
1678 * will succeed.
1679 */
1680TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1681 auto challenge = "hello";
1682 auto app_id = "foo";
1683
1684 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1685 .Authorization(TAG_NO_AUTH_REQUIRED)
1686 .AesEncryptionKey(128)
1687 .EcbMode()
1688 .Padding(PaddingMode::PKCS7)
1689 .AttestationChallenge(challenge)
1690 .AttestationApplicationId(app_id)));
1691
1692 ASSERT_EQ(cert_chain_.size(), 0);
1693}
1694
1695/*
1696 * NewKeyGenerationTest.TripleDesNoAttestation
1697 *
1698 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1699 * will be successful. No attestation should be generated.
1700 */
1701TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1702 auto challenge = "hello";
1703 auto app_id = "foo";
1704
1705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1706 .TripleDesEncryptionKey(168)
1707 .BlockMode(BlockMode::ECB)
1708 .Authorization(TAG_NO_AUTH_REQUIRED)
1709 .Padding(PaddingMode::NONE)
1710 .AttestationChallenge(challenge)
1711 .AttestationApplicationId(app_id)));
1712 ASSERT_EQ(cert_chain_.size(), 0);
1713}
1714
Selene Huang31ab4042020-04-29 04:22:39 -07001715INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1716
1717typedef KeyMintAidlTestBase SigningOperationsTest;
1718
1719/*
1720 * SigningOperationsTest.RsaSuccess
1721 *
1722 * Verifies that raw RSA signature operations succeed.
1723 */
1724TEST_P(SigningOperationsTest, RsaSuccess) {
1725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1726 .RsaSigningKey(2048, 65537)
1727 .Digest(Digest::NONE)
1728 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001729 .Authorization(TAG_NO_AUTH_REQUIRED)
1730 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001731 string message = "12345678901234567890123456789012";
1732 string signature = SignMessage(
1733 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1734}
1735
1736/*
1737 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1738 *
Shawn Willden7f424372021-01-10 18:06:50 -07001739 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001740 */
1741TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1743 .Authorization(TAG_NO_AUTH_REQUIRED)
1744 .RsaSigningKey(2048, 65537)
1745 .Digest(Digest::NONE)
1746 .Padding(PaddingMode::NONE)
1747 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001748 .Authorization(TAG_APPLICATION_DATA, "appdata")
1749 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001750 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1751 Begin(KeyPurpose::SIGN,
1752 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1753 AbortIfNeeded();
1754 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1755 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1756 .Digest(Digest::NONE)
1757 .Padding(PaddingMode::NONE)
1758 .Authorization(TAG_APPLICATION_ID, "clientid")));
1759 AbortIfNeeded();
1760 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1761 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1762 .Digest(Digest::NONE)
1763 .Padding(PaddingMode::NONE)
1764 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1765 AbortIfNeeded();
1766 EXPECT_EQ(ErrorCode::OK,
1767 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1768 .Digest(Digest::NONE)
1769 .Padding(PaddingMode::NONE)
1770 .Authorization(TAG_APPLICATION_DATA, "appdata")
1771 .Authorization(TAG_APPLICATION_ID, "clientid")));
1772 AbortIfNeeded();
1773}
1774
1775/*
1776 * SigningOperationsTest.RsaPssSha256Success
1777 *
1778 * Verifies that RSA-PSS signature operations succeed.
1779 */
1780TEST_P(SigningOperationsTest, RsaPssSha256Success) {
1781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1782 .RsaSigningKey(2048, 65537)
1783 .Digest(Digest::SHA_2_256)
1784 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001785 .Authorization(TAG_NO_AUTH_REQUIRED)
1786 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001787 // Use large message, which won't work without digesting.
1788 string message(1024, 'a');
1789 string signature = SignMessage(
1790 message,
1791 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1792}
1793
1794/*
1795 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1796 *
1797 * Verifies that keymint rejects signature operations that specify a padding mode when the key
1798 * supports only unpadded operations.
1799 */
1800TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1801 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1802 .RsaSigningKey(2048, 65537)
1803 .Digest(Digest::NONE)
1804 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001805 .Padding(PaddingMode::NONE)
1806 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001807 string message = "12345678901234567890123456789012";
1808 string signature;
1809
1810 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1811 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1812 .Digest(Digest::NONE)
1813 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1814}
1815
1816/*
1817 * SigningOperationsTest.NoUserConfirmation
1818 *
1819 * Verifies that keymint rejects signing operations for keys with
1820 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1821 * presented.
1822 */
1823TEST_P(SigningOperationsTest, NoUserConfirmation) {
1824 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1826 .RsaSigningKey(1024, 65537)
1827 .Digest(Digest::NONE)
1828 .Padding(PaddingMode::NONE)
1829 .Authorization(TAG_NO_AUTH_REQUIRED)
1830 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1831 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001832
1833 const string message = "12345678901234567890123456789012";
1834 EXPECT_EQ(ErrorCode::OK,
1835 Begin(KeyPurpose::SIGN,
1836 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1837 string signature;
1838 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1839}
1840
1841/*
1842 * SigningOperationsTest.RsaPkcs1Sha256Success
1843 *
1844 * Verifies that digested RSA-PKCS1 signature operations succeed.
1845 */
1846TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1847 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1848 .RsaSigningKey(2048, 65537)
1849 .Digest(Digest::SHA_2_256)
1850 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001851 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1852 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001853 string message(1024, 'a');
1854 string signature = SignMessage(message, AuthorizationSetBuilder()
1855 .Digest(Digest::SHA_2_256)
1856 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1857}
1858
1859/*
1860 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1861 *
1862 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1863 */
1864TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1865 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1866 .RsaSigningKey(2048, 65537)
1867 .Digest(Digest::NONE)
1868 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001869 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1870 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001871 string message(53, 'a');
1872 string signature = SignMessage(message, AuthorizationSetBuilder()
1873 .Digest(Digest::NONE)
1874 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1875}
1876
1877/*
1878 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1879 *
1880 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1881 * given a too-long message.
1882 */
1883TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1885 .RsaSigningKey(2048, 65537)
1886 .Digest(Digest::NONE)
1887 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001888 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1889 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001890 string message(257, 'a');
1891
1892 EXPECT_EQ(ErrorCode::OK,
1893 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1894 .Digest(Digest::NONE)
1895 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1896 string signature;
1897 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1898}
1899
1900/*
1901 * SigningOperationsTest.RsaPssSha512TooSmallKey
1902 *
1903 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1904 * used with a key that is too small for the message.
1905 *
1906 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
1907 * keymint specification requires that salt_size == digest_size, so the message will be
1908 * digest_size * 2 +
1909 * 16. Such a message can only be signed by a given key if the key is at least that size. This
1910 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
1911 * for a 1024-bit key.
1912 */
1913TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1914 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1916 .RsaSigningKey(1024, 65537)
1917 .Digest(Digest::SHA_2_512)
1918 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001919 .Padding(PaddingMode::RSA_PSS)
1920 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001921 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1922 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1923 .Digest(Digest::SHA_2_512)
1924 .Padding(PaddingMode::RSA_PSS)));
1925}
1926
1927/*
1928 * SigningOperationsTest.RsaNoPaddingTooLong
1929 *
1930 * Verifies that raw RSA signature operations fail with the correct error code when
1931 * given a too-long message.
1932 */
1933TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1934 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1935 .RsaSigningKey(2048, 65537)
1936 .Digest(Digest::NONE)
1937 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001938 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1939 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001940 // One byte too long
1941 string message(2048 / 8 + 1, 'a');
1942 ASSERT_EQ(ErrorCode::OK,
1943 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1944 .Digest(Digest::NONE)
1945 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1946 string result;
1947 ErrorCode finish_error_code = Finish(message, &result);
1948 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1949 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1950
1951 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1952 message = string(128 * 1024, 'a');
1953 ASSERT_EQ(ErrorCode::OK,
1954 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1955 .Digest(Digest::NONE)
1956 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1957 finish_error_code = Finish(message, &result);
1958 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1959 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1960}
1961
1962/*
1963 * SigningOperationsTest.RsaAbort
1964 *
1965 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1966 * test, but the behavior should be algorithm and purpose-independent.
1967 */
1968TEST_P(SigningOperationsTest, RsaAbort) {
1969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1970 .RsaSigningKey(2048, 65537)
1971 .Digest(Digest::NONE)
1972 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001973 .Padding(PaddingMode::NONE)
1974 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001975
1976 ASSERT_EQ(ErrorCode::OK,
1977 Begin(KeyPurpose::SIGN,
1978 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1979 EXPECT_EQ(ErrorCode::OK, Abort());
1980
1981 // Another abort should fail
1982 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1983
1984 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001985 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001986}
1987
1988/*
1989 * SigningOperationsTest.RsaUnsupportedPadding
1990 *
1991 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1992 * with a padding mode inappropriate for RSA.
1993 */
1994TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1995 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1996 .RsaSigningKey(2048, 65537)
1997 .Authorization(TAG_NO_AUTH_REQUIRED)
1998 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001999 .Padding(PaddingMode::PKCS7)
2000 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002001 ASSERT_EQ(
2002 ErrorCode::UNSUPPORTED_PADDING_MODE,
2003 Begin(KeyPurpose::SIGN,
2004 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
2005}
2006
2007/*
2008 * SigningOperationsTest.RsaPssNoDigest
2009 *
2010 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2011 */
2012TEST_P(SigningOperationsTest, RsaNoDigest) {
2013 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2014 .RsaSigningKey(2048, 65537)
2015 .Authorization(TAG_NO_AUTH_REQUIRED)
2016 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002017 .Padding(PaddingMode::RSA_PSS)
2018 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002019 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2020 Begin(KeyPurpose::SIGN,
2021 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2022
2023 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2024 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2025}
2026
2027/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002028 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002029 *
2030 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2031 * supported in some cases (as validated in other tests), but a mode must be specified.
2032 */
2033TEST_P(SigningOperationsTest, RsaNoPadding) {
2034 // Padding must be specified
2035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2036 .RsaKey(2048, 65537)
2037 .Authorization(TAG_NO_AUTH_REQUIRED)
2038 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002039 .Digest(Digest::NONE)
2040 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002041 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2042 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2043}
2044
2045/*
2046 * SigningOperationsTest.RsaShortMessage
2047 *
2048 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2049 */
2050TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2051 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2052 .Authorization(TAG_NO_AUTH_REQUIRED)
2053 .RsaSigningKey(2048, 65537)
2054 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002055 .Padding(PaddingMode::NONE)
2056 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002057
2058 // Barely shorter
2059 string message(2048 / 8 - 1, 'a');
2060 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2061
2062 // Much shorter
2063 message = "a";
2064 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2065}
2066
2067/*
2068 * SigningOperationsTest.RsaSignWithEncryptionKey
2069 *
2070 * Verifies that RSA encryption keys cannot be used to sign.
2071 */
2072TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2073 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2074 .Authorization(TAG_NO_AUTH_REQUIRED)
2075 .RsaEncryptionKey(2048, 65537)
2076 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002077 .Padding(PaddingMode::NONE)
2078 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002079 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2080 Begin(KeyPurpose::SIGN,
2081 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2082}
2083
2084/*
2085 * SigningOperationsTest.RsaSignTooLargeMessage
2086 *
2087 * Verifies that attempting a raw signature of a message which is the same length as the key,
2088 * but numerically larger than the public modulus, fails with the correct error.
2089 */
2090TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2092 .Authorization(TAG_NO_AUTH_REQUIRED)
2093 .RsaSigningKey(2048, 65537)
2094 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002095 .Padding(PaddingMode::NONE)
2096 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002097
2098 // Largest possible message will always be larger than the public modulus.
2099 string message(2048 / 8, static_cast<char>(0xff));
2100 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2101 .Authorization(TAG_NO_AUTH_REQUIRED)
2102 .Digest(Digest::NONE)
2103 .Padding(PaddingMode::NONE)));
2104 string signature;
2105 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2106}
2107
2108/*
2109 * SigningOperationsTest.EcdsaAllSizesAndHashes
2110 *
2111 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2112 */
2113TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2114 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2115 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2116 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2117 .Authorization(TAG_NO_AUTH_REQUIRED)
2118 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002119 .Digest(digest)
2120 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002121 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2122 << " and digest " << digest;
2123 if (error != ErrorCode::OK) continue;
2124
2125 string message(1024, 'a');
2126 if (digest == Digest::NONE) message.resize(key_size / 8);
2127 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2128 CheckedDeleteKey();
2129 }
2130 }
2131}
2132
2133/*
2134 * SigningOperationsTest.EcdsaAllCurves
2135 *
2136 * Verifies that ECDSA operations succeed with all possible curves.
2137 */
2138TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2139 for (auto curve : ValidCurves()) {
2140 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2141 .Authorization(TAG_NO_AUTH_REQUIRED)
2142 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002143 .Digest(Digest::SHA_2_256)
2144 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002145 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2146 if (error != ErrorCode::OK) continue;
2147
2148 string message(1024, 'a');
2149 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2150 CheckedDeleteKey();
2151 }
2152}
2153
2154/*
2155 * SigningOperationsTest.EcdsaNoDigestHugeData
2156 *
2157 * Verifies that ECDSA operations support very large messages, even without digesting. This
2158 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2159 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2160 * the framework.
2161 */
2162TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2163 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2164 .Authorization(TAG_NO_AUTH_REQUIRED)
2165 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002166 .Digest(Digest::NONE)
2167 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002168 string message(1 * 1024, 'a');
2169 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2170}
2171
2172/*
2173 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2174 *
2175 * Verifies that using an EC key requires the correct app ID/data.
2176 */
2177TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2178 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2179 .Authorization(TAG_NO_AUTH_REQUIRED)
2180 .EcdsaSigningKey(256)
2181 .Digest(Digest::NONE)
2182 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002183 .Authorization(TAG_APPLICATION_DATA, "appdata")
2184 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002185 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2186 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2187 AbortIfNeeded();
2188 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2189 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2190 .Digest(Digest::NONE)
2191 .Authorization(TAG_APPLICATION_ID, "clientid")));
2192 AbortIfNeeded();
2193 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2194 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2195 .Digest(Digest::NONE)
2196 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2197 AbortIfNeeded();
2198 EXPECT_EQ(ErrorCode::OK,
2199 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2200 .Digest(Digest::NONE)
2201 .Authorization(TAG_APPLICATION_DATA, "appdata")
2202 .Authorization(TAG_APPLICATION_ID, "clientid")));
2203 AbortIfNeeded();
2204}
2205
2206/*
2207 * SigningOperationsTest.AesEcbSign
2208 *
2209 * Verifies that attempts to use AES keys to sign fail in the correct way.
2210 */
2211TEST_P(SigningOperationsTest, AesEcbSign) {
2212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2213 .Authorization(TAG_NO_AUTH_REQUIRED)
2214 .SigningKey()
2215 .AesEncryptionKey(128)
2216 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2217
2218 AuthorizationSet out_params;
2219 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2220 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2221 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2222 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2223}
2224
2225/*
2226 * SigningOperationsTest.HmacAllDigests
2227 *
2228 * Verifies that HMAC works with all digests.
2229 */
2230TEST_P(SigningOperationsTest, HmacAllDigests) {
2231 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2232 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2233 .Authorization(TAG_NO_AUTH_REQUIRED)
2234 .HmacKey(128)
2235 .Digest(digest)
2236 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2237 << "Failed to create HMAC key with digest " << digest;
2238 string message = "12345678901234567890123456789012";
2239 string signature = MacMessage(message, digest, 160);
2240 EXPECT_EQ(160U / 8U, signature.size())
2241 << "Failed to sign with HMAC key with digest " << digest;
2242 CheckedDeleteKey();
2243 }
2244}
2245
2246/*
2247 * SigningOperationsTest.HmacSha256TooLargeMacLength
2248 *
2249 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2250 * digest size.
2251 */
2252TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2253 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2254 .Authorization(TAG_NO_AUTH_REQUIRED)
2255 .HmacKey(128)
2256 .Digest(Digest::SHA_2_256)
2257 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2258 AuthorizationSet output_params;
2259 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2260 AuthorizationSetBuilder()
2261 .Digest(Digest::SHA_2_256)
2262 .Authorization(TAG_MAC_LENGTH, 264),
2263 &output_params));
2264}
2265
2266/*
2267 * SigningOperationsTest.HmacSha256TooSmallMacLength
2268 *
2269 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2270 * specified minimum MAC length.
2271 */
2272TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2273 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2274 .Authorization(TAG_NO_AUTH_REQUIRED)
2275 .HmacKey(128)
2276 .Digest(Digest::SHA_2_256)
2277 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2278 AuthorizationSet output_params;
2279 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2280 AuthorizationSetBuilder()
2281 .Digest(Digest::SHA_2_256)
2282 .Authorization(TAG_MAC_LENGTH, 120),
2283 &output_params));
2284}
2285
2286/*
2287 * SigningOperationsTest.HmacRfc4231TestCase3
2288 *
2289 * Validates against the test vectors from RFC 4231 test case 3.
2290 */
2291TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2292 string key(20, 0xaa);
2293 string message(50, 0xdd);
2294 uint8_t sha_224_expected[] = {
2295 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2296 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2297 };
2298 uint8_t sha_256_expected[] = {
2299 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2300 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2301 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2302 };
2303 uint8_t sha_384_expected[] = {
2304 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2305 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2306 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2307 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2308 };
2309 uint8_t sha_512_expected[] = {
2310 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2311 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2312 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2313 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2314 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2315 };
2316
2317 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2318 if (SecLevel() != SecurityLevel::STRONGBOX) {
2319 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2320 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2321 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2322 }
2323}
2324
2325/*
2326 * SigningOperationsTest.HmacRfc4231TestCase5
2327 *
2328 * Validates against the test vectors from RFC 4231 test case 5.
2329 */
2330TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2331 string key(20, 0x0c);
2332 string message = "Test With Truncation";
2333
2334 uint8_t sha_224_expected[] = {
2335 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2336 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2337 };
2338 uint8_t sha_256_expected[] = {
2339 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2340 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2341 };
2342 uint8_t sha_384_expected[] = {
2343 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2344 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2345 };
2346 uint8_t sha_512_expected[] = {
2347 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2348 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2349 };
2350
2351 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2352 if (SecLevel() != SecurityLevel::STRONGBOX) {
2353 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2354 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2355 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2356 }
2357}
2358
2359INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2360
2361typedef KeyMintAidlTestBase VerificationOperationsTest;
2362
2363/*
2364 * VerificationOperationsTest.RsaSuccess
2365 *
2366 * Verifies that a simple RSA signature/verification sequence succeeds.
2367 */
2368TEST_P(VerificationOperationsTest, RsaSuccess) {
2369 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2370 .Authorization(TAG_NO_AUTH_REQUIRED)
2371 .RsaSigningKey(2048, 65537)
2372 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002373 .Padding(PaddingMode::NONE)
2374 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002375 string message = "12345678901234567890123456789012";
2376 string signature = SignMessage(
2377 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2378 VerifyMessage(message, signature,
2379 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2380}
2381
2382/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002383 * VerificationOperationsTest.RsaAllPaddingsAndDigests
Selene Huang31ab4042020-04-29 04:22:39 -07002384 *
2385 * Verifies RSA signature/verification for all padding modes and digests.
2386 */
2387TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2388 auto authorizations = AuthorizationSetBuilder()
2389 .Authorization(TAG_NO_AUTH_REQUIRED)
2390 .RsaSigningKey(2048, 65537)
2391 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2392 .Padding(PaddingMode::NONE)
2393 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002394 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2395 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002396
2397 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2398
2399 string message(128, 'a');
2400 string corrupt_message(message);
2401 ++corrupt_message[corrupt_message.size() / 2];
2402
2403 for (auto padding :
2404 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2405 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2406 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2407 // Digesting only makes sense with padding.
2408 continue;
2409 }
2410
2411 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2412 // PSS requires digesting.
2413 continue;
2414 }
2415
2416 string signature =
2417 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2418 VerifyMessage(message, signature,
2419 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2420
2421 /* TODO(seleneh) add exportkey tests back later when we have decided on
2422 * the new api.
2423 if (digest != Digest::NONE) {
2424 // Verify with OpenSSL.
2425 vector<uint8_t> pubkey;
2426 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2427
2428 const uint8_t* p = pubkey.data();
2429 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2430 ASSERT_TRUE(pkey.get());
2431
2432 EVP_MD_CTX digest_ctx;
2433 EVP_MD_CTX_init(&digest_ctx);
2434 EVP_PKEY_CTX* pkey_ctx;
2435 const EVP_MD* md = openssl_digest(digest);
2436 ASSERT_NE(md, nullptr);
2437 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2438 nullptr, pkey.get()));
2439
2440 switch (padding) {
2441 case PaddingMode::RSA_PSS:
2442 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2443 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2444 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2445 // PKCS1 is the default; don't need to set anything.
2446 break;
2447 default:
2448 FAIL();
2449 break;
2450 }
2451
2452 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2453 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2454 reinterpret_cast<const
2455 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2456 }
2457 */
2458
2459 // Corrupt signature shouldn't verify.
2460 string corrupt_signature(signature);
2461 ++corrupt_signature[corrupt_signature.size() / 2];
2462
2463 EXPECT_EQ(ErrorCode::OK,
2464 Begin(KeyPurpose::VERIFY,
2465 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2466 string result;
2467 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2468
2469 // Corrupt message shouldn't verify
2470 EXPECT_EQ(ErrorCode::OK,
2471 Begin(KeyPurpose::VERIFY,
2472 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2473 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2474 }
2475 }
2476}
2477
2478/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002479 * VerificationOperationsTest.RsaAllDigestsAndCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002480 *
2481 * Verifies ECDSA signature/verification for all digests and curves.
2482 */
2483TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2484 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2485
2486 string message = "1234567890";
2487 string corrupt_message = "2234567890";
2488 for (auto curve : ValidCurves()) {
2489 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2490 .Authorization(TAG_NO_AUTH_REQUIRED)
2491 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002492 .Digest(digests)
2493 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002494 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2495 if (error != ErrorCode::OK) {
2496 continue;
2497 }
2498
2499 for (auto digest : digests) {
2500 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2501 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2502
2503 /* TODO(seleneh) add exportkey tests back later when we have decided on
2504 * the new api.
2505
2506 // Verify with OpenSSL
2507 if (digest != Digest::NONE) {
2508 vector<uint8_t> pubkey;
2509 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2510 << curve << ' ' << digest;
2511
2512 const uint8_t* p = pubkey.data();
2513 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2514 ASSERT_TRUE(pkey.get());
2515
2516 EVP_MD_CTX digest_ctx;
2517 EVP_MD_CTX_init(&digest_ctx);
2518 EVP_PKEY_CTX* pkey_ctx;
2519 const EVP_MD* md = openssl_digest(digest);
2520
2521 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2522 nullptr, pkey.get()))
2523 << curve << ' ' << digest;
2524
2525 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2526 message.size()))
2527 << curve << ' ' << digest;
2528
2529 EXPECT_EQ(1,
2530 EVP_DigestVerifyFinal(&digest_ctx,
2531 reinterpret_cast<const
2532 uint8_t*>(signature.data()), signature.size()))
2533 << curve << ' ' << digest;
2534
2535 EVP_MD_CTX_cleanup(&digest_ctx);
2536 }
2537 */
2538 // Corrupt signature shouldn't verify.
2539 string corrupt_signature(signature);
2540 ++corrupt_signature[corrupt_signature.size() / 2];
2541
2542 EXPECT_EQ(ErrorCode::OK,
2543 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2544 << curve << ' ' << digest;
2545
2546 string result;
2547 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2548 << curve << ' ' << digest;
2549
2550 // Corrupt message shouldn't verify
2551 EXPECT_EQ(ErrorCode::OK,
2552 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2553 << curve << ' ' << digest;
2554
2555 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2556 << curve << ' ' << digest;
2557 }
2558
2559 auto rc = DeleteKey();
2560 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2561 }
2562}
2563
2564/*
2565 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2566 *
2567 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2568 */
2569TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2570 string key_material = "HelloThisIsAKey";
2571
2572 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002573 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002574 EXPECT_EQ(ErrorCode::OK,
2575 ImportKey(AuthorizationSetBuilder()
2576 .Authorization(TAG_NO_AUTH_REQUIRED)
2577 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2578 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2579 .Digest(Digest::SHA_2_256)
2580 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2581 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2582 EXPECT_EQ(ErrorCode::OK,
2583 ImportKey(AuthorizationSetBuilder()
2584 .Authorization(TAG_NO_AUTH_REQUIRED)
2585 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2586 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2587 .Digest(Digest::SHA_2_256)
2588 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2589 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2590
2591 string message = "This is a message.";
2592 string signature = SignMessage(
2593 signing_key, message,
2594 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2595
2596 // Signing key should not work.
2597 AuthorizationSet out_params;
2598 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2599 Begin(KeyPurpose::VERIFY, signing_key,
2600 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2601
2602 // Verification key should work.
2603 VerifyMessage(verification_key, message, signature,
2604 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2605
2606 CheckedDeleteKey(&signing_key);
2607 CheckedDeleteKey(&verification_key);
2608}
2609
2610INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2611
2612typedef KeyMintAidlTestBase ExportKeyTest;
2613
2614/*
2615 * ExportKeyTest.RsaUnsupportedKeyFormat
2616 *
2617 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2618 */
2619// TODO(seleneh) add ExportKey to GenerateKey
2620// check result
2621
2622class ImportKeyTest : public KeyMintAidlTestBase {
2623 public:
2624 template <TagType tag_type, Tag tag, typename ValueT>
2625 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2626 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002627 for (auto& entry : key_characteristics_) {
2628 if (entry.securityLevel == SecLevel()) {
2629 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2630 << "Tag " << tag << " with value " << expected
2631 << " not found at security level" << entry.securityLevel;
2632 } else {
2633 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2634 << "Tag " << tag << " found at security level " << entry.securityLevel;
2635 }
Selene Huang31ab4042020-04-29 04:22:39 -07002636 }
2637 }
2638
2639 void CheckOrigin() {
2640 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002641 // Origin isn't a crypto param, but it always lives with them.
2642 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002643 }
2644};
2645
2646/*
2647 * ImportKeyTest.RsaSuccess
2648 *
2649 * Verifies that importing and using an RSA key pair works correctly.
2650 */
2651TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002652 uint32_t key_size;
2653 string key;
2654
2655 if (SecLevel() == SecurityLevel::STRONGBOX) {
2656 key_size = 2048;
2657 key = rsa_2048_key;
2658 } else {
2659 key_size = 1024;
2660 key = rsa_key;
2661 }
2662
Selene Huang31ab4042020-04-29 04:22:39 -07002663 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2664 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07002665 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07002666 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002667 .Padding(PaddingMode::RSA_PSS)
2668 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07002669 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07002670
2671 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07002672 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002673 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2674 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2675 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2676 CheckOrigin();
2677
2678 string message(1024 / 8, 'a');
2679 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2680 string signature = SignMessage(message, params);
2681 VerifyMessage(message, signature, params);
2682}
2683
2684/*
2685 * ImportKeyTest.RsaKeySizeMismatch
2686 *
2687 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2688 * correct way.
2689 */
2690TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2691 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2692 ImportKey(AuthorizationSetBuilder()
2693 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2694 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002695 .Padding(PaddingMode::NONE)
2696 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002697 KeyFormat::PKCS8, rsa_key));
2698}
2699
2700/*
2701 * ImportKeyTest.RsaPublicExponentMismatch
2702 *
2703 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
2704 * fails in the correct way.
2705 */
2706TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2707 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2708 ImportKey(AuthorizationSetBuilder()
2709 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2710 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002711 .Padding(PaddingMode::NONE)
2712 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002713 KeyFormat::PKCS8, rsa_key));
2714}
2715
2716/*
2717 * ImportKeyTest.EcdsaSuccess
2718 *
2719 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2720 */
2721TEST_P(ImportKeyTest, EcdsaSuccess) {
2722 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2723 .Authorization(TAG_NO_AUTH_REQUIRED)
2724 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002725 .Digest(Digest::SHA_2_256)
2726 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002727 KeyFormat::PKCS8, ec_256_key));
2728
2729 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2730 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2731 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2732 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2733
2734 CheckOrigin();
2735
2736 string message(32, 'a');
2737 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2738 string signature = SignMessage(message, params);
2739 VerifyMessage(message, signature, params);
2740}
2741
2742/*
2743 * ImportKeyTest.EcdsaP256RFC5915Success
2744 *
2745 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
2746 * correctly.
2747 */
2748TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
2749 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2750 .Authorization(TAG_NO_AUTH_REQUIRED)
2751 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002752 .Digest(Digest::SHA_2_256)
2753 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002754 KeyFormat::PKCS8, ec_256_key_rfc5915));
2755
2756 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2757 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2758 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2759 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2760
2761 CheckOrigin();
2762
2763 string message(32, 'a');
2764 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2765 string signature = SignMessage(message, params);
2766 VerifyMessage(message, signature, params);
2767}
2768
2769/*
2770 * ImportKeyTest.EcdsaP256SEC1Success
2771 *
2772 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
2773 */
2774TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
2775 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2776 .Authorization(TAG_NO_AUTH_REQUIRED)
2777 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002778 .Digest(Digest::SHA_2_256)
2779 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002780 KeyFormat::PKCS8, ec_256_key_sec1));
2781
2782 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2783 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2784 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2785 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2786
2787 CheckOrigin();
2788
2789 string message(32, 'a');
2790 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2791 string signature = SignMessage(message, params);
2792 VerifyMessage(message, signature, params);
2793}
2794
2795/*
2796 * ImportKeyTest.Ecdsa521Success
2797 *
2798 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2799 */
2800TEST_P(ImportKeyTest, Ecdsa521Success) {
2801 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2802 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2803 .Authorization(TAG_NO_AUTH_REQUIRED)
2804 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002805 .Digest(Digest::SHA_2_256)
2806 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002807 KeyFormat::PKCS8, ec_521_key));
2808
2809 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2810 CheckCryptoParam(TAG_KEY_SIZE, 521U);
2811 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2812 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2813 CheckOrigin();
2814
2815 string message(32, 'a');
2816 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2817 string signature = SignMessage(message, params);
2818 VerifyMessage(message, signature, params);
2819}
2820
2821/*
2822 * ImportKeyTest.EcdsaSizeMismatch
2823 *
2824 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2825 * correct way.
2826 */
2827TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2828 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2829 ImportKey(AuthorizationSetBuilder()
2830 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002831 .Digest(Digest::NONE)
2832 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002833 KeyFormat::PKCS8, ec_256_key));
2834}
2835
2836/*
2837 * ImportKeyTest.EcdsaCurveMismatch
2838 *
2839 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
2840 * the correct way.
2841 */
2842TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2843 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2844 ImportKey(AuthorizationSetBuilder()
2845 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002846 .Digest(Digest::NONE)
2847 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002848 KeyFormat::PKCS8, ec_256_key));
2849}
2850
2851/*
2852 * ImportKeyTest.AesSuccess
2853 *
2854 * Verifies that importing and using an AES key works.
2855 */
2856TEST_P(ImportKeyTest, AesSuccess) {
2857 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2858 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2859 .Authorization(TAG_NO_AUTH_REQUIRED)
2860 .AesEncryptionKey(key.size() * 8)
2861 .EcbMode()
2862 .Padding(PaddingMode::PKCS7),
2863 KeyFormat::RAW, key));
2864
2865 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2866 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2867 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2868 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2869 CheckOrigin();
2870
2871 string message = "Hello World!";
2872 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2873 string ciphertext = EncryptMessage(message, params);
2874 string plaintext = DecryptMessage(ciphertext, params);
2875 EXPECT_EQ(message, plaintext);
2876}
2877
2878/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002879 * ImportKeyTest.AesFailure
2880 *
2881 * Verifies that importing an invalid AES key fails.
2882 */
2883TEST_P(ImportKeyTest, AesFailure) {
2884 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2885 uint32_t bitlen = key.size() * 8;
2886 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
2887 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2888 ImportKey(AuthorizationSetBuilder()
2889 .Authorization(TAG_NO_AUTH_REQUIRED)
2890 .AesEncryptionKey(key_size)
2891 .EcbMode()
2892 .Padding(PaddingMode::PKCS7),
2893 KeyFormat::RAW, key));
2894 }
2895}
2896
2897/*
2898 * ImportKeyTest.TripleDesSuccess
2899 *
2900 * Verifies that importing and using a 3DES key works.
2901 */
2902TEST_P(ImportKeyTest, TripleDesSuccess) {
2903 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
2904 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2905 .Authorization(TAG_NO_AUTH_REQUIRED)
2906 .TripleDesEncryptionKey(168)
2907 .EcbMode()
2908 .Padding(PaddingMode::PKCS7),
2909 KeyFormat::RAW, key));
2910
2911 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
2912 CheckCryptoParam(TAG_KEY_SIZE, 168U);
2913 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2914 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2915 CheckOrigin();
2916
2917 string message = "Hello World!";
2918 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2919 string ciphertext = EncryptMessage(message, params);
2920 string plaintext = DecryptMessage(ciphertext, params);
2921 EXPECT_EQ(message, plaintext);
2922}
2923
2924/*
2925 * ImportKeyTest.TripleDesFailure
2926 *
2927 * Verifies that importing an invalid 3DES key fails.
2928 */
2929TEST_P(ImportKeyTest, TripleDesFailure) {
2930 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
2931 uint32_t bitlen = key.size() * 8;
2932 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
2933 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2934 ImportKey(AuthorizationSetBuilder()
2935 .Authorization(TAG_NO_AUTH_REQUIRED)
2936 .TripleDesEncryptionKey(key_size)
2937 .EcbMode()
2938 .Padding(PaddingMode::PKCS7),
2939 KeyFormat::RAW, key));
2940 }
2941}
2942
2943/*
2944 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07002945 *
2946 * Verifies that importing and using an HMAC key works.
2947 */
2948TEST_P(ImportKeyTest, HmacKeySuccess) {
2949 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2950 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2951 .Authorization(TAG_NO_AUTH_REQUIRED)
2952 .HmacKey(key.size() * 8)
2953 .Digest(Digest::SHA_2_256)
2954 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2955 KeyFormat::RAW, key));
2956
2957 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2958 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2959 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2960 CheckOrigin();
2961
2962 string message = "Hello World!";
2963 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2964 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2965}
2966
2967INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
2968
2969auto wrapped_key = hex2str(
2970 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
2971 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
2972 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
2973 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
2974 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
2975 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
2976 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
2977 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
2978 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
2979
2980auto wrapped_key_masked = hex2str(
2981 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
2982 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
2983 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
2984 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
2985 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
2986 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
2987 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
2988 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
2989 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
2990
2991auto wrapping_key = hex2str(
2992 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
2993 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
2994 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
2995 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
2996 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
2997 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
2998 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
2999 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
3000 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
3001 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
3002 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
3003 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
3004 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
3005 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
3006 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
3007 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
3008 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
3009 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
3010 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
3011 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
3012 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
3013 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
3014 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
3015 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
3016 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
3017 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
3018 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
3019 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
3020 "f27ba61be6ad02dfddda8f4e6822");
3021
3022string zero_masking_key =
3023 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3024string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3025
3026class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3027
3028TEST_P(ImportWrappedKeyTest, Success) {
3029 auto wrapping_key_desc = AuthorizationSetBuilder()
3030 .RsaEncryptionKey(2048, 65537)
3031 .Digest(Digest::SHA_2_256)
3032 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003033 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3034 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003035
3036 ASSERT_EQ(ErrorCode::OK,
3037 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3038 AuthorizationSetBuilder()
3039 .Digest(Digest::SHA_2_256)
3040 .Padding(PaddingMode::RSA_OAEP)));
3041
3042 string message = "Hello World!";
3043 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3044 string ciphertext = EncryptMessage(message, params);
3045 string plaintext = DecryptMessage(ciphertext, params);
3046 EXPECT_EQ(message, plaintext);
3047}
3048
3049TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3050 auto wrapping_key_desc = AuthorizationSetBuilder()
3051 .RsaEncryptionKey(2048, 65537)
3052 .Digest(Digest::SHA_2_256)
3053 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003054 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3055 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003056
3057 ASSERT_EQ(ErrorCode::OK,
3058 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3059 AuthorizationSetBuilder()
3060 .Digest(Digest::SHA_2_256)
3061 .Padding(PaddingMode::RSA_OAEP)));
3062}
3063
3064TEST_P(ImportWrappedKeyTest, WrongMask) {
3065 auto wrapping_key_desc = AuthorizationSetBuilder()
3066 .RsaEncryptionKey(2048, 65537)
3067 .Digest(Digest::SHA_2_256)
3068 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003069 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3070 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003071
3072 ASSERT_EQ(
3073 ErrorCode::VERIFICATION_FAILED,
3074 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3075 AuthorizationSetBuilder()
3076 .Digest(Digest::SHA_2_256)
3077 .Padding(PaddingMode::RSA_OAEP)));
3078}
3079
3080TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3081 auto wrapping_key_desc = AuthorizationSetBuilder()
3082 .RsaEncryptionKey(2048, 65537)
3083 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003084 .Padding(PaddingMode::RSA_OAEP)
3085 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003086
3087 ASSERT_EQ(
3088 ErrorCode::INCOMPATIBLE_PURPOSE,
3089 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3090 AuthorizationSetBuilder()
3091 .Digest(Digest::SHA_2_256)
3092 .Padding(PaddingMode::RSA_OAEP)));
3093}
3094
3095INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3096
3097typedef KeyMintAidlTestBase EncryptionOperationsTest;
3098
3099/*
3100 * EncryptionOperationsTest.RsaNoPaddingSuccess
3101 *
3102 * Verifies that raw RSA encryption works.
3103 */
3104TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
3105 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3106 .Authorization(TAG_NO_AUTH_REQUIRED)
3107 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003108 .Padding(PaddingMode::NONE)
3109 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003110
3111 string message = string(2048 / 8, 'a');
3112 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3113 string ciphertext1 = EncryptMessage(message, params);
3114 EXPECT_EQ(2048U / 8, ciphertext1.size());
3115
3116 string ciphertext2 = EncryptMessage(message, params);
3117 EXPECT_EQ(2048U / 8, ciphertext2.size());
3118
3119 // Unpadded RSA is deterministic
3120 EXPECT_EQ(ciphertext1, ciphertext2);
3121}
3122
3123/*
3124 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3125 *
3126 * Verifies that raw RSA encryption of short messages works.
3127 */
3128TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3130 .Authorization(TAG_NO_AUTH_REQUIRED)
3131 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003132 .Padding(PaddingMode::NONE)
3133 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003134
3135 string message = "1";
3136 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3137
3138 string ciphertext = EncryptMessage(message, params);
3139 EXPECT_EQ(2048U / 8, ciphertext.size());
3140
3141 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3142 string plaintext = DecryptMessage(ciphertext, params);
3143
3144 EXPECT_EQ(expected_plaintext, plaintext);
3145
3146 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
3147 message = static_cast<char>(1);
3148 ciphertext = EncryptMessage(message, params);
3149 EXPECT_EQ(2048U / 8, ciphertext.size());
3150 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
3151}
3152
3153/*
3154 * EncryptionOperationsTest.RsaNoPaddingTooLong
3155 *
3156 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
3157 */
3158TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
3159 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3160 .Authorization(TAG_NO_AUTH_REQUIRED)
3161 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003162 .Padding(PaddingMode::NONE)
3163 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003164
3165 string message(2048 / 8 + 1, 'a');
3166
3167 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3168 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3169
3170 string result;
3171 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
3172}
3173
3174/*
3175 * EncryptionOperationsTest.RsaNoPaddingTooLarge
3176 *
3177 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
3178 * way.
3179 */
3180// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
3181// version of ExportKey inside generateKey
3182
3183/*
3184 * EncryptionOperationsTest.RsaOaepSuccess
3185 *
3186 * Verifies that RSA-OAEP encryption operations work, with all digests.
3187 */
3188TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3189 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3190
3191 size_t key_size = 2048; // Need largish key for SHA-512 test.
3192 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3193 .Authorization(TAG_NO_AUTH_REQUIRED)
3194 .RsaEncryptionKey(key_size, 65537)
3195 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003196 .Digest(digests)
3197 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003198
3199 string message = "Hello";
3200
3201 for (auto digest : digests) {
3202 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
3203 string ciphertext1 = EncryptMessage(message, params);
3204 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3205 EXPECT_EQ(key_size / 8, ciphertext1.size());
3206
3207 string ciphertext2 = EncryptMessage(message, params);
3208 EXPECT_EQ(key_size / 8, ciphertext2.size());
3209
3210 // OAEP randomizes padding so every result should be different (with astronomically high
3211 // probability).
3212 EXPECT_NE(ciphertext1, ciphertext2);
3213
3214 string plaintext1 = DecryptMessage(ciphertext1, params);
3215 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3216 string plaintext2 = DecryptMessage(ciphertext2, params);
3217 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3218
3219 // Decrypting corrupted ciphertext should fail.
3220 size_t offset_to_corrupt = random() % ciphertext1.size();
3221 char corrupt_byte;
3222 do {
3223 corrupt_byte = static_cast<char>(random() % 256);
3224 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3225 ciphertext1[offset_to_corrupt] = corrupt_byte;
3226
3227 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3228 string result;
3229 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3230 EXPECT_EQ(0U, result.size());
3231 }
3232}
3233
3234/*
3235 * EncryptionOperationsTest.RsaOaepInvalidDigest
3236 *
3237 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3238 * without a digest.
3239 */
3240TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3242 .Authorization(TAG_NO_AUTH_REQUIRED)
3243 .RsaEncryptionKey(2048, 65537)
3244 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003245 .Digest(Digest::NONE)
3246 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003247 string message = "Hello World!";
3248
3249 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
3250 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3251}
3252
3253/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003254 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003255 *
3256 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
3257 * with a different digest than was used to encrypt.
3258 */
3259TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3260 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3261
3262 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3263 .Authorization(TAG_NO_AUTH_REQUIRED)
3264 .RsaEncryptionKey(1024, 65537)
3265 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003266 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3267 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003268 string message = "Hello World!";
3269 string ciphertext = EncryptMessage(
3270 message,
3271 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3272
3273 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3274 .Digest(Digest::SHA_2_256)
3275 .Padding(PaddingMode::RSA_OAEP)));
3276 string result;
3277 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3278 EXPECT_EQ(0U, result.size());
3279}
3280
3281/*
3282 * EncryptionOperationsTest.RsaOaepTooLarge
3283 *
3284 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
3285 * too-large message.
3286 */
3287TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
3288 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3289 .Authorization(TAG_NO_AUTH_REQUIRED)
3290 .RsaEncryptionKey(2048, 65537)
3291 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003292 .Digest(Digest::SHA_2_256)
3293 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003294 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
3295 constexpr size_t oaep_overhead = 2 * digest_size + 2;
3296 string message(2048 / 8 - oaep_overhead + 1, 'a');
3297 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3298 .Padding(PaddingMode::RSA_OAEP)
3299 .Digest(Digest::SHA_2_256)));
3300 string result;
3301 ErrorCode error = Finish(message, &result);
3302 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3303 EXPECT_EQ(0U, result.size());
3304}
3305
3306/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003307 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3308 *
3309 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
3310 * digests.
3311 */
3312TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3313 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3314
3315 size_t key_size = 2048; // Need largish key for SHA-512 test.
3316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3317 .OaepMGFDigest(digests)
3318 .Authorization(TAG_NO_AUTH_REQUIRED)
3319 .RsaEncryptionKey(key_size, 65537)
3320 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003321 .Digest(Digest::SHA_2_256)
3322 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003323
3324 string message = "Hello";
3325
3326 for (auto digest : digests) {
3327 auto params = AuthorizationSetBuilder()
3328 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3329 .Digest(Digest::SHA_2_256)
3330 .Padding(PaddingMode::RSA_OAEP);
3331 string ciphertext1 = EncryptMessage(message, params);
3332 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3333 EXPECT_EQ(key_size / 8, ciphertext1.size());
3334
3335 string ciphertext2 = EncryptMessage(message, params);
3336 EXPECT_EQ(key_size / 8, ciphertext2.size());
3337
3338 // OAEP randomizes padding so every result should be different (with astronomically high
3339 // probability).
3340 EXPECT_NE(ciphertext1, ciphertext2);
3341
3342 string plaintext1 = DecryptMessage(ciphertext1, params);
3343 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3344 string plaintext2 = DecryptMessage(ciphertext2, params);
3345 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3346
3347 // Decrypting corrupted ciphertext should fail.
3348 size_t offset_to_corrupt = random() % ciphertext1.size();
3349 char corrupt_byte;
3350 do {
3351 corrupt_byte = static_cast<char>(random() % 256);
3352 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3353 ciphertext1[offset_to_corrupt] = corrupt_byte;
3354
3355 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3356 string result;
3357 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3358 EXPECT_EQ(0U, result.size());
3359 }
3360}
3361
3362/*
3363 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3364 *
3365 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3366 * with incompatible MGF digest.
3367 */
3368TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3369 ASSERT_EQ(ErrorCode::OK,
3370 GenerateKey(AuthorizationSetBuilder()
3371 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3372 .Authorization(TAG_NO_AUTH_REQUIRED)
3373 .RsaEncryptionKey(2048, 65537)
3374 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003375 .Digest(Digest::SHA_2_256)
3376 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003377 string message = "Hello World!";
3378
3379 auto params = AuthorizationSetBuilder()
3380 .Padding(PaddingMode::RSA_OAEP)
3381 .Digest(Digest::SHA_2_256)
3382 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
3383 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3384}
3385
3386/*
3387 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
3388 *
3389 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3390 * with unsupported MGF digest.
3391 */
3392TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
3393 ASSERT_EQ(ErrorCode::OK,
3394 GenerateKey(AuthorizationSetBuilder()
3395 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3396 .Authorization(TAG_NO_AUTH_REQUIRED)
3397 .RsaEncryptionKey(2048, 65537)
3398 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003399 .Digest(Digest::SHA_2_256)
3400 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003401 string message = "Hello World!";
3402
3403 auto params = AuthorizationSetBuilder()
3404 .Padding(PaddingMode::RSA_OAEP)
3405 .Digest(Digest::SHA_2_256)
3406 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
3407 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3408}
3409
3410/*
Selene Huang31ab4042020-04-29 04:22:39 -07003411 * EncryptionOperationsTest.RsaPkcs1Success
3412 *
3413 * Verifies that RSA PKCS encryption/decrypts works.
3414 */
3415TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
3416 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3417 .Authorization(TAG_NO_AUTH_REQUIRED)
3418 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003419 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3420 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003421
3422 string message = "Hello World!";
3423 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3424 string ciphertext1 = EncryptMessage(message, params);
3425 EXPECT_EQ(2048U / 8, ciphertext1.size());
3426
3427 string ciphertext2 = EncryptMessage(message, params);
3428 EXPECT_EQ(2048U / 8, ciphertext2.size());
3429
3430 // PKCS1 v1.5 randomizes padding so every result should be different.
3431 EXPECT_NE(ciphertext1, ciphertext2);
3432
3433 string plaintext = DecryptMessage(ciphertext1, params);
3434 EXPECT_EQ(message, plaintext);
3435
3436 // Decrypting corrupted ciphertext should fail.
3437 size_t offset_to_corrupt = random() % ciphertext1.size();
3438 char corrupt_byte;
3439 do {
3440 corrupt_byte = static_cast<char>(random() % 256);
3441 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3442 ciphertext1[offset_to_corrupt] = corrupt_byte;
3443
3444 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3445 string result;
3446 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3447 EXPECT_EQ(0U, result.size());
3448}
3449
3450/*
3451 * EncryptionOperationsTest.RsaPkcs1TooLarge
3452 *
3453 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
3454 */
3455TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
3456 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3457 .Authorization(TAG_NO_AUTH_REQUIRED)
3458 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003459 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3460 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003461 string message(2048 / 8 - 10, 'a');
3462
3463 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3464 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3465 string result;
3466 ErrorCode error = Finish(message, &result);
3467 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3468 EXPECT_EQ(0U, result.size());
3469}
3470
3471/*
3472 * EncryptionOperationsTest.EcdsaEncrypt
3473 *
3474 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
3475 */
3476TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
3477 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3478 .Authorization(TAG_NO_AUTH_REQUIRED)
3479 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003480 .Digest(Digest::NONE)
3481 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003482 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3483 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3484 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3485}
3486
3487/*
3488 * EncryptionOperationsTest.HmacEncrypt
3489 *
3490 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
3491 */
3492TEST_P(EncryptionOperationsTest, HmacEncrypt) {
3493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3494 .Authorization(TAG_NO_AUTH_REQUIRED)
3495 .HmacKey(128)
3496 .Digest(Digest::SHA_2_256)
3497 .Padding(PaddingMode::NONE)
3498 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3499 auto params = AuthorizationSetBuilder()
3500 .Digest(Digest::SHA_2_256)
3501 .Padding(PaddingMode::NONE)
3502 .Authorization(TAG_MAC_LENGTH, 128);
3503 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3504 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3505}
3506
3507/*
3508 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3509 *
3510 * Verifies that AES ECB mode works.
3511 */
3512TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
3513 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3514 .Authorization(TAG_NO_AUTH_REQUIRED)
3515 .AesEncryptionKey(128)
3516 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3517 .Padding(PaddingMode::NONE)));
3518
3519 ASSERT_GT(key_blob_.size(), 0U);
3520 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3521
3522 // Two-block message.
3523 string message = "12345678901234567890123456789012";
3524 string ciphertext1 = EncryptMessage(message, params);
3525 EXPECT_EQ(message.size(), ciphertext1.size());
3526
3527 string ciphertext2 = EncryptMessage(string(message), params);
3528 EXPECT_EQ(message.size(), ciphertext2.size());
3529
3530 // ECB is deterministic.
3531 EXPECT_EQ(ciphertext1, ciphertext2);
3532
3533 string plaintext = DecryptMessage(ciphertext1, params);
3534 EXPECT_EQ(message, plaintext);
3535}
3536
3537/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003538 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07003539 *
3540 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
3541 */
3542TEST_P(EncryptionOperationsTest, AesWrongMode) {
3543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3544 .Authorization(TAG_NO_AUTH_REQUIRED)
3545 .AesEncryptionKey(128)
3546 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3547 .Padding(PaddingMode::NONE)));
3548
3549 ASSERT_GT(key_blob_.size(), 0U);
3550
3551 // Two-block message.
3552 string message = "12345678901234567890123456789012";
3553 EXPECT_EQ(
3554 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
3555 Begin(KeyPurpose::ENCRYPT,
3556 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
3557}
3558
3559/*
3560 * EncryptionOperationsTest.AesWrongPurpose
3561 *
3562 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
3563 * specified.
3564 */
3565TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
3566 auto err = GenerateKey(AuthorizationSetBuilder()
3567 .Authorization(TAG_NO_AUTH_REQUIRED)
3568 .AesKey(128)
3569 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
3570 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3571 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3572 .Padding(PaddingMode::NONE));
3573 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
3574 ASSERT_GT(key_blob_.size(), 0U);
3575
3576 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3577 .BlockMode(BlockMode::GCM)
3578 .Padding(PaddingMode::NONE)
3579 .Authorization(TAG_MAC_LENGTH, 128));
3580 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3581
3582 CheckedDeleteKey();
3583
3584 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3585 .Authorization(TAG_NO_AUTH_REQUIRED)
3586 .AesKey(128)
3587 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
3588 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3589 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3590 .Padding(PaddingMode::NONE)));
3591
3592 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3593 .BlockMode(BlockMode::GCM)
3594 .Padding(PaddingMode::NONE)
3595 .Authorization(TAG_MAC_LENGTH, 128));
3596 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3597}
3598
3599/*
3600 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
3601 *
3602 * Verifies that AES encryption fails in the correct way when provided an input that is not a
3603 * multiple of the block size and no padding is specified.
3604 */
3605TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
3606 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3607 .Authorization(TAG_NO_AUTH_REQUIRED)
3608 .AesEncryptionKey(128)
3609 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3610 .Padding(PaddingMode::NONE)));
3611 // Message is slightly shorter than two blocks.
3612 string message(16 * 2 - 1, 'a');
3613
3614 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3615 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3616 string ciphertext;
3617 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
3618 EXPECT_EQ(0U, ciphertext.size());
3619}
3620
3621/*
3622 * EncryptionOperationsTest.AesEcbPkcs7Padding
3623 *
3624 * Verifies that AES PKCS7 padding works for any message length.
3625 */
3626TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
3627 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3628 .Authorization(TAG_NO_AUTH_REQUIRED)
3629 .AesEncryptionKey(128)
3630 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3631 .Padding(PaddingMode::PKCS7)));
3632
3633 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3634
3635 // Try various message lengths; all should work.
3636 for (size_t i = 0; i < 32; ++i) {
3637 string message(i, 'a');
3638 string ciphertext = EncryptMessage(message, params);
3639 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
3640 string plaintext = DecryptMessage(ciphertext, params);
3641 EXPECT_EQ(message, plaintext);
3642 }
3643}
3644
3645/*
3646 * EncryptionOperationsTest.AesEcbWrongPadding
3647 *
3648 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
3649 * specified.
3650 */
3651TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
3652 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3653 .Authorization(TAG_NO_AUTH_REQUIRED)
3654 .AesEncryptionKey(128)
3655 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3656 .Padding(PaddingMode::NONE)));
3657
3658 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3659
3660 // Try various message lengths; all should fail
3661 for (size_t i = 0; i < 32; ++i) {
3662 string message(i, 'a');
3663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3664 }
3665}
3666
3667/*
3668 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
3669 *
3670 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
3671 */
3672TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
3673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3674 .Authorization(TAG_NO_AUTH_REQUIRED)
3675 .AesEncryptionKey(128)
3676 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3677 .Padding(PaddingMode::PKCS7)));
3678
3679 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3680
3681 string message = "a";
3682 string ciphertext = EncryptMessage(message, params);
3683 EXPECT_EQ(16U, ciphertext.size());
3684 EXPECT_NE(ciphertext, message);
3685 ++ciphertext[ciphertext.size() / 2];
3686
3687 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3688 string plaintext;
3689 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3690}
3691
3692vector<uint8_t> CopyIv(const AuthorizationSet& set) {
3693 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003694 EXPECT_TRUE(iv);
3695 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07003696}
3697
3698/*
3699 * EncryptionOperationsTest.AesCtrRoundTripSuccess
3700 *
3701 * Verifies that AES CTR mode works.
3702 */
3703TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3705 .Authorization(TAG_NO_AUTH_REQUIRED)
3706 .AesEncryptionKey(128)
3707 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3708 .Padding(PaddingMode::NONE)));
3709
3710 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3711
3712 string message = "123";
3713 AuthorizationSet out_params;
3714 string ciphertext1 = EncryptMessage(message, params, &out_params);
3715 vector<uint8_t> iv1 = CopyIv(out_params);
3716 EXPECT_EQ(16U, iv1.size());
3717
3718 EXPECT_EQ(message.size(), ciphertext1.size());
3719
3720 out_params.Clear();
3721 string ciphertext2 = EncryptMessage(message, params, &out_params);
3722 vector<uint8_t> iv2 = CopyIv(out_params);
3723 EXPECT_EQ(16U, iv2.size());
3724
3725 // IVs should be random, so ciphertexts should differ.
3726 EXPECT_NE(ciphertext1, ciphertext2);
3727
3728 auto params_iv1 =
3729 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3730 auto params_iv2 =
3731 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3732
3733 string plaintext = DecryptMessage(ciphertext1, params_iv1);
3734 EXPECT_EQ(message, plaintext);
3735 plaintext = DecryptMessage(ciphertext2, params_iv2);
3736 EXPECT_EQ(message, plaintext);
3737
3738 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3739 plaintext = DecryptMessage(ciphertext1, params_iv2);
3740 EXPECT_NE(message, plaintext);
3741 plaintext = DecryptMessage(ciphertext2, params_iv1);
3742 EXPECT_NE(message, plaintext);
3743}
3744
3745/*
3746 * EncryptionOperationsTest.AesIncremental
3747 *
3748 * Verifies that AES works, all modes, when provided data in various size increments.
3749 */
3750TEST_P(EncryptionOperationsTest, AesIncremental) {
3751 auto block_modes = {
3752 BlockMode::ECB,
3753 BlockMode::CBC,
3754 BlockMode::CTR,
3755 BlockMode::GCM,
3756 };
3757
3758 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3759 .Authorization(TAG_NO_AUTH_REQUIRED)
3760 .AesEncryptionKey(128)
3761 .BlockMode(block_modes)
3762 .Padding(PaddingMode::NONE)
3763 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3764
3765 for (int increment = 1; increment <= 240; ++increment) {
3766 for (auto block_mode : block_modes) {
3767 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07003768 auto params =
3769 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
3770 if (block_mode == BlockMode::GCM) {
3771 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3772 }
Selene Huang31ab4042020-04-29 04:22:39 -07003773
3774 AuthorizationSet output_params;
3775 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3776
3777 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07003778 string to_send;
3779 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003780 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003781 }
Shawn Willden92d79c02021-02-19 07:31:55 -07003782 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
3783 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07003784
3785 switch (block_mode) {
3786 case BlockMode::GCM:
3787 EXPECT_EQ(message.size() + 16, ciphertext.size());
3788 break;
3789 case BlockMode::CTR:
3790 EXPECT_EQ(message.size(), ciphertext.size());
3791 break;
3792 case BlockMode::CBC:
3793 case BlockMode::ECB:
3794 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3795 break;
3796 }
3797
3798 auto iv = output_params.GetTagValue(TAG_NONCE);
3799 switch (block_mode) {
3800 case BlockMode::CBC:
3801 case BlockMode::GCM:
3802 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003803 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
3804 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
3805 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003806 break;
3807
3808 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003809 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07003810 break;
3811 }
3812
3813 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3814 << "Decrypt begin() failed for block mode " << block_mode;
3815
3816 string plaintext;
3817 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003818 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003819 }
3820 ErrorCode error = Finish(to_send, &plaintext);
3821 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
3822 << " and increment " << increment;
3823 if (error == ErrorCode::OK) {
3824 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3825 << block_mode << " and increment " << increment;
3826 }
3827 }
3828 }
3829}
3830
3831struct AesCtrSp80038aTestVector {
3832 const char* key;
3833 const char* nonce;
3834 const char* plaintext;
3835 const char* ciphertext;
3836};
3837
3838// These test vectors are taken from
3839// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3840static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3841 // AES-128
3842 {
3843 "2b7e151628aed2a6abf7158809cf4f3c",
3844 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3845 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3846 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3847 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3848 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3849 },
3850 // AES-192
3851 {
3852 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
3853 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3854 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3855 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3856 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3857 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3858 },
3859 // AES-256
3860 {
3861 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3862 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3863 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3864 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3865 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3866 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3867 },
3868};
3869
3870/*
3871 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3872 *
3873 * Verifies AES CTR implementation against SP800-38A test vectors.
3874 */
3875TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3876 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3877 for (size_t i = 0; i < 3; i++) {
3878 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3879 const string key = hex2str(test.key);
3880 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3881 InvalidSizes.end())
3882 continue;
3883 const string nonce = hex2str(test.nonce);
3884 const string plaintext = hex2str(test.plaintext);
3885 const string ciphertext = hex2str(test.ciphertext);
3886 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3887 }
3888}
3889
3890/*
3891 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3892 *
3893 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
3894 */
3895TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3896 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3897 .Authorization(TAG_NO_AUTH_REQUIRED)
3898 .AesEncryptionKey(128)
3899 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3900 .Padding(PaddingMode::PKCS7)));
3901 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3902 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3903}
3904
3905/*
3906 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3907 *
3908 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3909 */
3910TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3911 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3912 .Authorization(TAG_NO_AUTH_REQUIRED)
3913 .AesEncryptionKey(128)
3914 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3915 .Authorization(TAG_CALLER_NONCE)
3916 .Padding(PaddingMode::NONE)));
3917
3918 auto params = AuthorizationSetBuilder()
3919 .BlockMode(BlockMode::CTR)
3920 .Padding(PaddingMode::NONE)
3921 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
3922 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3923
3924 params = AuthorizationSetBuilder()
3925 .BlockMode(BlockMode::CTR)
3926 .Padding(PaddingMode::NONE)
3927 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
3928 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3929
3930 params = AuthorizationSetBuilder()
3931 .BlockMode(BlockMode::CTR)
3932 .Padding(PaddingMode::NONE)
3933 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
3934 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3935}
3936
3937/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003938 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003939 *
3940 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3941 */
3942TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3943 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3944 .Authorization(TAG_NO_AUTH_REQUIRED)
3945 .AesEncryptionKey(128)
3946 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3947 .Padding(PaddingMode::NONE)));
3948 // Two-block message.
3949 string message = "12345678901234567890123456789012";
3950 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3951 AuthorizationSet out_params;
3952 string ciphertext1 = EncryptMessage(message, params, &out_params);
3953 vector<uint8_t> iv1 = CopyIv(out_params);
3954 EXPECT_EQ(message.size(), ciphertext1.size());
3955
3956 out_params.Clear();
3957
3958 string ciphertext2 = EncryptMessage(message, params, &out_params);
3959 vector<uint8_t> iv2 = CopyIv(out_params);
3960 EXPECT_EQ(message.size(), ciphertext2.size());
3961
3962 // IVs should be random, so ciphertexts should differ.
3963 EXPECT_NE(ciphertext1, ciphertext2);
3964
3965 params.push_back(TAG_NONCE, iv1);
3966 string plaintext = DecryptMessage(ciphertext1, params);
3967 EXPECT_EQ(message, plaintext);
3968}
3969
3970/*
3971 * EncryptionOperationsTest.AesCallerNonce
3972 *
3973 * Verifies that AES caller-provided nonces work correctly.
3974 */
3975TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3977 .Authorization(TAG_NO_AUTH_REQUIRED)
3978 .AesEncryptionKey(128)
3979 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3980 .Authorization(TAG_CALLER_NONCE)
3981 .Padding(PaddingMode::NONE)));
3982
3983 string message = "12345678901234567890123456789012";
3984
3985 // Don't specify nonce, should get a random one.
3986 AuthorizationSetBuilder params =
3987 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3988 AuthorizationSet out_params;
3989 string ciphertext = EncryptMessage(message, params, &out_params);
3990 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003991 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003992
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003993 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003994 string plaintext = DecryptMessage(ciphertext, params);
3995 EXPECT_EQ(message, plaintext);
3996
3997 // Now specify a nonce, should also work.
3998 params = AuthorizationSetBuilder()
3999 .BlockMode(BlockMode::CBC)
4000 .Padding(PaddingMode::NONE)
4001 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4002 out_params.Clear();
4003 ciphertext = EncryptMessage(message, params, &out_params);
4004
4005 // Decrypt with correct nonce.
4006 plaintext = DecryptMessage(ciphertext, params);
4007 EXPECT_EQ(message, plaintext);
4008
4009 // Try with wrong nonce.
4010 params = AuthorizationSetBuilder()
4011 .BlockMode(BlockMode::CBC)
4012 .Padding(PaddingMode::NONE)
4013 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4014 plaintext = DecryptMessage(ciphertext, params);
4015 EXPECT_NE(message, plaintext);
4016}
4017
4018/*
4019 * EncryptionOperationsTest.AesCallerNonceProhibited
4020 *
4021 * Verifies that caller-provided nonces are not permitted when not specified in the key
4022 * authorizations.
4023 */
4024TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4025 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4026 .Authorization(TAG_NO_AUTH_REQUIRED)
4027 .AesEncryptionKey(128)
4028 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4029 .Padding(PaddingMode::NONE)));
4030
4031 string message = "12345678901234567890123456789012";
4032
4033 // Don't specify nonce, should get a random one.
4034 AuthorizationSetBuilder params =
4035 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4036 AuthorizationSet out_params;
4037 string ciphertext = EncryptMessage(message, params, &out_params);
4038 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004039 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004040
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004041 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004042 string plaintext = DecryptMessage(ciphertext, params);
4043 EXPECT_EQ(message, plaintext);
4044
4045 // Now specify a nonce, should fail
4046 params = AuthorizationSetBuilder()
4047 .BlockMode(BlockMode::CBC)
4048 .Padding(PaddingMode::NONE)
4049 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4050 out_params.Clear();
4051 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4052}
4053
4054/*
4055 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4056 *
4057 * Verifies that AES GCM mode works.
4058 */
4059TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4060 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4061 .Authorization(TAG_NO_AUTH_REQUIRED)
4062 .AesEncryptionKey(128)
4063 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4064 .Padding(PaddingMode::NONE)
4065 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4066
4067 string aad = "foobar";
4068 string message = "123456789012345678901234567890123456";
4069
4070 auto begin_params = AuthorizationSetBuilder()
4071 .BlockMode(BlockMode::GCM)
4072 .Padding(PaddingMode::NONE)
4073 .Authorization(TAG_MAC_LENGTH, 128);
4074
Selene Huang31ab4042020-04-29 04:22:39 -07004075 // Encrypt
4076 AuthorizationSet begin_out_params;
4077 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4078 << "Begin encrypt";
4079 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004080 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4081 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004082 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4083
4084 // Grab nonce
4085 begin_params.push_back(begin_out_params);
4086
4087 // Decrypt.
4088 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004089 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004090 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004091 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004092 EXPECT_EQ(message.length(), plaintext.length());
4093 EXPECT_EQ(message, plaintext);
4094}
4095
4096/*
4097 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4098 *
4099 * Verifies that AES GCM mode works, even when there's a long delay
4100 * between operations.
4101 */
4102TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4104 .Authorization(TAG_NO_AUTH_REQUIRED)
4105 .AesEncryptionKey(128)
4106 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4107 .Padding(PaddingMode::NONE)
4108 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4109
4110 string aad = "foobar";
4111 string message = "123456789012345678901234567890123456";
4112
4113 auto begin_params = AuthorizationSetBuilder()
4114 .BlockMode(BlockMode::GCM)
4115 .Padding(PaddingMode::NONE)
4116 .Authorization(TAG_MAC_LENGTH, 128);
4117
Selene Huang31ab4042020-04-29 04:22:39 -07004118 // Encrypt
4119 AuthorizationSet begin_out_params;
4120 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4121 << "Begin encrypt";
4122 string ciphertext;
4123 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004124 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004125 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004126 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004127
4128 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4129
4130 // Grab nonce
4131 begin_params.push_back(begin_out_params);
4132
4133 // Decrypt.
4134 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4135 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004136 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004137 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004138 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004139 sleep(5);
4140 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4141 EXPECT_EQ(message.length(), plaintext.length());
4142 EXPECT_EQ(message, plaintext);
4143}
4144
4145/*
4146 * EncryptionOperationsTest.AesGcmDifferentNonces
4147 *
4148 * Verifies that encrypting the same data with different nonces produces different outputs.
4149 */
4150TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4152 .Authorization(TAG_NO_AUTH_REQUIRED)
4153 .AesEncryptionKey(128)
4154 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4155 .Padding(PaddingMode::NONE)
4156 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4157 .Authorization(TAG_CALLER_NONCE)));
4158
4159 string aad = "foobar";
4160 string message = "123456789012345678901234567890123456";
4161 string nonce1 = "000000000000";
4162 string nonce2 = "111111111111";
4163 string nonce3 = "222222222222";
4164
4165 string ciphertext1 =
4166 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4167 string ciphertext2 =
4168 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4169 string ciphertext3 =
4170 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4171
4172 ASSERT_NE(ciphertext1, ciphertext2);
4173 ASSERT_NE(ciphertext1, ciphertext3);
4174 ASSERT_NE(ciphertext2, ciphertext3);
4175}
4176
4177/*
4178 * EncryptionOperationsTest.AesGcmTooShortTag
4179 *
4180 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4181 */
4182TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4183 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4184 .Authorization(TAG_NO_AUTH_REQUIRED)
4185 .AesEncryptionKey(128)
4186 .BlockMode(BlockMode::GCM)
4187 .Padding(PaddingMode::NONE)
4188 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4189 string message = "123456789012345678901234567890123456";
4190 auto params = AuthorizationSetBuilder()
4191 .BlockMode(BlockMode::GCM)
4192 .Padding(PaddingMode::NONE)
4193 .Authorization(TAG_MAC_LENGTH, 96);
4194
4195 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4196}
4197
4198/*
4199 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4200 *
4201 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4202 */
4203TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4204 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4205 .Authorization(TAG_NO_AUTH_REQUIRED)
4206 .AesEncryptionKey(128)
4207 .BlockMode(BlockMode::GCM)
4208 .Padding(PaddingMode::NONE)
4209 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4210 string aad = "foobar";
4211 string message = "123456789012345678901234567890123456";
4212 auto params = AuthorizationSetBuilder()
4213 .BlockMode(BlockMode::GCM)
4214 .Padding(PaddingMode::NONE)
4215 .Authorization(TAG_MAC_LENGTH, 128);
4216
Selene Huang31ab4042020-04-29 04:22:39 -07004217 // Encrypt
4218 AuthorizationSet begin_out_params;
4219 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4220 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004221 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004222
4223 AuthorizationSet finish_out_params;
4224 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004225 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4226 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004227
4228 params = AuthorizationSetBuilder()
4229 .Authorizations(begin_out_params)
4230 .BlockMode(BlockMode::GCM)
4231 .Padding(PaddingMode::NONE)
4232 .Authorization(TAG_MAC_LENGTH, 96);
4233
4234 // Decrypt.
4235 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4236}
4237
4238/*
4239 * EncryptionOperationsTest.AesGcmCorruptKey
4240 *
4241 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4242 */
4243TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4244 const uint8_t nonce_bytes[] = {
4245 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4246 };
4247 string nonce = make_string(nonce_bytes);
4248 const uint8_t ciphertext_bytes[] = {
4249 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4250 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4251 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4252 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4253 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4254 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4255 };
4256 string ciphertext = make_string(ciphertext_bytes);
4257
4258 auto params = AuthorizationSetBuilder()
4259 .BlockMode(BlockMode::GCM)
4260 .Padding(PaddingMode::NONE)
4261 .Authorization(TAG_MAC_LENGTH, 128)
4262 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4263
4264 auto import_params = AuthorizationSetBuilder()
4265 .Authorization(TAG_NO_AUTH_REQUIRED)
4266 .AesEncryptionKey(128)
4267 .BlockMode(BlockMode::GCM)
4268 .Padding(PaddingMode::NONE)
4269 .Authorization(TAG_CALLER_NONCE)
4270 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4271
4272 // Import correct key and decrypt
4273 const uint8_t key_bytes[] = {
4274 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4275 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4276 };
4277 string key = make_string(key_bytes);
4278 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4279 string plaintext = DecryptMessage(ciphertext, params);
4280 CheckedDeleteKey();
4281
4282 // Corrupt key and attempt to decrypt
4283 key[0] = 0;
4284 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4285 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4286 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
4287 CheckedDeleteKey();
4288}
4289
4290/*
4291 * EncryptionOperationsTest.AesGcmAadNoData
4292 *
4293 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
4294 * encrypt.
4295 */
4296TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
4297 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4298 .Authorization(TAG_NO_AUTH_REQUIRED)
4299 .AesEncryptionKey(128)
4300 .BlockMode(BlockMode::GCM)
4301 .Padding(PaddingMode::NONE)
4302 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4303
4304 string aad = "1234567890123456";
4305 auto params = AuthorizationSetBuilder()
4306 .BlockMode(BlockMode::GCM)
4307 .Padding(PaddingMode::NONE)
4308 .Authorization(TAG_MAC_LENGTH, 128);
4309
Selene Huang31ab4042020-04-29 04:22:39 -07004310 // Encrypt
4311 AuthorizationSet begin_out_params;
4312 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4313 string ciphertext;
4314 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004315 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4316 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004317 EXPECT_TRUE(finish_out_params.empty());
4318
4319 // Grab nonce
4320 params.push_back(begin_out_params);
4321
4322 // Decrypt.
4323 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004324 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004325 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004326 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004327
4328 EXPECT_TRUE(finish_out_params.empty());
4329
4330 EXPECT_EQ("", plaintext);
4331}
4332
4333/*
4334 * EncryptionOperationsTest.AesGcmMultiPartAad
4335 *
4336 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
4337 * chunks.
4338 */
4339TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
4340 const size_t tag_bits = 128;
4341 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4342 .Authorization(TAG_NO_AUTH_REQUIRED)
4343 .AesEncryptionKey(128)
4344 .BlockMode(BlockMode::GCM)
4345 .Padding(PaddingMode::NONE)
4346 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4347
4348 string message = "123456789012345678901234567890123456";
4349 auto begin_params = AuthorizationSetBuilder()
4350 .BlockMode(BlockMode::GCM)
4351 .Padding(PaddingMode::NONE)
4352 .Authorization(TAG_MAC_LENGTH, tag_bits);
4353 AuthorizationSet begin_out_params;
4354
Selene Huang31ab4042020-04-29 04:22:39 -07004355 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4356
4357 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07004358 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
4359 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004360 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004361 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4362 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004363
Selene Huang31ab4042020-04-29 04:22:39 -07004364 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07004365 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004366
4367 // Grab nonce.
4368 begin_params.push_back(begin_out_params);
4369
4370 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004371 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004372 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004373 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004374 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004375 EXPECT_EQ(message, plaintext);
4376}
4377
4378/*
4379 * EncryptionOperationsTest.AesGcmAadOutOfOrder
4380 *
4381 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
4382 */
4383TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
4384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4385 .Authorization(TAG_NO_AUTH_REQUIRED)
4386 .AesEncryptionKey(128)
4387 .BlockMode(BlockMode::GCM)
4388 .Padding(PaddingMode::NONE)
4389 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4390
4391 string message = "123456789012345678901234567890123456";
4392 auto begin_params = AuthorizationSetBuilder()
4393 .BlockMode(BlockMode::GCM)
4394 .Padding(PaddingMode::NONE)
4395 .Authorization(TAG_MAC_LENGTH, 128);
4396 AuthorizationSet begin_out_params;
4397
Selene Huang31ab4042020-04-29 04:22:39 -07004398 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4399
Shawn Willden92d79c02021-02-19 07:31:55 -07004400 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004401 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004402 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4403 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004404
Shawn Willden92d79c02021-02-19 07:31:55 -07004405 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07004406}
4407
4408/*
4409 * EncryptionOperationsTest.AesGcmBadAad
4410 *
4411 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
4412 */
4413TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
4414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4415 .Authorization(TAG_NO_AUTH_REQUIRED)
4416 .AesEncryptionKey(128)
4417 .BlockMode(BlockMode::GCM)
4418 .Padding(PaddingMode::NONE)
4419 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4420
4421 string message = "12345678901234567890123456789012";
4422 auto begin_params = AuthorizationSetBuilder()
4423 .BlockMode(BlockMode::GCM)
4424 .Padding(PaddingMode::NONE)
4425 .Authorization(TAG_MAC_LENGTH, 128);
4426
Selene Huang31ab4042020-04-29 04:22:39 -07004427 // Encrypt
4428 AuthorizationSet begin_out_params;
4429 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004430 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004431 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004432 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004433
4434 // Grab nonce
4435 begin_params.push_back(begin_out_params);
4436
Selene Huang31ab4042020-04-29 04:22:39 -07004437 // Decrypt.
4438 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004439 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004440 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004441 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004442}
4443
4444/*
4445 * EncryptionOperationsTest.AesGcmWrongNonce
4446 *
4447 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
4448 */
4449TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
4450 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4451 .Authorization(TAG_NO_AUTH_REQUIRED)
4452 .AesEncryptionKey(128)
4453 .BlockMode(BlockMode::GCM)
4454 .Padding(PaddingMode::NONE)
4455 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4456
4457 string message = "12345678901234567890123456789012";
4458 auto begin_params = AuthorizationSetBuilder()
4459 .BlockMode(BlockMode::GCM)
4460 .Padding(PaddingMode::NONE)
4461 .Authorization(TAG_MAC_LENGTH, 128);
4462
Selene Huang31ab4042020-04-29 04:22:39 -07004463 // Encrypt
4464 AuthorizationSet begin_out_params;
4465 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004466 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004467 string ciphertext;
4468 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004469 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004470
4471 // Wrong nonce
4472 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
4473
4474 // Decrypt.
4475 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004476 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004477 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004478 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004479
4480 // With wrong nonce, should have gotten garbage plaintext (or none).
4481 EXPECT_NE(message, plaintext);
4482}
4483
4484/*
4485 * EncryptionOperationsTest.AesGcmCorruptTag
4486 *
4487 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
4488 */
4489TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
4490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4491 .Authorization(TAG_NO_AUTH_REQUIRED)
4492 .AesEncryptionKey(128)
4493 .BlockMode(BlockMode::GCM)
4494 .Padding(PaddingMode::NONE)
4495 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4496
4497 string aad = "1234567890123456";
4498 string message = "123456789012345678901234567890123456";
4499
4500 auto params = AuthorizationSetBuilder()
4501 .BlockMode(BlockMode::GCM)
4502 .Padding(PaddingMode::NONE)
4503 .Authorization(TAG_MAC_LENGTH, 128);
4504
Selene Huang31ab4042020-04-29 04:22:39 -07004505 // Encrypt
4506 AuthorizationSet begin_out_params;
4507 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004508 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004509 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004510 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004511
4512 // Corrupt tag
4513 ++(*ciphertext.rbegin());
4514
4515 // Grab nonce
4516 params.push_back(begin_out_params);
4517
4518 // Decrypt.
4519 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004520 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004521 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004522 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004523}
4524
4525/*
4526 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
4527 *
4528 * Verifies that 3DES is basically functional.
4529 */
4530TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
4531 auto auths = AuthorizationSetBuilder()
4532 .TripleDesEncryptionKey(168)
4533 .BlockMode(BlockMode::ECB)
4534 .Authorization(TAG_NO_AUTH_REQUIRED)
4535 .Padding(PaddingMode::NONE);
4536
4537 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
4538 // Two-block message.
4539 string message = "1234567890123456";
4540 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4541 string ciphertext1 = EncryptMessage(message, inParams);
4542 EXPECT_EQ(message.size(), ciphertext1.size());
4543
4544 string ciphertext2 = EncryptMessage(string(message), inParams);
4545 EXPECT_EQ(message.size(), ciphertext2.size());
4546
4547 // ECB is deterministic.
4548 EXPECT_EQ(ciphertext1, ciphertext2);
4549
4550 string plaintext = DecryptMessage(ciphertext1, inParams);
4551 EXPECT_EQ(message, plaintext);
4552}
4553
4554/*
4555 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
4556 *
4557 * Verifies that CBC keys reject ECB usage.
4558 */
4559TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
4560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4561 .TripleDesEncryptionKey(168)
4562 .BlockMode(BlockMode::CBC)
4563 .Authorization(TAG_NO_AUTH_REQUIRED)
4564 .Padding(PaddingMode::NONE)));
4565
4566 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4567 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4568}
4569
4570/*
4571 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
4572 *
4573 * Tests ECB mode with PKCS#7 padding, various message sizes.
4574 */
4575TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
4576 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4577 .TripleDesEncryptionKey(168)
4578 .BlockMode(BlockMode::ECB)
4579 .Authorization(TAG_NO_AUTH_REQUIRED)
4580 .Padding(PaddingMode::PKCS7)));
4581
4582 for (size_t i = 0; i < 32; ++i) {
4583 string message(i, 'a');
4584 auto inParams =
4585 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4586 string ciphertext = EncryptMessage(message, inParams);
4587 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4588 string plaintext = DecryptMessage(ciphertext, inParams);
4589 EXPECT_EQ(message, plaintext);
4590 }
4591}
4592
4593/*
4594 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
4595 *
4596 * Verifies that keys configured for no padding reject PKCS7 padding
4597 */
4598TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
4599 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4600 .TripleDesEncryptionKey(168)
4601 .BlockMode(BlockMode::ECB)
4602 .Authorization(TAG_NO_AUTH_REQUIRED)
4603 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00004604 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4605 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07004606}
4607
4608/*
4609 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
4610 *
4611 * Verifies that corrupted padding is detected.
4612 */
4613TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
4614 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4615 .TripleDesEncryptionKey(168)
4616 .BlockMode(BlockMode::ECB)
4617 .Authorization(TAG_NO_AUTH_REQUIRED)
4618 .Padding(PaddingMode::PKCS7)));
4619
4620 string message = "a";
4621 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
4622 EXPECT_EQ(8U, ciphertext.size());
4623 EXPECT_NE(ciphertext, message);
4624 ++ciphertext[ciphertext.size() / 2];
4625
4626 AuthorizationSetBuilder begin_params;
4627 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
4628 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
4629 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4630 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004631 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004632 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4633}
4634
4635struct TripleDesTestVector {
4636 const char* name;
4637 const KeyPurpose purpose;
4638 const BlockMode block_mode;
4639 const PaddingMode padding_mode;
4640 const char* key;
4641 const char* iv;
4642 const char* input;
4643 const char* output;
4644};
4645
4646// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
4647// of the NIST vectors are multiples of the block size.
4648static const TripleDesTestVector kTripleDesTestVectors[] = {
4649 {
4650 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4651 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
4652 "", // IV
4653 "329d86bdf1bc5af4", // input
4654 "d946c2756d78633f", // output
4655 },
4656 {
4657 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4658 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
4659 "", // IV
4660 "6b1540781b01ce1997adae102dbf3c5b", // input
4661 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
4662 },
4663 {
4664 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4665 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
4666 "", // IV
4667 "6daad94ce08acfe7", // input
4668 "660e7d32dcc90e79", // output
4669 },
4670 {
4671 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4672 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
4673 "", // IV
4674 "e9653a0a1f05d31b9acd12d73aa9879d", // input
4675 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
4676 },
4677 {
4678 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4679 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
4680 "43f791134c5647ba", // IV
4681 "dcc153cef81d6f24", // input
4682 "92538bd8af18d3ba", // output
4683 },
4684 {
4685 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4686 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4687 "c2e999cb6249023c", // IV
4688 "c689aee38a301bb316da75db36f110b5", // input
4689 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
4690 },
4691 {
4692 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
4693 PaddingMode::PKCS7,
4694 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4695 "c2e999cb6249023c", // IV
4696 "c689aee38a301bb316da75db36f110b500", // input
4697 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
4698 },
4699 {
4700 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
4701 PaddingMode::PKCS7,
4702 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4703 "c2e999cb6249023c", // IV
4704 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
4705 "c689aee38a301bb316da75db36f110b500", // output
4706 },
4707 {
4708 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4709 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
4710 "41746c7e442d3681", // IV
4711 "c53a7b0ec40600fe", // input
4712 "d4f00eb455de1034", // output
4713 },
4714 {
4715 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4716 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
4717 "3982bc02c3727d45", // IV
4718 "6006f10adef52991fcc777a1238bbb65", // input
4719 "edae09288e9e3bc05746d872b48e3b29", // output
4720 },
4721};
4722
4723/*
4724 * EncryptionOperationsTest.TripleDesTestVector
4725 *
4726 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
4727 */
4728TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
4729 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
4730 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
4731 SCOPED_TRACE(test->name);
4732 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
4733 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
4734 hex2str(test->output));
4735 }
4736}
4737
4738/*
4739 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
4740 *
4741 * Validates CBC mode functionality.
4742 */
4743TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
4744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4745 .TripleDesEncryptionKey(168)
4746 .BlockMode(BlockMode::CBC)
4747 .Authorization(TAG_NO_AUTH_REQUIRED)
4748 .Padding(PaddingMode::NONE)));
4749
4750 ASSERT_GT(key_blob_.size(), 0U);
4751
4752 // Two-block message.
4753 string message = "1234567890123456";
4754 vector<uint8_t> iv1;
4755 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
4756 EXPECT_EQ(message.size(), ciphertext1.size());
4757
4758 vector<uint8_t> iv2;
4759 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
4760 EXPECT_EQ(message.size(), ciphertext2.size());
4761
4762 // IVs should be random, so ciphertexts should differ.
4763 EXPECT_NE(iv1, iv2);
4764 EXPECT_NE(ciphertext1, ciphertext2);
4765
4766 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
4767 EXPECT_EQ(message, plaintext);
4768}
4769
4770/*
4771 * EncryptionOperationsTest.TripleDesCallerIv
4772 *
4773 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
4774 */
4775TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
4776 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4777 .TripleDesEncryptionKey(168)
4778 .BlockMode(BlockMode::CBC)
4779 .Authorization(TAG_NO_AUTH_REQUIRED)
4780 .Authorization(TAG_CALLER_NONCE)
4781 .Padding(PaddingMode::NONE)));
4782 string message = "1234567890123456";
4783 vector<uint8_t> iv;
4784 // Don't specify IV, should get a random one.
4785 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4786 EXPECT_EQ(message.size(), ciphertext1.size());
4787 EXPECT_EQ(8U, iv.size());
4788
4789 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4790 EXPECT_EQ(message, plaintext);
4791
4792 // Now specify an IV, should also work.
4793 iv = AidlBuf("abcdefgh");
4794 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
4795
4796 // Decrypt with correct IV.
4797 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
4798 EXPECT_EQ(message, plaintext);
4799
4800 // Now try with wrong IV.
4801 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
4802 EXPECT_NE(message, plaintext);
4803}
4804
4805/*
4806 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
4807 *
4808 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
4809 */
4810TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
4811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4812 .TripleDesEncryptionKey(168)
4813 .BlockMode(BlockMode::CBC)
4814 .Authorization(TAG_NO_AUTH_REQUIRED)
4815 .Padding(PaddingMode::NONE)));
4816
4817 string message = "12345678901234567890123456789012";
4818 vector<uint8_t> iv;
4819 // Don't specify nonce, should get a random one.
4820 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4821 EXPECT_EQ(message.size(), ciphertext1.size());
4822 EXPECT_EQ(8U, iv.size());
4823
4824 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4825 EXPECT_EQ(message, plaintext);
4826
4827 // Now specify a nonce, should fail.
4828 auto input_params = AuthorizationSetBuilder()
4829 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
4830 .BlockMode(BlockMode::CBC)
4831 .Padding(PaddingMode::NONE);
4832 AuthorizationSet output_params;
4833 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
4834 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4835}
4836
4837/*
4838 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
4839 *
4840 * Verifies that 3DES ECB-only keys do not allow CBC usage.
4841 */
4842TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
4843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4844 .TripleDesEncryptionKey(168)
4845 .BlockMode(BlockMode::ECB)
4846 .Authorization(TAG_NO_AUTH_REQUIRED)
4847 .Padding(PaddingMode::NONE)));
4848 // Two-block message.
4849 string message = "1234567890123456";
4850 auto begin_params =
4851 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4852 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4853}
4854
4855/*
4856 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4857 *
4858 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4859 */
4860TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4862 .TripleDesEncryptionKey(168)
4863 .BlockMode(BlockMode::CBC)
4864 .Authorization(TAG_NO_AUTH_REQUIRED)
4865 .Padding(PaddingMode::NONE)));
4866 // Message is slightly shorter than two blocks.
4867 string message = "123456789012345";
4868
4869 auto begin_params =
4870 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4871 AuthorizationSet output_params;
4872 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4873 string ciphertext;
4874 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4875}
4876
4877/*
4878 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4879 *
4880 * Verifies that PKCS7 padding works correctly in CBC mode.
4881 */
4882TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4883 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4884 .TripleDesEncryptionKey(168)
4885 .BlockMode(BlockMode::CBC)
4886 .Authorization(TAG_NO_AUTH_REQUIRED)
4887 .Padding(PaddingMode::PKCS7)));
4888
4889 // Try various message lengths; all should work.
4890 for (size_t i = 0; i < 32; ++i) {
4891 string message(i, 'a');
4892 vector<uint8_t> iv;
4893 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4894 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4895 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4896 EXPECT_EQ(message, plaintext);
4897 }
4898}
4899
4900/*
4901 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4902 *
4903 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4904 */
4905TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4907 .TripleDesEncryptionKey(168)
4908 .BlockMode(BlockMode::CBC)
4909 .Authorization(TAG_NO_AUTH_REQUIRED)
4910 .Padding(PaddingMode::NONE)));
4911
4912 // Try various message lengths; all should fail.
4913 for (size_t i = 0; i < 32; ++i) {
4914 auto begin_params =
4915 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4916 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4917 }
4918}
4919
4920/*
4921 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4922 *
4923 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4924 */
4925TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4926 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4927 .TripleDesEncryptionKey(168)
4928 .BlockMode(BlockMode::CBC)
4929 .Authorization(TAG_NO_AUTH_REQUIRED)
4930 .Padding(PaddingMode::PKCS7)));
4931
4932 string message = "a";
4933 vector<uint8_t> iv;
4934 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4935 EXPECT_EQ(8U, ciphertext.size());
4936 EXPECT_NE(ciphertext, message);
4937 ++ciphertext[ciphertext.size() / 2];
4938
4939 auto begin_params = AuthorizationSetBuilder()
4940 .BlockMode(BlockMode::CBC)
4941 .Padding(PaddingMode::PKCS7)
4942 .Authorization(TAG_NONCE, iv);
4943 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4944 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004945 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004946 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4947}
4948
4949/*
4950 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4951 *
4952 * Verifies that 3DES CBC works with many different input sizes.
4953 */
4954TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4956 .TripleDesEncryptionKey(168)
4957 .BlockMode(BlockMode::CBC)
4958 .Authorization(TAG_NO_AUTH_REQUIRED)
4959 .Padding(PaddingMode::NONE)));
4960
4961 int increment = 7;
4962 string message(240, 'a');
4963 AuthorizationSet input_params =
4964 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4965 AuthorizationSet output_params;
4966 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4967
4968 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004969 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004970 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004971 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4972 EXPECT_EQ(message.size(), ciphertext.size());
4973
4974 // Move TAG_NONCE into input_params
4975 input_params = output_params;
4976 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4977 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4978 output_params.Clear();
4979
4980 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4981 string plaintext;
4982 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004983 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004984 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4985 EXPECT_EQ(ciphertext.size(), plaintext.size());
4986 EXPECT_EQ(message, plaintext);
4987}
4988
4989INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4990
4991typedef KeyMintAidlTestBase MaxOperationsTest;
4992
4993/*
4994 * MaxOperationsTest.TestLimitAes
4995 *
4996 * Verifies that the max uses per boot tag works correctly with AES keys.
4997 */
4998TEST_P(MaxOperationsTest, TestLimitAes) {
4999 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5000
5001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5002 .Authorization(TAG_NO_AUTH_REQUIRED)
5003 .AesEncryptionKey(128)
5004 .EcbMode()
5005 .Padding(PaddingMode::NONE)
5006 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5007
5008 string message = "1234567890123456";
5009
5010 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5011
5012 EncryptMessage(message, params);
5013 EncryptMessage(message, params);
5014 EncryptMessage(message, params);
5015
5016 // Fourth time should fail.
5017 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5018}
5019
5020/*
Qi Wud22ec842020-11-26 13:27:53 +08005021 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005022 *
5023 * Verifies that the max uses per boot tag works correctly with RSA keys.
5024 */
5025TEST_P(MaxOperationsTest, TestLimitRsa) {
5026 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5027
5028 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5029 .Authorization(TAG_NO_AUTH_REQUIRED)
5030 .RsaSigningKey(1024, 65537)
5031 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005032 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5033 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005034
5035 string message = "1234567890123456";
5036
5037 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5038
5039 SignMessage(message, params);
5040 SignMessage(message, params);
5041 SignMessage(message, params);
5042
5043 // Fourth time should fail.
5044 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5045}
5046
5047INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5048
Qi Wud22ec842020-11-26 13:27:53 +08005049typedef KeyMintAidlTestBase UsageCountLimitTest;
5050
5051/*
Qi Wubeefae42021-01-28 23:16:37 +08005052 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005053 *
Qi Wubeefae42021-01-28 23:16:37 +08005054 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005055 */
Qi Wubeefae42021-01-28 23:16:37 +08005056TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005057 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5058
5059 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5060 .Authorization(TAG_NO_AUTH_REQUIRED)
5061 .AesEncryptionKey(128)
5062 .EcbMode()
5063 .Padding(PaddingMode::NONE)
5064 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5065
5066 // Check the usage count limit tag appears in the authorizations.
5067 AuthorizationSet auths;
5068 for (auto& entry : key_characteristics_) {
5069 auths.push_back(AuthorizationSet(entry.authorizations));
5070 }
5071 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5072 << "key usage count limit " << 1U << " missing";
5073
5074 string message = "1234567890123456";
5075 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5076
Qi Wubeefae42021-01-28 23:16:37 +08005077 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5078 AuthorizationSet keystore_auths =
5079 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5080
Qi Wud22ec842020-11-26 13:27:53 +08005081 // First usage of AES key should work.
5082 EncryptMessage(message, params);
5083
Qi Wud22ec842020-11-26 13:27:53 +08005084 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5085 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5086 // must be invalidated from secure storage (such as RPMB partition).
5087 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5088 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005089 // Usage count limit tag is enforced by keystore, keymint does nothing.
5090 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5092 }
5093}
5094
5095/*
Qi Wubeefae42021-01-28 23:16:37 +08005096 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005097 *
Qi Wubeefae42021-01-28 23:16:37 +08005098 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005099 */
Qi Wubeefae42021-01-28 23:16:37 +08005100TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5101 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5102
5103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5104 .Authorization(TAG_NO_AUTH_REQUIRED)
5105 .AesEncryptionKey(128)
5106 .EcbMode()
5107 .Padding(PaddingMode::NONE)
5108 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5109
5110 // Check the usage count limit tag appears in the authorizations.
5111 AuthorizationSet auths;
5112 for (auto& entry : key_characteristics_) {
5113 auths.push_back(AuthorizationSet(entry.authorizations));
5114 }
5115 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5116 << "key usage count limit " << 3U << " missing";
5117
5118 string message = "1234567890123456";
5119 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5120
5121 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5122 AuthorizationSet keystore_auths =
5123 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5124
5125 EncryptMessage(message, params);
5126 EncryptMessage(message, params);
5127 EncryptMessage(message, params);
5128
5129 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5130 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5131 // must be invalidated from secure storage (such as RPMB partition).
5132 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5133 } else {
5134 // Usage count limit tag is enforced by keystore, keymint does nothing.
5135 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5136 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5137 }
5138}
5139
5140/*
5141 * UsageCountLimitTest.TestSingleUseRsa
5142 *
5143 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5144 */
5145TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005146 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5147
5148 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5149 .Authorization(TAG_NO_AUTH_REQUIRED)
5150 .RsaSigningKey(1024, 65537)
5151 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005152 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5153 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005154
5155 // Check the usage count limit tag appears in the authorizations.
5156 AuthorizationSet auths;
5157 for (auto& entry : key_characteristics_) {
5158 auths.push_back(AuthorizationSet(entry.authorizations));
5159 }
5160 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5161 << "key usage count limit " << 1U << " missing";
5162
5163 string message = "1234567890123456";
5164 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5165
Qi Wubeefae42021-01-28 23:16:37 +08005166 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5167 AuthorizationSet keystore_auths =
5168 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5169
Qi Wud22ec842020-11-26 13:27:53 +08005170 // First usage of RSA key should work.
5171 SignMessage(message, params);
5172
Qi Wud22ec842020-11-26 13:27:53 +08005173 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5174 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5175 // must be invalidated from secure storage (such as RPMB partition).
5176 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5177 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005178 // Usage count limit tag is enforced by keystore, keymint does nothing.
5179 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5180 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5181 }
5182}
5183
5184/*
5185 * UsageCountLimitTest.TestLimitUseRsa
5186 *
5187 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5188 */
5189TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5190 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5191
5192 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5193 .Authorization(TAG_NO_AUTH_REQUIRED)
5194 .RsaSigningKey(1024, 65537)
5195 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005196 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5197 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005198
5199 // Check the usage count limit tag appears in the authorizations.
5200 AuthorizationSet auths;
5201 for (auto& entry : key_characteristics_) {
5202 auths.push_back(AuthorizationSet(entry.authorizations));
5203 }
5204 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5205 << "key usage count limit " << 3U << " missing";
5206
5207 string message = "1234567890123456";
5208 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5209
5210 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5211 AuthorizationSet keystore_auths =
5212 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5213
5214 SignMessage(message, params);
5215 SignMessage(message, params);
5216 SignMessage(message, params);
5217
5218 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5219 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5220 // must be invalidated from secure storage (such as RPMB partition).
5221 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5222 } else {
5223 // Usage count limit tag is enforced by keystore, keymint does nothing.
5224 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005225 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5226 }
5227}
5228
Qi Wu8e727f72021-02-11 02:49:33 +08005229/*
5230 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5231 *
5232 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5233 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5234 * in hardware.
5235 */
5236TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5237 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5238
5239 auto error = GenerateKey(AuthorizationSetBuilder()
5240 .RsaSigningKey(2048, 65537)
5241 .Digest(Digest::NONE)
5242 .Padding(PaddingMode::NONE)
5243 .Authorization(TAG_NO_AUTH_REQUIRED)
5244 .Authorization(TAG_ROLLBACK_RESISTANCE)
5245 .SetDefaultValidity());
5246 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5247
5248 if (error == ErrorCode::OK) {
5249 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5250 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5251 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5252 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5253
5254 // The KeyMint should also enforce single use key in hardware when it supports rollback
5255 // resistance.
5256 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5257 .Authorization(TAG_NO_AUTH_REQUIRED)
5258 .RsaSigningKey(1024, 65537)
5259 .NoDigestOrPadding()
5260 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5261 .SetDefaultValidity()));
5262
5263 // Check the usage count limit tag appears in the hardware authorizations.
5264 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5265 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5266 << "key usage count limit " << 1U << " missing";
5267
5268 string message = "1234567890123456";
5269 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5270
5271 // First usage of RSA key should work.
5272 SignMessage(message, params);
5273
5274 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5275 // must be invalidated from secure storage (such as RPMB partition).
5276 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5277 }
5278}
5279
Qi Wud22ec842020-11-26 13:27:53 +08005280INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
5281
David Drysdale7de9feb2021-03-05 14:56:19 +00005282typedef KeyMintAidlTestBase GetHardwareInfoTest;
5283
5284TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
5285 // Retrieving hardware info should give the same result each time.
5286 KeyMintHardwareInfo info;
5287 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
5288 KeyMintHardwareInfo info2;
5289 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
5290 EXPECT_EQ(info, info2);
5291}
5292
5293INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
5294
Selene Huang31ab4042020-04-29 04:22:39 -07005295typedef KeyMintAidlTestBase AddEntropyTest;
5296
5297/*
5298 * AddEntropyTest.AddEntropy
5299 *
5300 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
5301 * is actually added.
5302 */
5303TEST_P(AddEntropyTest, AddEntropy) {
5304 string data = "foo";
5305 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
5306}
5307
5308/*
5309 * AddEntropyTest.AddEmptyEntropy
5310 *
5311 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
5312 */
5313TEST_P(AddEntropyTest, AddEmptyEntropy) {
5314 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
5315}
5316
5317/*
5318 * AddEntropyTest.AddLargeEntropy
5319 *
5320 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
5321 */
5322TEST_P(AddEntropyTest, AddLargeEntropy) {
5323 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
5324}
5325
David Drysdalebb3d85e2021-04-13 11:15:51 +01005326/*
5327 * AddEntropyTest.AddTooLargeEntropy
5328 *
5329 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
5330 */
5331TEST_P(AddEntropyTest, AddTooLargeEntropy) {
5332 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
5333 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
5334}
5335
Selene Huang31ab4042020-04-29 04:22:39 -07005336INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
5337
Selene Huang31ab4042020-04-29 04:22:39 -07005338typedef KeyMintAidlTestBase KeyDeletionTest;
5339
5340/**
5341 * KeyDeletionTest.DeleteKey
5342 *
5343 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
5344 * valid key blob.
5345 */
5346TEST_P(KeyDeletionTest, DeleteKey) {
5347 auto error = GenerateKey(AuthorizationSetBuilder()
5348 .RsaSigningKey(2048, 65537)
5349 .Digest(Digest::NONE)
5350 .Padding(PaddingMode::NONE)
5351 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005352 .Authorization(TAG_ROLLBACK_RESISTANCE)
5353 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005354 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5355
5356 // Delete must work if rollback protection is implemented
5357 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005358 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005359 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5360
5361 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
5362
5363 string message = "12345678901234567890123456789012";
5364 AuthorizationSet begin_out_params;
5365 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5366 Begin(KeyPurpose::SIGN, key_blob_,
5367 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5368 &begin_out_params));
5369 AbortIfNeeded();
5370 key_blob_ = AidlBuf();
5371 }
5372}
5373
5374/**
5375 * KeyDeletionTest.DeleteInvalidKey
5376 *
5377 * This test checks that the HAL excepts invalid key blobs..
5378 */
5379TEST_P(KeyDeletionTest, DeleteInvalidKey) {
5380 // Generate key just to check if rollback protection is implemented
5381 auto error = GenerateKey(AuthorizationSetBuilder()
5382 .RsaSigningKey(2048, 65537)
5383 .Digest(Digest::NONE)
5384 .Padding(PaddingMode::NONE)
5385 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005386 .Authorization(TAG_ROLLBACK_RESISTANCE)
5387 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005388 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5389
5390 // Delete must work if rollback protection is implemented
5391 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005392 AuthorizationSet enforced(SecLevelAuthorizations());
5393 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005394
5395 // Delete the key we don't care about the result at this point.
5396 DeleteKey();
5397
5398 // Now create an invalid key blob and delete it.
5399 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
5400
5401 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5402 }
5403}
5404
5405/**
5406 * KeyDeletionTest.DeleteAllKeys
5407 *
5408 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
5409 *
5410 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
5411 * FBE/FDE encryption keys, which means that the device will not even boot until after the
5412 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
5413 * been provisioned. Use this test only on dedicated testing devices that have no valuable
5414 * credentials stored in Keystore/Keymint.
5415 */
5416TEST_P(KeyDeletionTest, DeleteAllKeys) {
5417 if (!arm_deleteAllKeys) return;
5418 auto error = GenerateKey(AuthorizationSetBuilder()
5419 .RsaSigningKey(2048, 65537)
5420 .Digest(Digest::NONE)
5421 .Padding(PaddingMode::NONE)
5422 .Authorization(TAG_NO_AUTH_REQUIRED)
5423 .Authorization(TAG_ROLLBACK_RESISTANCE));
5424 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5425
5426 // Delete must work if rollback protection is implemented
5427 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005428 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005429 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5430
5431 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
5432
5433 string message = "12345678901234567890123456789012";
5434 AuthorizationSet begin_out_params;
5435
5436 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5437 Begin(KeyPurpose::SIGN, key_blob_,
5438 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5439 &begin_out_params));
5440 AbortIfNeeded();
5441 key_blob_ = AidlBuf();
5442 }
5443}
5444
5445INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
5446
5447using UpgradeKeyTest = KeyMintAidlTestBase;
5448
5449/*
5450 * UpgradeKeyTest.UpgradeKey
5451 *
5452 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
5453 */
5454TEST_P(UpgradeKeyTest, UpgradeKey) {
5455 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5456 .AesEncryptionKey(128)
5457 .Padding(PaddingMode::NONE)
5458 .Authorization(TAG_NO_AUTH_REQUIRED)));
5459
5460 auto result = UpgradeKey(key_blob_);
5461
5462 // Key doesn't need upgrading. Should get okay, but no new key blob.
5463 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
5464}
5465
5466INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
5467
5468using ClearOperationsTest = KeyMintAidlTestBase;
5469
5470/*
5471 * ClearSlotsTest.TooManyOperations
5472 *
5473 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
5474 * operations are started without being finished or aborted. Also verifies
5475 * that aborting the operations clears the operations.
5476 *
5477 */
5478TEST_P(ClearOperationsTest, TooManyOperations) {
5479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5480 .Authorization(TAG_NO_AUTH_REQUIRED)
5481 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005482 .Padding(PaddingMode::NONE)
5483 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005484
5485 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5486 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08005487 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07005488 AuthorizationSet out_params;
5489 ErrorCode result;
5490 size_t i;
5491
5492 for (i = 0; i < max_operations; i++) {
5493 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
5494 if (ErrorCode::OK != result) {
5495 break;
5496 }
5497 }
5498 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
5499 // Try again just in case there's a weird overflow bug
5500 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
5501 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5502 for (size_t j = 0; j < i; j++) {
5503 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
5504 << "Aboort failed for i = " << j << std::endl;
5505 }
5506 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5507 AbortIfNeeded();
5508}
5509
5510INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
5511
5512typedef KeyMintAidlTestBase TransportLimitTest;
5513
5514/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005515 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07005516 *
5517 * Verifies that passing input data to finish succeeds as expected.
5518 */
5519TEST_P(TransportLimitTest, LargeFinishInput) {
5520 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5521 .Authorization(TAG_NO_AUTH_REQUIRED)
5522 .AesEncryptionKey(128)
5523 .BlockMode(BlockMode::ECB)
5524 .Padding(PaddingMode::NONE)));
5525
5526 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
5527 auto cipher_params =
5528 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5529
5530 AuthorizationSet out_params;
5531 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
5532
5533 string plain_message = std::string(1 << msg_size, 'x');
5534 string encrypted_message;
5535 auto rc = Finish(plain_message, &encrypted_message);
5536
5537 EXPECT_EQ(ErrorCode::OK, rc);
5538 EXPECT_EQ(plain_message.size(), encrypted_message.size())
5539 << "Encrypt finish returned OK, but did not consume all of the given input";
5540 cipher_params.push_back(out_params);
5541
5542 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
5543
5544 string decrypted_message;
5545 rc = Finish(encrypted_message, &decrypted_message);
5546 EXPECT_EQ(ErrorCode::OK, rc);
5547 EXPECT_EQ(plain_message.size(), decrypted_message.size())
5548 << "Decrypt finish returned OK, did not consume all of the given input";
5549 }
5550}
5551
5552INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
5553
David Zeuthene0c40892021-01-08 12:54:11 -05005554typedef KeyMintAidlTestBase KeyAgreementTest;
5555
5556int CurveToOpenSslCurveName(EcCurve curve) {
5557 switch (curve) {
5558 case EcCurve::P_224:
5559 return NID_secp224r1;
5560 case EcCurve::P_256:
5561 return NID_X9_62_prime256v1;
5562 case EcCurve::P_384:
5563 return NID_secp384r1;
5564 case EcCurve::P_521:
5565 return NID_secp521r1;
5566 }
5567}
5568
5569/*
5570 * KeyAgreementTest.Ecdh
5571 *
5572 * Verifies that ECDH works for all curves
5573 */
5574TEST_P(KeyAgreementTest, Ecdh) {
5575 // Because it's possible to use this API with keys on different curves, we
5576 // check all N^2 combinations where N is the number of supported
5577 // curves.
5578 //
5579 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
5580 // lot more curves we can be smart about things and just pick |otherCurve| so
5581 // it's not |curve| and that way we end up with only 2*N runs
5582 //
5583 for (auto curve : ValidCurves()) {
5584 for (auto localCurve : ValidCurves()) {
5585 // Generate EC key locally (with access to private key material)
5586 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
5587 int curveName = CurveToOpenSslCurveName(localCurve);
5588 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
5589 ASSERT_NE(group, nullptr);
5590 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
5591 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
5592 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
5593 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
5594
5595 // Get encoded form of the public part of the locally generated key...
5596 unsigned char* p = nullptr;
5597 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
5598 ASSERT_GT(encodedPublicKeySize, 0);
5599 vector<uint8_t> encodedPublicKey(
5600 reinterpret_cast<const uint8_t*>(p),
5601 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
5602 OPENSSL_free(p);
5603
5604 // Generate EC key in KeyMint (only access to public key material)
5605 vector<uint8_t> challenge = {0x41, 0x42};
5606 EXPECT_EQ(
5607 ErrorCode::OK,
5608 GenerateKey(AuthorizationSetBuilder()
5609 .Authorization(TAG_NO_AUTH_REQUIRED)
5610 .Authorization(TAG_EC_CURVE, curve)
5611 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
5612 .Authorization(TAG_ALGORITHM, Algorithm::EC)
5613 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08005614 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
5615 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05005616 << "Failed to generate key";
5617 ASSERT_GT(cert_chain_.size(), 0);
5618 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
5619 ASSERT_NE(kmKeyCert, nullptr);
5620 // Check that keyAgreement (bit 4) is set in KeyUsage
5621 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
5622 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
5623 ASSERT_NE(kmPkey, nullptr);
5624 if (dump_Attestations) {
5625 for (size_t n = 0; n < cert_chain_.size(); n++) {
5626 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
5627 }
5628 }
5629
5630 // Now that we have the two keys, we ask KeyMint to perform ECDH...
5631 if (curve != localCurve) {
5632 // If the keys are using different curves KeyMint should fail with
5633 // ErrorCode:INVALID_ARGUMENT. Check that.
5634 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5635 string ZabFromKeyMintStr;
5636 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
5637 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5638 &ZabFromKeyMintStr));
5639
5640 } else {
5641 // Otherwise if the keys are using the same curve, it should work.
5642 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5643 string ZabFromKeyMintStr;
5644 EXPECT_EQ(ErrorCode::OK,
5645 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5646 &ZabFromKeyMintStr));
5647 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
5648
5649 // Perform local ECDH between the two keys so we can check if we get the same Zab..
5650 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
5651 ASSERT_NE(ctx, nullptr);
5652 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
5653 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
5654 size_t ZabFromTestLen = 0;
5655 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
5656 vector<uint8_t> ZabFromTest;
5657 ZabFromTest.resize(ZabFromTestLen);
5658 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
5659
5660 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
5661 }
5662
5663 CheckedDeleteKey();
5664 }
5665 }
5666}
5667
5668INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
5669
Shawn Willdend659c7c2021-02-19 14:51:51 -07005670using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005671
5672TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
5673 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5674 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5675
5676 CheckedDeleteKey(&aesKeyData.blob);
5677 CheckedDeleteKey(&hmacKeyData.blob);
5678 CheckedDeleteKey(&rsaKeyData.blob);
5679 CheckedDeleteKey(&ecdsaKeyData.blob);
5680}
5681
5682// This is a more comprenhensive test, but it can only be run on a machine which is still in early
5683// boot stage, which no proper Android device is by the time we can run VTS. To use this,
5684// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
5685// early boot, so you'll have to reboot between runs.
5686TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
5687 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5688 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5689 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
5690 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5691 EXPECT_TRUE(
5692 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5693 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5694 EXPECT_TRUE(
5695 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5696
5697 // Should be able to use keys, since early boot has not ended
5698 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5699 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5700 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5701 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5702
5703 // End early boot
5704 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
5705 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
5706
5707 // Should not be able to use already-created keys.
5708 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
5709 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
5710 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
5711 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
5712
5713 CheckedDeleteKey(&aesKeyData.blob);
5714 CheckedDeleteKey(&hmacKeyData.blob);
5715 CheckedDeleteKey(&rsaKeyData.blob);
5716 CheckedDeleteKey(&ecdsaKeyData.blob);
5717
5718 // Should not be able to create new keys
5719 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
5720 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
5721
5722 CheckedDeleteKey(&aesKeyData.blob);
5723 CheckedDeleteKey(&hmacKeyData.blob);
5724 CheckedDeleteKey(&rsaKeyData.blob);
5725 CheckedDeleteKey(&ecdsaKeyData.blob);
5726}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005727
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005728INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
5729
Shawn Willdend659c7c2021-02-19 14:51:51 -07005730using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005731
5732// This may be a problematic test. It can't be run repeatedly without unlocking the device in
5733// between runs... and on most test devices there are no enrolled credentials so it can't be
5734// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
5735// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
5736// a manual test process, which includes unlocking between runs, which is why it's included here.
5737// Well, that and the fact that it's the only test we can do without also making calls into the
5738// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
5739// implications might be, so that may or may not be a solution.
5740TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
5741 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5742 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
5743
5744 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5745 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5746 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5747 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5748
5749 ErrorCode rc = GetReturnErrorCode(
5750 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
5751 ASSERT_EQ(ErrorCode::OK, rc);
5752 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
5753 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
5754 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
5755 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
5756
5757 CheckedDeleteKey(&aesKeyData.blob);
5758 CheckedDeleteKey(&hmacKeyData.blob);
5759 CheckedDeleteKey(&rsaKeyData.blob);
5760 CheckedDeleteKey(&ecdsaKeyData.blob);
5761}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005762
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005763INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
5764
Janis Danisevskis24c04702020-12-16 18:28:39 -08005765} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07005766
5767int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07005768 std::cout << "Testing ";
5769 auto halInstances =
5770 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
5771 std::cout << "HAL instances:\n";
5772 for (auto& entry : halInstances) {
5773 std::cout << " " << entry << '\n';
5774 }
5775
Selene Huang31ab4042020-04-29 04:22:39 -07005776 ::testing::InitGoogleTest(&argc, argv);
5777 for (int i = 1; i < argc; ++i) {
5778 if (argv[i][0] == '-') {
5779 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07005780 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5781 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07005782 }
5783 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07005784 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5785 dump_Attestations = true;
5786 } else {
5787 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07005788 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01005789 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
5790 if (std::string(argv[i]) == "--check_patchLevels") {
5791 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
5792 }
Selene Huang31ab4042020-04-29 04:22:39 -07005793 }
5794 }
Shawn Willden08a7e432020-12-11 13:05:27 +00005795 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07005796}