blob: 19ee83c65bd7fb1052b4bd5ce65c2084dc31ed32 [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);
David Drysdale7de9feb2021-03-05 14:56:19 +0000446 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800447 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000448 .AesEncryptionKey(key_size)
449 .BlockMode(block_mode)
450 .Padding(padding_mode)
451 .SetDefaultValidity();
452 if (block_mode == BlockMode::GCM) {
453 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
454 }
455
Tommy Chiu3950b452021-05-03 22:01:46 +0800456 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000457 if (result == ErrorCode::OK) {
458 // Key creation was OK but has generated a key that cannot be used.
459 auto params =
460 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800461 if (block_mode == BlockMode::GCM) {
462 params.Authorization(TAG_MAC_LENGTH, 128);
463 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000464 auto result = Begin(KeyPurpose::ENCRYPT, params);
465 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
466 result == ErrorCode::INVALID_KEY_BLOB);
467 } else {
468 // The KeyMint implementation detected that the generated key
469 // is unusable.
470 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
471 }
472 }
473 }
474 }
475}
476
477/*
478 * NewKeyGenerationTest.AesGcmMissingMinMac
479 *
480 * Verifies that specifying an invalid key size for AES key generation returns
481 * UNSUPPORTED_KEY_SIZE.
482 */
483TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
484 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
485 BlockMode block_mode = BlockMode::GCM;
486 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
487 SCOPED_TRACE(testing::Message()
488 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
489 vector<uint8_t> key_blob;
490 vector<KeyCharacteristics> key_characteristics;
491 // No MIN_MAC_LENGTH provided.
492 auto builder = AuthorizationSetBuilder()
493 .AesEncryptionKey(key_size)
494 .BlockMode(block_mode)
495 .Padding(padding_mode)
496 .SetDefaultValidity();
497 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
498 GenerateKey(builder, &key_blob, &key_characteristics));
499 }
500 }
501}
502
503/*
504 * NewKeyGenerationTest.TripleDes
505 *
506 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
507 * have correct characteristics.
508 */
509TEST_P(NewKeyGenerationTest, TripleDes) {
510 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
511 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
512 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
513 SCOPED_TRACE(testing::Message()
514 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
515 vector<uint8_t> key_blob;
516 vector<KeyCharacteristics> key_characteristics;
517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
518 .TripleDesEncryptionKey(key_size)
519 .BlockMode(block_mode)
520 .Padding(padding_mode)
521 .Authorization(TAG_NO_AUTH_REQUIRED)
522 .SetDefaultValidity(),
523 &key_blob, &key_characteristics));
524
525 EXPECT_GT(key_blob.size(), 0U);
526 CheckSymmetricParams(key_characteristics);
527
528 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
529
530 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
531 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
532 << "Key size " << key_size << "missing";
533
534 CheckedDeleteKey(&key_blob);
535 }
536 }
537 }
538}
539
540/*
541 * NewKeyGenerationTest.TripleDesWithAttestation
542 *
543 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
544 * have correct characteristics.
545 *
546 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
547 * put in a certificate) but which isn't an error.
548 */
549TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
550 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
551 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
552 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
553 SCOPED_TRACE(testing::Message()
554 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
555
556 auto challenge = "hello";
557 auto app_id = "foo";
558
559 vector<uint8_t> key_blob;
560 vector<KeyCharacteristics> key_characteristics;
561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
562 .TripleDesEncryptionKey(key_size)
563 .BlockMode(block_mode)
564 .Padding(padding_mode)
565 .Authorization(TAG_NO_AUTH_REQUIRED)
566 .AttestationChallenge(challenge)
567 .AttestationApplicationId(app_id)
568 .SetDefaultValidity(),
569 &key_blob, &key_characteristics));
570
571 EXPECT_GT(key_blob.size(), 0U);
572 CheckSymmetricParams(key_characteristics);
573
574 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
575
576 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
577 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
578 << "Key size " << key_size << "missing";
579
580 CheckedDeleteKey(&key_blob);
581 }
582 }
583 }
584}
585
586/*
587 * NewKeyGenerationTest.TripleDesInvalidSize
588 *
589 * Verifies that specifying an invalid key size for 3-DES key generation returns
590 * UNSUPPORTED_KEY_SIZE.
591 */
592TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
593 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
594 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
595 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
596 SCOPED_TRACE(testing::Message()
597 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
598 vector<uint8_t> key_blob;
599 vector<KeyCharacteristics> key_characteristics;
600 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
601 GenerateKey(AuthorizationSetBuilder()
602 .TripleDesEncryptionKey(key_size)
603 .BlockMode(block_mode)
604 .Padding(padding_mode)
605 .Authorization(TAG_NO_AUTH_REQUIRED)
606 .SetDefaultValidity(),
607 &key_blob, &key_characteristics));
608 }
609 }
610 }
611
612 // Omitting the key size fails.
613 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
614 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
615 SCOPED_TRACE(testing::Message()
616 << "3DES-default-" << block_mode << "-" << padding_mode);
617 vector<uint8_t> key_blob;
618 vector<KeyCharacteristics> key_characteristics;
619 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
620 GenerateKey(AuthorizationSetBuilder()
621 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
622 .BlockMode(block_mode)
623 .Padding(padding_mode)
624 .Authorization(TAG_NO_AUTH_REQUIRED)
625 .SetDefaultValidity(),
626 &key_blob, &key_characteristics));
627 }
628 }
629}
630
631/*
Selene Huang31ab4042020-04-29 04:22:39 -0700632 * NewKeyGenerationTest.Rsa
633 *
634 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
635 * have correct characteristics.
636 */
637TEST_P(NewKeyGenerationTest, Rsa) {
638 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
639 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700640 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
642 .RsaSigningKey(key_size, 65537)
643 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800644 .Padding(PaddingMode::NONE)
645 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700646 &key_blob, &key_characteristics));
647
648 ASSERT_GT(key_blob.size(), 0U);
649 CheckBaseParams(key_characteristics);
650
Shawn Willden7f424372021-01-10 18:06:50 -0700651 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700652
653 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
654 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
655 << "Key size " << key_size << "missing";
656 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
657
658 CheckedDeleteKey(&key_blob);
659 }
660}
661
662/*
Qi Wud22ec842020-11-26 13:27:53 +0800663 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700664 *
665 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
666 * have correct characteristics.
667 */
668TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700669 auto challenge = "hello";
670 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700671
Selene Huang6e46f142021-04-20 19:20:11 -0700672 auto subject = "cert subj 2";
673 vector<uint8_t> subject_der(make_name_from_str(subject));
674
675 uint64_t serial_int = 66;
676 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
677
Selene Huang4f64c222021-04-13 19:54:36 -0700678 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700679 vector<uint8_t> key_blob;
680 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700681 ASSERT_EQ(ErrorCode::OK,
682 GenerateKey(AuthorizationSetBuilder()
683 .RsaSigningKey(key_size, 65537)
684 .Digest(Digest::NONE)
685 .Padding(PaddingMode::NONE)
686 .AttestationChallenge(challenge)
687 .AttestationApplicationId(app_id)
688 .Authorization(TAG_NO_AUTH_REQUIRED)
689 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
690 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
691 .SetDefaultValidity(),
692 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700693
694 ASSERT_GT(key_blob.size(), 0U);
695 CheckBaseParams(key_characteristics);
696
697 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
698
699 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
700 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
701 << "Key size " << key_size << "missing";
702 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
703
Selene Huang6e46f142021-04-20 19:20:11 -0700704 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700705 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700706 ASSERT_GT(cert_chain_.size(), 0);
707
708 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
709 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
710 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
711 sw_enforced, hw_enforced, SecLevel(),
712 cert_chain_[0].encodedCertificate));
713
714 CheckedDeleteKey(&key_blob);
715 }
716}
717
718/*
David Drysdale4dc01072021-04-01 12:17:35 +0100719 * NewKeyGenerationTest.RsaWithRpkAttestation
720 *
721 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
722 * that has been generated using an associate IRemotelyProvisionedComponent.
723 */
724TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
725 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
726 // instance.
727 std::shared_ptr<IRemotelyProvisionedComponent> rp;
728 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
729 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
730
731 // Generate a P-256 keypair to use as an attestation key.
732 MacedPublicKey macedPubKey;
733 std::vector<uint8_t> privateKeyBlob;
734 auto status =
735 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
736 ASSERT_TRUE(status.isOk());
737 vector<uint8_t> coseKeyData;
738 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
739
740 AttestationKey attestation_key;
741 attestation_key.keyBlob = std::move(privateKeyBlob);
742 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
743
744 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
745 auto challenge = "hello";
746 auto app_id = "foo";
747
748 vector<uint8_t> key_blob;
749 vector<KeyCharacteristics> key_characteristics;
750 ASSERT_EQ(ErrorCode::OK,
751 GenerateKey(AuthorizationSetBuilder()
752 .RsaSigningKey(key_size, 65537)
753 .Digest(Digest::NONE)
754 .Padding(PaddingMode::NONE)
755 .AttestationChallenge(challenge)
756 .AttestationApplicationId(app_id)
757 .Authorization(TAG_NO_AUTH_REQUIRED)
758 .SetDefaultValidity(),
759 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
760
761 ASSERT_GT(key_blob.size(), 0U);
762 CheckBaseParams(key_characteristics);
763
764 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
765
766 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
767 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
768 << "Key size " << key_size << "missing";
769 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
770
771 // Attestation by itself is not valid (last entry is not self-signed).
772 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
773
774 // The signature over the attested key should correspond to the P256 public key.
775 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
776 ASSERT_TRUE(key_cert.get());
777 EVP_PKEY_Ptr signing_pubkey;
778 p256_pub_key(coseKeyData, &signing_pubkey);
779 ASSERT_TRUE(signing_pubkey.get());
780
781 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
782 << "Verification of attested certificate failed "
783 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
784
785 CheckedDeleteKey(&key_blob);
786 }
787}
788
789/*
Selene Huang4f64c222021-04-13 19:54:36 -0700790 * NewKeyGenerationTest.RsaEncryptionWithAttestation
791 *
792 * Verifies that keymint attestation for RSA encryption keys with challenge and
793 * app id is also successful.
794 */
795TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
796 auto key_size = 2048;
797 auto challenge = "hello";
798 auto app_id = "foo";
799
Selene Huang6e46f142021-04-20 19:20:11 -0700800 auto subject = "subj 2";
801 vector<uint8_t> subject_der(make_name_from_str(subject));
802
803 uint64_t serial_int = 111166;
804 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
805
Selene Huang4f64c222021-04-13 19:54:36 -0700806 vector<uint8_t> key_blob;
807 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700808 ASSERT_EQ(ErrorCode::OK,
809 GenerateKey(AuthorizationSetBuilder()
810 .RsaEncryptionKey(key_size, 65537)
811 .Padding(PaddingMode::NONE)
812 .AttestationChallenge(challenge)
813 .AttestationApplicationId(app_id)
814 .Authorization(TAG_NO_AUTH_REQUIRED)
815 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
816 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
817 .SetDefaultValidity(),
818 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700819
820 ASSERT_GT(key_blob.size(), 0U);
821 AuthorizationSet auths;
822 for (auto& entry : key_characteristics) {
823 auths.push_back(AuthorizationSet(entry.authorizations));
824 }
825
826 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
827 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
828
829 // Verify that App data and ROT are NOT included.
830 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
831 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
832
833 // Check that some unexpected tags/values are NOT present.
834 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
835 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
836
837 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
838
839 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
840 ASSERT_TRUE(os_ver);
841 EXPECT_EQ(*os_ver, os_version());
842
843 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
844
845 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
846 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
847 << "Key size " << key_size << "missing";
848 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
849
Selene Huang6e46f142021-04-20 19:20:11 -0700850 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700851 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
852 ASSERT_GT(cert_chain_.size(), 0);
853
854 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
855 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
856 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
857 sw_enforced, hw_enforced, SecLevel(),
858 cert_chain_[0].encodedCertificate));
859
860 CheckedDeleteKey(&key_blob);
861}
862
863/*
864 * NewKeyGenerationTest.RsaWithSelfSign
865 *
866 * Verifies that attesting to RSA key generation is successful, and returns
867 * self signed certificate if no challenge is provided. And signing etc
868 * works as expected.
869 */
870TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -0700871 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
872 vector<uint8_t> subject_der(make_name_from_str(subject));
873
874 uint64_t serial_int = 0;
875 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
876
Selene Huang4f64c222021-04-13 19:54:36 -0700877 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
878 vector<uint8_t> key_blob;
879 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700880 ASSERT_EQ(ErrorCode::OK,
881 GenerateKey(AuthorizationSetBuilder()
882 .RsaSigningKey(key_size, 65537)
883 .Digest(Digest::NONE)
884 .Padding(PaddingMode::NONE)
885 .Authorization(TAG_NO_AUTH_REQUIRED)
886 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
887 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
888 .SetDefaultValidity(),
889 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700890
891 ASSERT_GT(key_blob.size(), 0U);
892 CheckBaseParams(key_characteristics);
893
894 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
895
896 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
897 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
898 << "Key size " << key_size << "missing";
899 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
900
Selene Huang6e46f142021-04-20 19:20:11 -0700901 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700902 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
903 ASSERT_EQ(cert_chain_.size(), 1);
904
905 CheckedDeleteKey(&key_blob);
906 }
907}
908
909/*
910 * NewKeyGenerationTest.RsaWithAttestationMissAppId
911 *
912 * Verifies that attesting to RSA checks for missing app ID.
913 */
914TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
915 auto challenge = "hello";
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918
919 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
920 GenerateKey(AuthorizationSetBuilder()
921 .RsaSigningKey(2048, 65537)
922 .Digest(Digest::NONE)
923 .Padding(PaddingMode::NONE)
924 .AttestationChallenge(challenge)
925 .Authorization(TAG_NO_AUTH_REQUIRED)
926 .SetDefaultValidity(),
927 &key_blob, &key_characteristics));
928}
929
930/*
931 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
932 *
933 * Verifies that attesting to RSA ignores app id if challenge is missing.
934 */
935TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
936 auto key_size = 2048;
937 auto app_id = "foo";
938
Selene Huang6e46f142021-04-20 19:20:11 -0700939 auto subject = "cert subj 2";
940 vector<uint8_t> subject_der(make_name_from_str(subject));
941
942 uint64_t serial_int = 1;
943 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
944
Selene Huang4f64c222021-04-13 19:54:36 -0700945 vector<uint8_t> key_blob;
946 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700947 ASSERT_EQ(ErrorCode::OK,
948 GenerateKey(AuthorizationSetBuilder()
949 .RsaSigningKey(key_size, 65537)
950 .Digest(Digest::NONE)
951 .Padding(PaddingMode::NONE)
952 .AttestationApplicationId(app_id)
953 .Authorization(TAG_NO_AUTH_REQUIRED)
954 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
955 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
956 .SetDefaultValidity(),
957 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700958
959 ASSERT_GT(key_blob.size(), 0U);
960 CheckBaseParams(key_characteristics);
961
962 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
963
964 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
965 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
966 << "Key size " << key_size << "missing";
967 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
968
Selene Huang6e46f142021-04-20 19:20:11 -0700969 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700970 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
971 ASSERT_EQ(cert_chain_.size(), 1);
972
973 CheckedDeleteKey(&key_blob);
974}
975
976/*
Qi Wud22ec842020-11-26 13:27:53 +0800977 * NewKeyGenerationTest.LimitedUsageRsa
978 *
979 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
980 * resulting keys have correct characteristics.
981 */
982TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
983 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
984 vector<uint8_t> key_blob;
985 vector<KeyCharacteristics> key_characteristics;
986 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
987 .RsaSigningKey(key_size, 65537)
988 .Digest(Digest::NONE)
989 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800990 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
991 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800992 &key_blob, &key_characteristics));
993
994 ASSERT_GT(key_blob.size(), 0U);
995 CheckBaseParams(key_characteristics);
996
997 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
998
999 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1000 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1001 << "Key size " << key_size << "missing";
1002 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1003
1004 // Check the usage count limit tag appears in the authorizations.
1005 AuthorizationSet auths;
1006 for (auto& entry : key_characteristics) {
1007 auths.push_back(AuthorizationSet(entry.authorizations));
1008 }
1009 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1010 << "key usage count limit " << 1U << " missing";
1011
1012 CheckedDeleteKey(&key_blob);
1013 }
1014}
1015
1016/*
Qi Wubeefae42021-01-28 23:16:37 +08001017 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1018 *
1019 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1020 * resulting keys have correct characteristics and attestation.
1021 */
1022TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001023 auto challenge = "hello";
1024 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001025
Selene Huang6e46f142021-04-20 19:20:11 -07001026 auto subject = "cert subj 2";
1027 vector<uint8_t> subject_der(make_name_from_str(subject));
1028
1029 uint64_t serial_int = 66;
1030 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1031
Selene Huang4f64c222021-04-13 19:54:36 -07001032 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001033 vector<uint8_t> key_blob;
1034 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001035 ASSERT_EQ(ErrorCode::OK,
1036 GenerateKey(AuthorizationSetBuilder()
1037 .RsaSigningKey(key_size, 65537)
1038 .Digest(Digest::NONE)
1039 .Padding(PaddingMode::NONE)
1040 .AttestationChallenge(challenge)
1041 .AttestationApplicationId(app_id)
1042 .Authorization(TAG_NO_AUTH_REQUIRED)
1043 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1044 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1045 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1046 .SetDefaultValidity(),
1047 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001048
1049 ASSERT_GT(key_blob.size(), 0U);
1050 CheckBaseParams(key_characteristics);
1051
1052 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1053
1054 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1055 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1056 << "Key size " << key_size << "missing";
1057 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1058
1059 // Check the usage count limit tag appears in the authorizations.
1060 AuthorizationSet auths;
1061 for (auto& entry : key_characteristics) {
1062 auths.push_back(AuthorizationSet(entry.authorizations));
1063 }
1064 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1065 << "key usage count limit " << 1U << " missing";
1066
1067 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001068 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001069 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001070 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001071
1072 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1073 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1074 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1075 sw_enforced, hw_enforced, SecLevel(),
1076 cert_chain_[0].encodedCertificate));
1077
1078 CheckedDeleteKey(&key_blob);
1079 }
1080}
1081
1082/*
Selene Huang31ab4042020-04-29 04:22:39 -07001083 * NewKeyGenerationTest.NoInvalidRsaSizes
1084 *
1085 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1086 */
1087TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1088 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1089 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001090 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001091 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1092 GenerateKey(AuthorizationSetBuilder()
1093 .RsaSigningKey(key_size, 65537)
1094 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001095 .Padding(PaddingMode::NONE)
1096 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001097 &key_blob, &key_characteristics));
1098 }
1099}
1100
1101/*
1102 * NewKeyGenerationTest.RsaNoDefaultSize
1103 *
1104 * Verifies that failing to specify a key size for RSA key generation returns
1105 * UNSUPPORTED_KEY_SIZE.
1106 */
1107TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1108 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1109 GenerateKey(AuthorizationSetBuilder()
1110 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1111 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001112 .SigningKey()
1113 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001114}
1115
1116/*
1117 * NewKeyGenerationTest.Ecdsa
1118 *
1119 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1120 * have correct characteristics.
1121 */
1122TEST_P(NewKeyGenerationTest, Ecdsa) {
1123 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1124 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001125 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001126 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1127 .EcdsaSigningKey(key_size)
1128 .Digest(Digest::NONE)
1129 .SetDefaultValidity(),
1130 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001131 ASSERT_GT(key_blob.size(), 0U);
1132 CheckBaseParams(key_characteristics);
1133
Shawn Willden7f424372021-01-10 18:06:50 -07001134 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001135
1136 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1137 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1138 << "Key size " << key_size << "missing";
1139
1140 CheckedDeleteKey(&key_blob);
1141 }
1142}
1143
1144/*
Selene Huang4f64c222021-04-13 19:54:36 -07001145 * NewKeyGenerationTest.EcdsaAttestation
1146 *
1147 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1148 * an attestation will be generated.
1149 */
1150TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1151 auto challenge = "hello";
1152 auto app_id = "foo";
1153
Selene Huang6e46f142021-04-20 19:20:11 -07001154 auto subject = "cert subj 2";
1155 vector<uint8_t> subject_der(make_name_from_str(subject));
1156
1157 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1158 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1159
Selene Huang4f64c222021-04-13 19:54:36 -07001160 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1161 vector<uint8_t> key_blob;
1162 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001163 ASSERT_EQ(ErrorCode::OK,
1164 GenerateKey(AuthorizationSetBuilder()
1165 .Authorization(TAG_NO_AUTH_REQUIRED)
1166 .EcdsaSigningKey(key_size)
1167 .Digest(Digest::NONE)
1168 .AttestationChallenge(challenge)
1169 .AttestationApplicationId(app_id)
1170 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1171 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1172 .SetDefaultValidity(),
1173 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001174 ASSERT_GT(key_blob.size(), 0U);
1175 CheckBaseParams(key_characteristics);
1176
1177 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1178
1179 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1180 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1181 << "Key size " << key_size << "missing";
1182
1183 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1184 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001185 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001186
1187 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1188 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1189 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1190 sw_enforced, hw_enforced, SecLevel(),
1191 cert_chain_[0].encodedCertificate));
1192
1193 CheckedDeleteKey(&key_blob);
1194 }
1195}
1196
1197/*
1198 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1199 *
1200 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1201 * the key will generate a self signed attestation.
1202 */
1203TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001204 auto subject = "cert subj 2";
1205 vector<uint8_t> subject_der(make_name_from_str(subject));
1206
1207 uint64_t serial_int = 0x123456FFF1234;
1208 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1209
Selene Huang4f64c222021-04-13 19:54:36 -07001210 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1211 vector<uint8_t> key_blob;
1212 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001213 ASSERT_EQ(ErrorCode::OK,
1214 GenerateKey(AuthorizationSetBuilder()
1215 .EcdsaSigningKey(key_size)
1216 .Digest(Digest::NONE)
1217 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1218 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1219 .SetDefaultValidity(),
1220 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001221 ASSERT_GT(key_blob.size(), 0U);
1222 CheckBaseParams(key_characteristics);
1223
1224 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1225
1226 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1227 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1228 << "Key size " << key_size << "missing";
1229
1230 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001231 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001232 ASSERT_EQ(cert_chain_.size(), 1);
1233
1234 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1235 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1236
1237 CheckedDeleteKey(&key_blob);
1238 }
1239}
1240
1241/*
1242 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1243 *
1244 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1245 * app id must also be provided or else it will fail.
1246 */
1247TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1248 auto challenge = "hello";
1249 vector<uint8_t> key_blob;
1250 vector<KeyCharacteristics> key_characteristics;
1251
1252 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1253 GenerateKey(AuthorizationSetBuilder()
1254 .EcdsaSigningKey(EcCurve::P_256)
1255 .Digest(Digest::NONE)
1256 .AttestationChallenge(challenge)
1257 .SetDefaultValidity(),
1258 &key_blob, &key_characteristics));
1259}
1260
1261/*
1262 * NewKeyGenerationTest.EcdsaIgnoreAppId
1263 *
1264 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1265 * any appid will be ignored, and keymint will generate a self sign certificate.
1266 */
1267TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1268 auto app_id = "foo";
1269
1270 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1271 vector<uint8_t> key_blob;
1272 vector<KeyCharacteristics> key_characteristics;
1273 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1274 .EcdsaSigningKey(key_size)
1275 .Digest(Digest::NONE)
1276 .AttestationApplicationId(app_id)
1277 .SetDefaultValidity(),
1278 &key_blob, &key_characteristics));
1279
1280 ASSERT_GT(key_blob.size(), 0U);
1281 CheckBaseParams(key_characteristics);
1282
1283 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1284
1285 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1286 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1287 << "Key size " << key_size << "missing";
1288
1289 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1290 ASSERT_EQ(cert_chain_.size(), 1);
1291
1292 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1293 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1294
1295 CheckedDeleteKey(&key_blob);
1296 }
1297}
1298
1299/*
1300 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1301 *
1302 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1303 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1304 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1305 * to specify how many following bytes will be used to encode the length.
1306 */
1307TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1308 auto challenge = "hello";
1309 auto key_size = 256;
1310 std::vector<uint32_t> app_id_lengths{143, 258};
1311
1312 for (uint32_t length : app_id_lengths) {
1313 const string app_id(length, 'a');
1314 vector<uint8_t> key_blob;
1315 vector<KeyCharacteristics> key_characteristics;
1316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1317 .Authorization(TAG_NO_AUTH_REQUIRED)
1318 .EcdsaSigningKey(key_size)
1319 .Digest(Digest::NONE)
1320 .AttestationChallenge(challenge)
1321 .AttestationApplicationId(app_id)
1322 .SetDefaultValidity(),
1323 &key_blob, &key_characteristics));
1324 ASSERT_GT(key_blob.size(), 0U);
1325 CheckBaseParams(key_characteristics);
1326
1327 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1328
1329 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1330 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1331 << "Key size " << key_size << "missing";
1332
1333 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1334 ASSERT_GT(cert_chain_.size(), 0);
1335
1336 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1337 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1338 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1339 sw_enforced, hw_enforced, SecLevel(),
1340 cert_chain_[0].encodedCertificate));
1341
1342 CheckedDeleteKey(&key_blob);
1343 }
1344}
1345
1346/*
Qi Wud22ec842020-11-26 13:27:53 +08001347 * NewKeyGenerationTest.LimitedUsageEcdsa
1348 *
1349 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1350 * resulting keys have correct characteristics.
1351 */
1352TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1353 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1354 vector<uint8_t> key_blob;
1355 vector<KeyCharacteristics> key_characteristics;
1356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1357 .EcdsaSigningKey(key_size)
1358 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001359 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1360 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001361 &key_blob, &key_characteristics));
1362
1363 ASSERT_GT(key_blob.size(), 0U);
1364 CheckBaseParams(key_characteristics);
1365
1366 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1367
1368 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1369 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1370 << "Key size " << key_size << "missing";
1371
1372 // Check the usage count limit tag appears in the authorizations.
1373 AuthorizationSet auths;
1374 for (auto& entry : key_characteristics) {
1375 auths.push_back(AuthorizationSet(entry.authorizations));
1376 }
1377 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1378 << "key usage count limit " << 1U << " missing";
1379
1380 CheckedDeleteKey(&key_blob);
1381 }
1382}
1383
1384/*
Selene Huang31ab4042020-04-29 04:22:39 -07001385 * NewKeyGenerationTest.EcdsaDefaultSize
1386 *
1387 * Verifies that failing to specify a key size for EC key generation returns
1388 * UNSUPPORTED_KEY_SIZE.
1389 */
1390TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1391 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1392 GenerateKey(AuthorizationSetBuilder()
1393 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1394 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001395 .Digest(Digest::NONE)
1396 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001397}
1398
1399/*
1400 * NewKeyGenerationTest.EcdsaInvalidSize
1401 *
1402 * Verifies that specifying an invalid key size for EC key generation returns
1403 * UNSUPPORTED_KEY_SIZE.
1404 */
1405TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1406 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1407 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001408 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001409 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1410 .EcdsaSigningKey(key_size)
1411 .Digest(Digest::NONE)
1412 .SetDefaultValidity(),
1413 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001414 }
1415
Janis Danisevskis164bb872021-02-09 11:30:25 -08001416 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1417 .EcdsaSigningKey(190)
1418 .Digest(Digest::NONE)
1419 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001420}
1421
1422/*
1423 * NewKeyGenerationTest.EcdsaMismatchKeySize
1424 *
1425 * Verifies that specifying mismatched key size and curve for EC key generation returns
1426 * INVALID_ARGUMENT.
1427 */
1428TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1429 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1430
1431 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1432 GenerateKey(AuthorizationSetBuilder()
1433 .EcdsaSigningKey(224)
1434 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001435 .Digest(Digest::NONE)
1436 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001437}
1438
1439/*
1440 * NewKeyGenerationTest.EcdsaAllValidSizes
1441 *
1442 * Verifies that keymint supports all required EC key sizes.
1443 */
1444TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1445 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1446 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001447 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1448 .EcdsaSigningKey(size)
1449 .Digest(Digest::NONE)
1450 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001451 << "Failed to generate size: " << size;
1452 CheckedDeleteKey();
1453 }
1454}
1455
1456/*
1457 * NewKeyGenerationTest.EcdsaInvalidCurves
1458 *
1459 * Verifies that keymint does not support any curve designated as unsupported.
1460 */
1461TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1462 Digest digest;
1463 if (SecLevel() == SecurityLevel::STRONGBOX) {
1464 digest = Digest::SHA_2_256;
1465 } else {
1466 digest = Digest::SHA_2_512;
1467 }
1468 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001469 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1470 .EcdsaSigningKey(curve)
1471 .Digest(digest)
1472 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001473 << "Failed to generate key on curve: " << curve;
1474 CheckedDeleteKey();
1475 }
1476}
1477
1478/*
1479 * NewKeyGenerationTest.Hmac
1480 *
1481 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1482 * characteristics.
1483 */
1484TEST_P(NewKeyGenerationTest, Hmac) {
1485 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1486 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001487 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001488 constexpr size_t key_size = 128;
1489 ASSERT_EQ(ErrorCode::OK,
1490 GenerateKey(
1491 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1492 TAG_MIN_MAC_LENGTH, 128),
1493 &key_blob, &key_characteristics));
1494
1495 ASSERT_GT(key_blob.size(), 0U);
1496 CheckBaseParams(key_characteristics);
1497
Shawn Willden7f424372021-01-10 18:06:50 -07001498 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1499 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1500 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1501 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001502
1503 CheckedDeleteKey(&key_blob);
1504 }
1505}
1506
1507/*
Selene Huang4f64c222021-04-13 19:54:36 -07001508 * NewKeyGenerationTest.HmacNoAttestation
1509 *
1510 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1511 * and app id are provided.
1512 */
1513TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1514 auto challenge = "hello";
1515 auto app_id = "foo";
1516
1517 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1518 vector<uint8_t> key_blob;
1519 vector<KeyCharacteristics> key_characteristics;
1520 constexpr size_t key_size = 128;
1521 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1522 .HmacKey(key_size)
1523 .Digest(digest)
1524 .AttestationChallenge(challenge)
1525 .AttestationApplicationId(app_id)
1526 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1527 &key_blob, &key_characteristics));
1528
1529 ASSERT_GT(key_blob.size(), 0U);
1530 ASSERT_EQ(cert_chain_.size(), 0);
1531 CheckBaseParams(key_characteristics);
1532
1533 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1534 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1535 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1536 << "Key size " << key_size << "missing";
1537
1538 CheckedDeleteKey(&key_blob);
1539 }
1540}
1541
1542/*
Qi Wud22ec842020-11-26 13:27:53 +08001543 * NewKeyGenerationTest.LimitedUsageHmac
1544 *
1545 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1546 * resulting keys have correct characteristics.
1547 */
1548TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1549 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1550 vector<uint8_t> key_blob;
1551 vector<KeyCharacteristics> key_characteristics;
1552 constexpr size_t key_size = 128;
1553 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1554 .HmacKey(key_size)
1555 .Digest(digest)
1556 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1557 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1558 &key_blob, &key_characteristics));
1559
1560 ASSERT_GT(key_blob.size(), 0U);
1561 CheckBaseParams(key_characteristics);
1562
1563 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1564 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1565 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1566 << "Key size " << key_size << "missing";
1567
1568 // Check the usage count limit tag appears in the authorizations.
1569 AuthorizationSet auths;
1570 for (auto& entry : key_characteristics) {
1571 auths.push_back(AuthorizationSet(entry.authorizations));
1572 }
1573 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1574 << "key usage count limit " << 1U << " missing";
1575
1576 CheckedDeleteKey(&key_blob);
1577 }
1578}
1579
1580/*
Selene Huang31ab4042020-04-29 04:22:39 -07001581 * NewKeyGenerationTest.HmacCheckKeySizes
1582 *
1583 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1584 */
1585TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1586 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1587 if (key_size < 64 || key_size % 8 != 0) {
1588 // To keep this test from being very slow, we only test a random fraction of
1589 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1590 // them, we expect to run ~40 of them in each run.
1591 if (key_size % 8 == 0 || random() % 10 == 0) {
1592 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1593 GenerateKey(AuthorizationSetBuilder()
1594 .HmacKey(key_size)
1595 .Digest(Digest::SHA_2_256)
1596 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1597 << "HMAC key size " << key_size << " invalid";
1598 }
1599 } else {
1600 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1601 .HmacKey(key_size)
1602 .Digest(Digest::SHA_2_256)
1603 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1604 << "Failed to generate HMAC key of size " << key_size;
1605 CheckedDeleteKey();
1606 }
1607 }
1608}
1609
1610/*
1611 * NewKeyGenerationTest.HmacCheckMinMacLengths
1612 *
1613 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1614 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1615 * specific MAC length that failed, so reproducing a failed run will be easy.
1616 */
1617TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1618 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1619 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1620 // To keep this test from being very long, we only test a random fraction of
1621 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1622 // we expect to run ~17 of them in each run.
1623 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1624 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1625 GenerateKey(AuthorizationSetBuilder()
1626 .HmacKey(128)
1627 .Digest(Digest::SHA_2_256)
1628 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1629 << "HMAC min mac length " << min_mac_length << " invalid.";
1630 }
1631 } else {
1632 EXPECT_EQ(ErrorCode::OK,
1633 GenerateKey(AuthorizationSetBuilder()
1634 .HmacKey(128)
1635 .Digest(Digest::SHA_2_256)
1636 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1637 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1638 CheckedDeleteKey();
1639 }
1640 }
1641}
1642
1643/*
1644 * NewKeyGenerationTest.HmacMultipleDigests
1645 *
1646 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1647 */
1648TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1649 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1650
1651 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1652 GenerateKey(AuthorizationSetBuilder()
1653 .HmacKey(128)
1654 .Digest(Digest::SHA1)
1655 .Digest(Digest::SHA_2_256)
1656 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1657}
1658
1659/*
1660 * NewKeyGenerationTest.HmacDigestNone
1661 *
1662 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1663 */
1664TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1665 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1666 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1667 128)));
1668
1669 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1670 GenerateKey(AuthorizationSetBuilder()
1671 .HmacKey(128)
1672 .Digest(Digest::NONE)
1673 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1674}
1675
Selene Huang4f64c222021-04-13 19:54:36 -07001676/*
1677 * NewKeyGenerationTest.AesNoAttestation
1678 *
1679 * Verifies that attestation parameters to AES keys are ignored and generateKey
1680 * will succeed.
1681 */
1682TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1683 auto challenge = "hello";
1684 auto app_id = "foo";
1685
1686 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1687 .Authorization(TAG_NO_AUTH_REQUIRED)
1688 .AesEncryptionKey(128)
1689 .EcbMode()
1690 .Padding(PaddingMode::PKCS7)
1691 .AttestationChallenge(challenge)
1692 .AttestationApplicationId(app_id)));
1693
1694 ASSERT_EQ(cert_chain_.size(), 0);
1695}
1696
1697/*
1698 * NewKeyGenerationTest.TripleDesNoAttestation
1699 *
1700 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1701 * will be successful. No attestation should be generated.
1702 */
1703TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1704 auto challenge = "hello";
1705 auto app_id = "foo";
1706
1707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1708 .TripleDesEncryptionKey(168)
1709 .BlockMode(BlockMode::ECB)
1710 .Authorization(TAG_NO_AUTH_REQUIRED)
1711 .Padding(PaddingMode::NONE)
1712 .AttestationChallenge(challenge)
1713 .AttestationApplicationId(app_id)));
1714 ASSERT_EQ(cert_chain_.size(), 0);
1715}
1716
Selene Huang31ab4042020-04-29 04:22:39 -07001717INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1718
1719typedef KeyMintAidlTestBase SigningOperationsTest;
1720
1721/*
1722 * SigningOperationsTest.RsaSuccess
1723 *
1724 * Verifies that raw RSA signature operations succeed.
1725 */
1726TEST_P(SigningOperationsTest, RsaSuccess) {
1727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1728 .RsaSigningKey(2048, 65537)
1729 .Digest(Digest::NONE)
1730 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001731 .Authorization(TAG_NO_AUTH_REQUIRED)
1732 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001733 string message = "12345678901234567890123456789012";
1734 string signature = SignMessage(
1735 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1736}
1737
1738/*
1739 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1740 *
Shawn Willden7f424372021-01-10 18:06:50 -07001741 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001742 */
1743TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1745 .Authorization(TAG_NO_AUTH_REQUIRED)
1746 .RsaSigningKey(2048, 65537)
1747 .Digest(Digest::NONE)
1748 .Padding(PaddingMode::NONE)
1749 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001750 .Authorization(TAG_APPLICATION_DATA, "appdata")
1751 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001752 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1753 Begin(KeyPurpose::SIGN,
1754 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1755 AbortIfNeeded();
1756 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1757 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1758 .Digest(Digest::NONE)
1759 .Padding(PaddingMode::NONE)
1760 .Authorization(TAG_APPLICATION_ID, "clientid")));
1761 AbortIfNeeded();
1762 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1763 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1764 .Digest(Digest::NONE)
1765 .Padding(PaddingMode::NONE)
1766 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1767 AbortIfNeeded();
1768 EXPECT_EQ(ErrorCode::OK,
1769 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1770 .Digest(Digest::NONE)
1771 .Padding(PaddingMode::NONE)
1772 .Authorization(TAG_APPLICATION_DATA, "appdata")
1773 .Authorization(TAG_APPLICATION_ID, "clientid")));
1774 AbortIfNeeded();
1775}
1776
1777/*
1778 * SigningOperationsTest.RsaPssSha256Success
1779 *
1780 * Verifies that RSA-PSS signature operations succeed.
1781 */
1782TEST_P(SigningOperationsTest, RsaPssSha256Success) {
1783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1784 .RsaSigningKey(2048, 65537)
1785 .Digest(Digest::SHA_2_256)
1786 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001787 .Authorization(TAG_NO_AUTH_REQUIRED)
1788 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001789 // Use large message, which won't work without digesting.
1790 string message(1024, 'a');
1791 string signature = SignMessage(
1792 message,
1793 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1794}
1795
1796/*
1797 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1798 *
1799 * Verifies that keymint rejects signature operations that specify a padding mode when the key
1800 * supports only unpadded operations.
1801 */
1802TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1804 .RsaSigningKey(2048, 65537)
1805 .Digest(Digest::NONE)
1806 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001807 .Padding(PaddingMode::NONE)
1808 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001809 string message = "12345678901234567890123456789012";
1810 string signature;
1811
1812 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1813 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1814 .Digest(Digest::NONE)
1815 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1816}
1817
1818/*
1819 * SigningOperationsTest.NoUserConfirmation
1820 *
1821 * Verifies that keymint rejects signing operations for keys with
1822 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1823 * presented.
1824 */
1825TEST_P(SigningOperationsTest, NoUserConfirmation) {
1826 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001827 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1828 .RsaSigningKey(1024, 65537)
1829 .Digest(Digest::NONE)
1830 .Padding(PaddingMode::NONE)
1831 .Authorization(TAG_NO_AUTH_REQUIRED)
1832 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1833 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001834
1835 const string message = "12345678901234567890123456789012";
1836 EXPECT_EQ(ErrorCode::OK,
1837 Begin(KeyPurpose::SIGN,
1838 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1839 string signature;
1840 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1841}
1842
1843/*
1844 * SigningOperationsTest.RsaPkcs1Sha256Success
1845 *
1846 * Verifies that digested RSA-PKCS1 signature operations succeed.
1847 */
1848TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1849 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1850 .RsaSigningKey(2048, 65537)
1851 .Digest(Digest::SHA_2_256)
1852 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001853 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1854 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001855 string message(1024, 'a');
1856 string signature = SignMessage(message, AuthorizationSetBuilder()
1857 .Digest(Digest::SHA_2_256)
1858 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1859}
1860
1861/*
1862 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1863 *
1864 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1865 */
1866TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1867 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1868 .RsaSigningKey(2048, 65537)
1869 .Digest(Digest::NONE)
1870 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001871 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1872 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001873 string message(53, 'a');
1874 string signature = SignMessage(message, AuthorizationSetBuilder()
1875 .Digest(Digest::NONE)
1876 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1877}
1878
1879/*
1880 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1881 *
1882 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1883 * given a too-long message.
1884 */
1885TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1887 .RsaSigningKey(2048, 65537)
1888 .Digest(Digest::NONE)
1889 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001890 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1891 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001892 string message(257, 'a');
1893
1894 EXPECT_EQ(ErrorCode::OK,
1895 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1896 .Digest(Digest::NONE)
1897 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1898 string signature;
1899 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1900}
1901
1902/*
1903 * SigningOperationsTest.RsaPssSha512TooSmallKey
1904 *
1905 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1906 * used with a key that is too small for the message.
1907 *
1908 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
1909 * keymint specification requires that salt_size == digest_size, so the message will be
1910 * digest_size * 2 +
1911 * 16. Such a message can only be signed by a given key if the key is at least that size. This
1912 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
1913 * for a 1024-bit key.
1914 */
1915TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1916 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1918 .RsaSigningKey(1024, 65537)
1919 .Digest(Digest::SHA_2_512)
1920 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001921 .Padding(PaddingMode::RSA_PSS)
1922 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001923 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1924 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1925 .Digest(Digest::SHA_2_512)
1926 .Padding(PaddingMode::RSA_PSS)));
1927}
1928
1929/*
1930 * SigningOperationsTest.RsaNoPaddingTooLong
1931 *
1932 * Verifies that raw RSA signature operations fail with the correct error code when
1933 * given a too-long message.
1934 */
1935TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1937 .RsaSigningKey(2048, 65537)
1938 .Digest(Digest::NONE)
1939 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001940 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1941 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001942 // One byte too long
1943 string message(2048 / 8 + 1, 'a');
1944 ASSERT_EQ(ErrorCode::OK,
1945 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1946 .Digest(Digest::NONE)
1947 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1948 string result;
1949 ErrorCode finish_error_code = Finish(message, &result);
1950 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1951 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1952
1953 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1954 message = string(128 * 1024, 'a');
1955 ASSERT_EQ(ErrorCode::OK,
1956 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1957 .Digest(Digest::NONE)
1958 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1959 finish_error_code = Finish(message, &result);
1960 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1961 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1962}
1963
1964/*
1965 * SigningOperationsTest.RsaAbort
1966 *
1967 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1968 * test, but the behavior should be algorithm and purpose-independent.
1969 */
1970TEST_P(SigningOperationsTest, RsaAbort) {
1971 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1972 .RsaSigningKey(2048, 65537)
1973 .Digest(Digest::NONE)
1974 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001975 .Padding(PaddingMode::NONE)
1976 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001977
1978 ASSERT_EQ(ErrorCode::OK,
1979 Begin(KeyPurpose::SIGN,
1980 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1981 EXPECT_EQ(ErrorCode::OK, Abort());
1982
1983 // Another abort should fail
1984 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1985
1986 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001987 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001988}
1989
1990/*
1991 * SigningOperationsTest.RsaUnsupportedPadding
1992 *
1993 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1994 * with a padding mode inappropriate for RSA.
1995 */
1996TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1997 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1998 .RsaSigningKey(2048, 65537)
1999 .Authorization(TAG_NO_AUTH_REQUIRED)
2000 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002001 .Padding(PaddingMode::PKCS7)
2002 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002003 ASSERT_EQ(
2004 ErrorCode::UNSUPPORTED_PADDING_MODE,
2005 Begin(KeyPurpose::SIGN,
2006 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
2007}
2008
2009/*
2010 * SigningOperationsTest.RsaPssNoDigest
2011 *
2012 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2013 */
2014TEST_P(SigningOperationsTest, RsaNoDigest) {
2015 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2016 .RsaSigningKey(2048, 65537)
2017 .Authorization(TAG_NO_AUTH_REQUIRED)
2018 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002019 .Padding(PaddingMode::RSA_PSS)
2020 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002021 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2022 Begin(KeyPurpose::SIGN,
2023 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2024
2025 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2026 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2027}
2028
2029/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002030 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002031 *
2032 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2033 * supported in some cases (as validated in other tests), but a mode must be specified.
2034 */
2035TEST_P(SigningOperationsTest, RsaNoPadding) {
2036 // Padding must be specified
2037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2038 .RsaKey(2048, 65537)
2039 .Authorization(TAG_NO_AUTH_REQUIRED)
2040 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002041 .Digest(Digest::NONE)
2042 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002043 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2044 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2045}
2046
2047/*
2048 * SigningOperationsTest.RsaShortMessage
2049 *
2050 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2051 */
2052TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2053 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2054 .Authorization(TAG_NO_AUTH_REQUIRED)
2055 .RsaSigningKey(2048, 65537)
2056 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002057 .Padding(PaddingMode::NONE)
2058 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002059
2060 // Barely shorter
2061 string message(2048 / 8 - 1, 'a');
2062 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2063
2064 // Much shorter
2065 message = "a";
2066 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2067}
2068
2069/*
2070 * SigningOperationsTest.RsaSignWithEncryptionKey
2071 *
2072 * Verifies that RSA encryption keys cannot be used to sign.
2073 */
2074TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2076 .Authorization(TAG_NO_AUTH_REQUIRED)
2077 .RsaEncryptionKey(2048, 65537)
2078 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002079 .Padding(PaddingMode::NONE)
2080 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002081 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2082 Begin(KeyPurpose::SIGN,
2083 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2084}
2085
2086/*
2087 * SigningOperationsTest.RsaSignTooLargeMessage
2088 *
2089 * Verifies that attempting a raw signature of a message which is the same length as the key,
2090 * but numerically larger than the public modulus, fails with the correct error.
2091 */
2092TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2093 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2094 .Authorization(TAG_NO_AUTH_REQUIRED)
2095 .RsaSigningKey(2048, 65537)
2096 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002097 .Padding(PaddingMode::NONE)
2098 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002099
2100 // Largest possible message will always be larger than the public modulus.
2101 string message(2048 / 8, static_cast<char>(0xff));
2102 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2103 .Authorization(TAG_NO_AUTH_REQUIRED)
2104 .Digest(Digest::NONE)
2105 .Padding(PaddingMode::NONE)));
2106 string signature;
2107 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2108}
2109
2110/*
2111 * SigningOperationsTest.EcdsaAllSizesAndHashes
2112 *
2113 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
2114 */
2115TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
2116 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
2117 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2118 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2119 .Authorization(TAG_NO_AUTH_REQUIRED)
2120 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002121 .Digest(digest)
2122 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002123 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
2124 << " and digest " << digest;
2125 if (error != ErrorCode::OK) continue;
2126
2127 string message(1024, 'a');
2128 if (digest == Digest::NONE) message.resize(key_size / 8);
2129 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2130 CheckedDeleteKey();
2131 }
2132 }
2133}
2134
2135/*
2136 * SigningOperationsTest.EcdsaAllCurves
2137 *
2138 * Verifies that ECDSA operations succeed with all possible curves.
2139 */
2140TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2141 for (auto curve : ValidCurves()) {
2142 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2143 .Authorization(TAG_NO_AUTH_REQUIRED)
2144 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002145 .Digest(Digest::SHA_2_256)
2146 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002147 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2148 if (error != ErrorCode::OK) continue;
2149
2150 string message(1024, 'a');
2151 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2152 CheckedDeleteKey();
2153 }
2154}
2155
2156/*
2157 * SigningOperationsTest.EcdsaNoDigestHugeData
2158 *
2159 * Verifies that ECDSA operations support very large messages, even without digesting. This
2160 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2161 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2162 * the framework.
2163 */
2164TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2165 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2166 .Authorization(TAG_NO_AUTH_REQUIRED)
2167 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002168 .Digest(Digest::NONE)
2169 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002170 string message(1 * 1024, 'a');
2171 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2172}
2173
2174/*
2175 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2176 *
2177 * Verifies that using an EC key requires the correct app ID/data.
2178 */
2179TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2180 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2181 .Authorization(TAG_NO_AUTH_REQUIRED)
2182 .EcdsaSigningKey(256)
2183 .Digest(Digest::NONE)
2184 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002185 .Authorization(TAG_APPLICATION_DATA, "appdata")
2186 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002187 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2188 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2189 AbortIfNeeded();
2190 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2191 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2192 .Digest(Digest::NONE)
2193 .Authorization(TAG_APPLICATION_ID, "clientid")));
2194 AbortIfNeeded();
2195 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2196 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2197 .Digest(Digest::NONE)
2198 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2199 AbortIfNeeded();
2200 EXPECT_EQ(ErrorCode::OK,
2201 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2202 .Digest(Digest::NONE)
2203 .Authorization(TAG_APPLICATION_DATA, "appdata")
2204 .Authorization(TAG_APPLICATION_ID, "clientid")));
2205 AbortIfNeeded();
2206}
2207
2208/*
2209 * SigningOperationsTest.AesEcbSign
2210 *
2211 * Verifies that attempts to use AES keys to sign fail in the correct way.
2212 */
2213TEST_P(SigningOperationsTest, AesEcbSign) {
2214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2215 .Authorization(TAG_NO_AUTH_REQUIRED)
2216 .SigningKey()
2217 .AesEncryptionKey(128)
2218 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2219
2220 AuthorizationSet out_params;
2221 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2222 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2223 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2224 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2225}
2226
2227/*
2228 * SigningOperationsTest.HmacAllDigests
2229 *
2230 * Verifies that HMAC works with all digests.
2231 */
2232TEST_P(SigningOperationsTest, HmacAllDigests) {
2233 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2234 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2235 .Authorization(TAG_NO_AUTH_REQUIRED)
2236 .HmacKey(128)
2237 .Digest(digest)
2238 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2239 << "Failed to create HMAC key with digest " << digest;
2240 string message = "12345678901234567890123456789012";
2241 string signature = MacMessage(message, digest, 160);
2242 EXPECT_EQ(160U / 8U, signature.size())
2243 << "Failed to sign with HMAC key with digest " << digest;
2244 CheckedDeleteKey();
2245 }
2246}
2247
2248/*
2249 * SigningOperationsTest.HmacSha256TooLargeMacLength
2250 *
2251 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2252 * digest size.
2253 */
2254TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2256 .Authorization(TAG_NO_AUTH_REQUIRED)
2257 .HmacKey(128)
2258 .Digest(Digest::SHA_2_256)
2259 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2260 AuthorizationSet output_params;
2261 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2262 AuthorizationSetBuilder()
2263 .Digest(Digest::SHA_2_256)
2264 .Authorization(TAG_MAC_LENGTH, 264),
2265 &output_params));
2266}
2267
2268/*
2269 * SigningOperationsTest.HmacSha256TooSmallMacLength
2270 *
2271 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2272 * specified minimum MAC length.
2273 */
2274TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2276 .Authorization(TAG_NO_AUTH_REQUIRED)
2277 .HmacKey(128)
2278 .Digest(Digest::SHA_2_256)
2279 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2280 AuthorizationSet output_params;
2281 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2282 AuthorizationSetBuilder()
2283 .Digest(Digest::SHA_2_256)
2284 .Authorization(TAG_MAC_LENGTH, 120),
2285 &output_params));
2286}
2287
2288/*
2289 * SigningOperationsTest.HmacRfc4231TestCase3
2290 *
2291 * Validates against the test vectors from RFC 4231 test case 3.
2292 */
2293TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2294 string key(20, 0xaa);
2295 string message(50, 0xdd);
2296 uint8_t sha_224_expected[] = {
2297 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2298 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2299 };
2300 uint8_t sha_256_expected[] = {
2301 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2302 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2303 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2304 };
2305 uint8_t sha_384_expected[] = {
2306 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2307 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2308 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2309 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2310 };
2311 uint8_t sha_512_expected[] = {
2312 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2313 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2314 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2315 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2316 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2317 };
2318
2319 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2320 if (SecLevel() != SecurityLevel::STRONGBOX) {
2321 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2322 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2323 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2324 }
2325}
2326
2327/*
2328 * SigningOperationsTest.HmacRfc4231TestCase5
2329 *
2330 * Validates against the test vectors from RFC 4231 test case 5.
2331 */
2332TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2333 string key(20, 0x0c);
2334 string message = "Test With Truncation";
2335
2336 uint8_t sha_224_expected[] = {
2337 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2338 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2339 };
2340 uint8_t sha_256_expected[] = {
2341 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2342 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2343 };
2344 uint8_t sha_384_expected[] = {
2345 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2346 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2347 };
2348 uint8_t sha_512_expected[] = {
2349 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2350 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2351 };
2352
2353 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2354 if (SecLevel() != SecurityLevel::STRONGBOX) {
2355 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2356 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2357 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2358 }
2359}
2360
2361INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2362
2363typedef KeyMintAidlTestBase VerificationOperationsTest;
2364
2365/*
2366 * VerificationOperationsTest.RsaSuccess
2367 *
2368 * Verifies that a simple RSA signature/verification sequence succeeds.
2369 */
2370TEST_P(VerificationOperationsTest, RsaSuccess) {
2371 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2372 .Authorization(TAG_NO_AUTH_REQUIRED)
2373 .RsaSigningKey(2048, 65537)
2374 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002375 .Padding(PaddingMode::NONE)
2376 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002377 string message = "12345678901234567890123456789012";
2378 string signature = SignMessage(
2379 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2380 VerifyMessage(message, signature,
2381 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2382}
2383
2384/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002385 * VerificationOperationsTest.RsaAllPaddingsAndDigests
Selene Huang31ab4042020-04-29 04:22:39 -07002386 *
2387 * Verifies RSA signature/verification for all padding modes and digests.
2388 */
2389TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2390 auto authorizations = AuthorizationSetBuilder()
2391 .Authorization(TAG_NO_AUTH_REQUIRED)
2392 .RsaSigningKey(2048, 65537)
2393 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2394 .Padding(PaddingMode::NONE)
2395 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002396 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2397 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002398
2399 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2400
2401 string message(128, 'a');
2402 string corrupt_message(message);
2403 ++corrupt_message[corrupt_message.size() / 2];
2404
2405 for (auto padding :
2406 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2407 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2408 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2409 // Digesting only makes sense with padding.
2410 continue;
2411 }
2412
2413 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2414 // PSS requires digesting.
2415 continue;
2416 }
2417
2418 string signature =
2419 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2420 VerifyMessage(message, signature,
2421 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2422
2423 /* TODO(seleneh) add exportkey tests back later when we have decided on
2424 * the new api.
2425 if (digest != Digest::NONE) {
2426 // Verify with OpenSSL.
2427 vector<uint8_t> pubkey;
2428 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2429
2430 const uint8_t* p = pubkey.data();
2431 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2432 ASSERT_TRUE(pkey.get());
2433
2434 EVP_MD_CTX digest_ctx;
2435 EVP_MD_CTX_init(&digest_ctx);
2436 EVP_PKEY_CTX* pkey_ctx;
2437 const EVP_MD* md = openssl_digest(digest);
2438 ASSERT_NE(md, nullptr);
2439 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2440 nullptr, pkey.get()));
2441
2442 switch (padding) {
2443 case PaddingMode::RSA_PSS:
2444 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2445 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2446 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2447 // PKCS1 is the default; don't need to set anything.
2448 break;
2449 default:
2450 FAIL();
2451 break;
2452 }
2453
2454 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2455 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2456 reinterpret_cast<const
2457 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2458 }
2459 */
2460
2461 // Corrupt signature shouldn't verify.
2462 string corrupt_signature(signature);
2463 ++corrupt_signature[corrupt_signature.size() / 2];
2464
2465 EXPECT_EQ(ErrorCode::OK,
2466 Begin(KeyPurpose::VERIFY,
2467 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2468 string result;
2469 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2470
2471 // Corrupt message shouldn't verify
2472 EXPECT_EQ(ErrorCode::OK,
2473 Begin(KeyPurpose::VERIFY,
2474 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2475 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2476 }
2477 }
2478}
2479
2480/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002481 * VerificationOperationsTest.RsaAllDigestsAndCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002482 *
2483 * Verifies ECDSA signature/verification for all digests and curves.
2484 */
2485TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2486 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2487
2488 string message = "1234567890";
2489 string corrupt_message = "2234567890";
2490 for (auto curve : ValidCurves()) {
2491 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2492 .Authorization(TAG_NO_AUTH_REQUIRED)
2493 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002494 .Digest(digests)
2495 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002496 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2497 if (error != ErrorCode::OK) {
2498 continue;
2499 }
2500
2501 for (auto digest : digests) {
2502 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2503 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2504
2505 /* TODO(seleneh) add exportkey tests back later when we have decided on
2506 * the new api.
2507
2508 // Verify with OpenSSL
2509 if (digest != Digest::NONE) {
2510 vector<uint8_t> pubkey;
2511 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2512 << curve << ' ' << digest;
2513
2514 const uint8_t* p = pubkey.data();
2515 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2516 ASSERT_TRUE(pkey.get());
2517
2518 EVP_MD_CTX digest_ctx;
2519 EVP_MD_CTX_init(&digest_ctx);
2520 EVP_PKEY_CTX* pkey_ctx;
2521 const EVP_MD* md = openssl_digest(digest);
2522
2523 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2524 nullptr, pkey.get()))
2525 << curve << ' ' << digest;
2526
2527 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2528 message.size()))
2529 << curve << ' ' << digest;
2530
2531 EXPECT_EQ(1,
2532 EVP_DigestVerifyFinal(&digest_ctx,
2533 reinterpret_cast<const
2534 uint8_t*>(signature.data()), signature.size()))
2535 << curve << ' ' << digest;
2536
2537 EVP_MD_CTX_cleanup(&digest_ctx);
2538 }
2539 */
2540 // Corrupt signature shouldn't verify.
2541 string corrupt_signature(signature);
2542 ++corrupt_signature[corrupt_signature.size() / 2];
2543
2544 EXPECT_EQ(ErrorCode::OK,
2545 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2546 << curve << ' ' << digest;
2547
2548 string result;
2549 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2550 << curve << ' ' << digest;
2551
2552 // Corrupt message shouldn't verify
2553 EXPECT_EQ(ErrorCode::OK,
2554 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2555 << curve << ' ' << digest;
2556
2557 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2558 << curve << ' ' << digest;
2559 }
2560
2561 auto rc = DeleteKey();
2562 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2563 }
2564}
2565
2566/*
2567 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2568 *
2569 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2570 */
2571TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2572 string key_material = "HelloThisIsAKey";
2573
2574 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002575 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002576 EXPECT_EQ(ErrorCode::OK,
2577 ImportKey(AuthorizationSetBuilder()
2578 .Authorization(TAG_NO_AUTH_REQUIRED)
2579 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2580 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2581 .Digest(Digest::SHA_2_256)
2582 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2583 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2584 EXPECT_EQ(ErrorCode::OK,
2585 ImportKey(AuthorizationSetBuilder()
2586 .Authorization(TAG_NO_AUTH_REQUIRED)
2587 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2588 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2589 .Digest(Digest::SHA_2_256)
2590 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2591 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2592
2593 string message = "This is a message.";
2594 string signature = SignMessage(
2595 signing_key, message,
2596 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2597
2598 // Signing key should not work.
2599 AuthorizationSet out_params;
2600 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2601 Begin(KeyPurpose::VERIFY, signing_key,
2602 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2603
2604 // Verification key should work.
2605 VerifyMessage(verification_key, message, signature,
2606 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2607
2608 CheckedDeleteKey(&signing_key);
2609 CheckedDeleteKey(&verification_key);
2610}
2611
2612INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2613
2614typedef KeyMintAidlTestBase ExportKeyTest;
2615
2616/*
2617 * ExportKeyTest.RsaUnsupportedKeyFormat
2618 *
2619 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2620 */
2621// TODO(seleneh) add ExportKey to GenerateKey
2622// check result
2623
2624class ImportKeyTest : public KeyMintAidlTestBase {
2625 public:
2626 template <TagType tag_type, Tag tag, typename ValueT>
2627 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2628 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002629 for (auto& entry : key_characteristics_) {
2630 if (entry.securityLevel == SecLevel()) {
2631 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2632 << "Tag " << tag << " with value " << expected
2633 << " not found at security level" << entry.securityLevel;
2634 } else {
2635 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2636 << "Tag " << tag << " found at security level " << entry.securityLevel;
2637 }
Selene Huang31ab4042020-04-29 04:22:39 -07002638 }
2639 }
2640
2641 void CheckOrigin() {
2642 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002643 // Origin isn't a crypto param, but it always lives with them.
2644 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002645 }
2646};
2647
2648/*
2649 * ImportKeyTest.RsaSuccess
2650 *
2651 * Verifies that importing and using an RSA key pair works correctly.
2652 */
2653TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002654 uint32_t key_size;
2655 string key;
2656
2657 if (SecLevel() == SecurityLevel::STRONGBOX) {
2658 key_size = 2048;
2659 key = rsa_2048_key;
2660 } else {
2661 key_size = 1024;
2662 key = rsa_key;
2663 }
2664
Selene Huang31ab4042020-04-29 04:22:39 -07002665 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2666 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07002667 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07002668 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002669 .Padding(PaddingMode::RSA_PSS)
2670 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07002671 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07002672
2673 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07002674 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002675 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2676 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2677 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2678 CheckOrigin();
2679
2680 string message(1024 / 8, 'a');
2681 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2682 string signature = SignMessage(message, params);
2683 VerifyMessage(message, signature, params);
2684}
2685
2686/*
2687 * ImportKeyTest.RsaKeySizeMismatch
2688 *
2689 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2690 * correct way.
2691 */
2692TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2693 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2694 ImportKey(AuthorizationSetBuilder()
2695 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2696 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002697 .Padding(PaddingMode::NONE)
2698 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002699 KeyFormat::PKCS8, rsa_key));
2700}
2701
2702/*
2703 * ImportKeyTest.RsaPublicExponentMismatch
2704 *
2705 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
2706 * fails in the correct way.
2707 */
2708TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2709 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2710 ImportKey(AuthorizationSetBuilder()
2711 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2712 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002713 .Padding(PaddingMode::NONE)
2714 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002715 KeyFormat::PKCS8, rsa_key));
2716}
2717
2718/*
2719 * ImportKeyTest.EcdsaSuccess
2720 *
2721 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2722 */
2723TEST_P(ImportKeyTest, EcdsaSuccess) {
2724 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2725 .Authorization(TAG_NO_AUTH_REQUIRED)
2726 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002727 .Digest(Digest::SHA_2_256)
2728 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002729 KeyFormat::PKCS8, ec_256_key));
2730
2731 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2732 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2733 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2734 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2735
2736 CheckOrigin();
2737
2738 string message(32, 'a');
2739 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2740 string signature = SignMessage(message, params);
2741 VerifyMessage(message, signature, params);
2742}
2743
2744/*
2745 * ImportKeyTest.EcdsaP256RFC5915Success
2746 *
2747 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
2748 * correctly.
2749 */
2750TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
2751 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002754 .Digest(Digest::SHA_2_256)
2755 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002756 KeyFormat::PKCS8, ec_256_key_rfc5915));
2757
2758 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2759 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2760 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2761 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2762
2763 CheckOrigin();
2764
2765 string message(32, 'a');
2766 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2767 string signature = SignMessage(message, params);
2768 VerifyMessage(message, signature, params);
2769}
2770
2771/*
2772 * ImportKeyTest.EcdsaP256SEC1Success
2773 *
2774 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
2775 */
2776TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
2777 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2778 .Authorization(TAG_NO_AUTH_REQUIRED)
2779 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002780 .Digest(Digest::SHA_2_256)
2781 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002782 KeyFormat::PKCS8, ec_256_key_sec1));
2783
2784 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2785 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2786 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2787 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2788
2789 CheckOrigin();
2790
2791 string message(32, 'a');
2792 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2793 string signature = SignMessage(message, params);
2794 VerifyMessage(message, signature, params);
2795}
2796
2797/*
2798 * ImportKeyTest.Ecdsa521Success
2799 *
2800 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2801 */
2802TEST_P(ImportKeyTest, Ecdsa521Success) {
2803 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2804 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2805 .Authorization(TAG_NO_AUTH_REQUIRED)
2806 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002807 .Digest(Digest::SHA_2_256)
2808 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002809 KeyFormat::PKCS8, ec_521_key));
2810
2811 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2812 CheckCryptoParam(TAG_KEY_SIZE, 521U);
2813 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2814 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2815 CheckOrigin();
2816
2817 string message(32, 'a');
2818 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2819 string signature = SignMessage(message, params);
2820 VerifyMessage(message, signature, params);
2821}
2822
2823/*
2824 * ImportKeyTest.EcdsaSizeMismatch
2825 *
2826 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2827 * correct way.
2828 */
2829TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2830 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2831 ImportKey(AuthorizationSetBuilder()
2832 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002833 .Digest(Digest::NONE)
2834 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002835 KeyFormat::PKCS8, ec_256_key));
2836}
2837
2838/*
2839 * ImportKeyTest.EcdsaCurveMismatch
2840 *
2841 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
2842 * the correct way.
2843 */
2844TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2845 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2846 ImportKey(AuthorizationSetBuilder()
2847 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002848 .Digest(Digest::NONE)
2849 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002850 KeyFormat::PKCS8, ec_256_key));
2851}
2852
2853/*
2854 * ImportKeyTest.AesSuccess
2855 *
2856 * Verifies that importing and using an AES key works.
2857 */
2858TEST_P(ImportKeyTest, AesSuccess) {
2859 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2860 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2861 .Authorization(TAG_NO_AUTH_REQUIRED)
2862 .AesEncryptionKey(key.size() * 8)
2863 .EcbMode()
2864 .Padding(PaddingMode::PKCS7),
2865 KeyFormat::RAW, key));
2866
2867 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2868 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2869 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2870 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2871 CheckOrigin();
2872
2873 string message = "Hello World!";
2874 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2875 string ciphertext = EncryptMessage(message, params);
2876 string plaintext = DecryptMessage(ciphertext, params);
2877 EXPECT_EQ(message, plaintext);
2878}
2879
2880/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002881 * ImportKeyTest.AesFailure
2882 *
2883 * Verifies that importing an invalid AES key fails.
2884 */
2885TEST_P(ImportKeyTest, AesFailure) {
2886 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2887 uint32_t bitlen = key.size() * 8;
2888 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
Tommy Chiu3950b452021-05-03 22:01:46 +08002889 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00002890 .Authorization(TAG_NO_AUTH_REQUIRED)
2891 .AesEncryptionKey(key_size)
2892 .EcbMode()
2893 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08002894 KeyFormat::RAW, key);
2895 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
2896 result == ErrorCode::UNSUPPORTED_KEY_SIZE);
David Drysdale7de9feb2021-03-05 14:56:19 +00002897 }
2898}
2899
2900/*
2901 * ImportKeyTest.TripleDesSuccess
2902 *
2903 * Verifies that importing and using a 3DES key works.
2904 */
2905TEST_P(ImportKeyTest, TripleDesSuccess) {
2906 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
2907 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2908 .Authorization(TAG_NO_AUTH_REQUIRED)
2909 .TripleDesEncryptionKey(168)
2910 .EcbMode()
2911 .Padding(PaddingMode::PKCS7),
2912 KeyFormat::RAW, key));
2913
2914 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
2915 CheckCryptoParam(TAG_KEY_SIZE, 168U);
2916 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2917 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2918 CheckOrigin();
2919
2920 string message = "Hello World!";
2921 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2922 string ciphertext = EncryptMessage(message, params);
2923 string plaintext = DecryptMessage(ciphertext, params);
2924 EXPECT_EQ(message, plaintext);
2925}
2926
2927/*
2928 * ImportKeyTest.TripleDesFailure
2929 *
2930 * Verifies that importing an invalid 3DES key fails.
2931 */
2932TEST_P(ImportKeyTest, TripleDesFailure) {
2933 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
2934 uint32_t bitlen = key.size() * 8;
2935 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
Tommy Chiu3950b452021-05-03 22:01:46 +08002936 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00002937 .Authorization(TAG_NO_AUTH_REQUIRED)
2938 .TripleDesEncryptionKey(key_size)
2939 .EcbMode()
2940 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08002941 KeyFormat::RAW, key);
2942 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
2943 result == ErrorCode::UNSUPPORTED_KEY_SIZE);
David Drysdale7de9feb2021-03-05 14:56:19 +00002944 }
2945}
2946
2947/*
2948 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07002949 *
2950 * Verifies that importing and using an HMAC key works.
2951 */
2952TEST_P(ImportKeyTest, HmacKeySuccess) {
2953 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2954 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2955 .Authorization(TAG_NO_AUTH_REQUIRED)
2956 .HmacKey(key.size() * 8)
2957 .Digest(Digest::SHA_2_256)
2958 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2959 KeyFormat::RAW, key));
2960
2961 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2962 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2963 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2964 CheckOrigin();
2965
2966 string message = "Hello World!";
2967 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2968 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2969}
2970
2971INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
2972
2973auto wrapped_key = hex2str(
2974 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
2975 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
2976 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
2977 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
2978 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
2979 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
2980 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
2981 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
2982 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
2983
2984auto wrapped_key_masked = hex2str(
2985 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
2986 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
2987 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
2988 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
2989 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
2990 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
2991 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
2992 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
2993 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
2994
2995auto wrapping_key = hex2str(
2996 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
2997 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
2998 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
2999 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
3000 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
3001 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
3002 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
3003 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
3004 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
3005 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
3006 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
3007 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
3008 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
3009 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
3010 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
3011 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
3012 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
3013 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
3014 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
3015 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
3016 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
3017 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
3018 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
3019 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
3020 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
3021 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
3022 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
3023 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
3024 "f27ba61be6ad02dfddda8f4e6822");
3025
3026string zero_masking_key =
3027 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3028string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3029
3030class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3031
3032TEST_P(ImportWrappedKeyTest, Success) {
3033 auto wrapping_key_desc = AuthorizationSetBuilder()
3034 .RsaEncryptionKey(2048, 65537)
3035 .Digest(Digest::SHA_2_256)
3036 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003037 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3038 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003039
3040 ASSERT_EQ(ErrorCode::OK,
3041 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3042 AuthorizationSetBuilder()
3043 .Digest(Digest::SHA_2_256)
3044 .Padding(PaddingMode::RSA_OAEP)));
3045
3046 string message = "Hello World!";
3047 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3048 string ciphertext = EncryptMessage(message, params);
3049 string plaintext = DecryptMessage(ciphertext, params);
3050 EXPECT_EQ(message, plaintext);
3051}
3052
3053TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3054 auto wrapping_key_desc = AuthorizationSetBuilder()
3055 .RsaEncryptionKey(2048, 65537)
3056 .Digest(Digest::SHA_2_256)
3057 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003058 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3059 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003060
3061 ASSERT_EQ(ErrorCode::OK,
3062 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3063 AuthorizationSetBuilder()
3064 .Digest(Digest::SHA_2_256)
3065 .Padding(PaddingMode::RSA_OAEP)));
3066}
3067
3068TEST_P(ImportWrappedKeyTest, WrongMask) {
3069 auto wrapping_key_desc = AuthorizationSetBuilder()
3070 .RsaEncryptionKey(2048, 65537)
3071 .Digest(Digest::SHA_2_256)
3072 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003073 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3074 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003075
3076 ASSERT_EQ(
3077 ErrorCode::VERIFICATION_FAILED,
3078 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3079 AuthorizationSetBuilder()
3080 .Digest(Digest::SHA_2_256)
3081 .Padding(PaddingMode::RSA_OAEP)));
3082}
3083
3084TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3085 auto wrapping_key_desc = AuthorizationSetBuilder()
3086 .RsaEncryptionKey(2048, 65537)
3087 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003088 .Padding(PaddingMode::RSA_OAEP)
3089 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003090
3091 ASSERT_EQ(
3092 ErrorCode::INCOMPATIBLE_PURPOSE,
3093 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3094 AuthorizationSetBuilder()
3095 .Digest(Digest::SHA_2_256)
3096 .Padding(PaddingMode::RSA_OAEP)));
3097}
3098
3099INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3100
3101typedef KeyMintAidlTestBase EncryptionOperationsTest;
3102
3103/*
3104 * EncryptionOperationsTest.RsaNoPaddingSuccess
3105 *
3106 * Verifies that raw RSA encryption works.
3107 */
3108TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
3109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3110 .Authorization(TAG_NO_AUTH_REQUIRED)
3111 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003112 .Padding(PaddingMode::NONE)
3113 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003114
3115 string message = string(2048 / 8, 'a');
3116 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3117 string ciphertext1 = EncryptMessage(message, params);
3118 EXPECT_EQ(2048U / 8, ciphertext1.size());
3119
3120 string ciphertext2 = EncryptMessage(message, params);
3121 EXPECT_EQ(2048U / 8, ciphertext2.size());
3122
3123 // Unpadded RSA is deterministic
3124 EXPECT_EQ(ciphertext1, ciphertext2);
3125}
3126
3127/*
3128 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3129 *
3130 * Verifies that raw RSA encryption of short messages works.
3131 */
3132TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3133 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3134 .Authorization(TAG_NO_AUTH_REQUIRED)
3135 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003136 .Padding(PaddingMode::NONE)
3137 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003138
3139 string message = "1";
3140 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3141
3142 string ciphertext = EncryptMessage(message, params);
3143 EXPECT_EQ(2048U / 8, ciphertext.size());
3144
3145 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3146 string plaintext = DecryptMessage(ciphertext, params);
3147
3148 EXPECT_EQ(expected_plaintext, plaintext);
3149
3150 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
3151 message = static_cast<char>(1);
3152 ciphertext = EncryptMessage(message, params);
3153 EXPECT_EQ(2048U / 8, ciphertext.size());
3154 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
3155}
3156
3157/*
3158 * EncryptionOperationsTest.RsaNoPaddingTooLong
3159 *
3160 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
3161 */
3162TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
3163 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3164 .Authorization(TAG_NO_AUTH_REQUIRED)
3165 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003166 .Padding(PaddingMode::NONE)
3167 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003168
3169 string message(2048 / 8 + 1, 'a');
3170
3171 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3172 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3173
3174 string result;
3175 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
3176}
3177
3178/*
3179 * EncryptionOperationsTest.RsaNoPaddingTooLarge
3180 *
3181 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
3182 * way.
3183 */
3184// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
3185// version of ExportKey inside generateKey
3186
3187/*
3188 * EncryptionOperationsTest.RsaOaepSuccess
3189 *
3190 * Verifies that RSA-OAEP encryption operations work, with all digests.
3191 */
3192TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3193 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3194
3195 size_t key_size = 2048; // Need largish key for SHA-512 test.
3196 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3197 .Authorization(TAG_NO_AUTH_REQUIRED)
3198 .RsaEncryptionKey(key_size, 65537)
3199 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003200 .Digest(digests)
3201 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003202
3203 string message = "Hello";
3204
3205 for (auto digest : digests) {
3206 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
3207 string ciphertext1 = EncryptMessage(message, params);
3208 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3209 EXPECT_EQ(key_size / 8, ciphertext1.size());
3210
3211 string ciphertext2 = EncryptMessage(message, params);
3212 EXPECT_EQ(key_size / 8, ciphertext2.size());
3213
3214 // OAEP randomizes padding so every result should be different (with astronomically high
3215 // probability).
3216 EXPECT_NE(ciphertext1, ciphertext2);
3217
3218 string plaintext1 = DecryptMessage(ciphertext1, params);
3219 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3220 string plaintext2 = DecryptMessage(ciphertext2, params);
3221 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3222
3223 // Decrypting corrupted ciphertext should fail.
3224 size_t offset_to_corrupt = random() % ciphertext1.size();
3225 char corrupt_byte;
3226 do {
3227 corrupt_byte = static_cast<char>(random() % 256);
3228 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3229 ciphertext1[offset_to_corrupt] = corrupt_byte;
3230
3231 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3232 string result;
3233 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3234 EXPECT_EQ(0U, result.size());
3235 }
3236}
3237
3238/*
3239 * EncryptionOperationsTest.RsaOaepInvalidDigest
3240 *
3241 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3242 * without a digest.
3243 */
3244TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3245 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3246 .Authorization(TAG_NO_AUTH_REQUIRED)
3247 .RsaEncryptionKey(2048, 65537)
3248 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003249 .Digest(Digest::NONE)
3250 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003251 string message = "Hello World!";
3252
3253 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
3254 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3255}
3256
3257/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003258 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003259 *
3260 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
3261 * with a different digest than was used to encrypt.
3262 */
3263TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3264 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3265
3266 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3267 .Authorization(TAG_NO_AUTH_REQUIRED)
3268 .RsaEncryptionKey(1024, 65537)
3269 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003270 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3271 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003272 string message = "Hello World!";
3273 string ciphertext = EncryptMessage(
3274 message,
3275 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3276
3277 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3278 .Digest(Digest::SHA_2_256)
3279 .Padding(PaddingMode::RSA_OAEP)));
3280 string result;
3281 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3282 EXPECT_EQ(0U, result.size());
3283}
3284
3285/*
3286 * EncryptionOperationsTest.RsaOaepTooLarge
3287 *
3288 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
3289 * too-large message.
3290 */
3291TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
3292 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3293 .Authorization(TAG_NO_AUTH_REQUIRED)
3294 .RsaEncryptionKey(2048, 65537)
3295 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003296 .Digest(Digest::SHA_2_256)
3297 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003298 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
3299 constexpr size_t oaep_overhead = 2 * digest_size + 2;
3300 string message(2048 / 8 - oaep_overhead + 1, 'a');
3301 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3302 .Padding(PaddingMode::RSA_OAEP)
3303 .Digest(Digest::SHA_2_256)));
3304 string result;
3305 ErrorCode error = Finish(message, &result);
3306 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3307 EXPECT_EQ(0U, result.size());
3308}
3309
3310/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003311 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3312 *
3313 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
3314 * digests.
3315 */
3316TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3317 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3318
3319 size_t key_size = 2048; // Need largish key for SHA-512 test.
3320 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3321 .OaepMGFDigest(digests)
3322 .Authorization(TAG_NO_AUTH_REQUIRED)
3323 .RsaEncryptionKey(key_size, 65537)
3324 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003325 .Digest(Digest::SHA_2_256)
3326 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003327
3328 string message = "Hello";
3329
3330 for (auto digest : digests) {
3331 auto params = AuthorizationSetBuilder()
3332 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3333 .Digest(Digest::SHA_2_256)
3334 .Padding(PaddingMode::RSA_OAEP);
3335 string ciphertext1 = EncryptMessage(message, params);
3336 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3337 EXPECT_EQ(key_size / 8, ciphertext1.size());
3338
3339 string ciphertext2 = EncryptMessage(message, params);
3340 EXPECT_EQ(key_size / 8, ciphertext2.size());
3341
3342 // OAEP randomizes padding so every result should be different (with astronomically high
3343 // probability).
3344 EXPECT_NE(ciphertext1, ciphertext2);
3345
3346 string plaintext1 = DecryptMessage(ciphertext1, params);
3347 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3348 string plaintext2 = DecryptMessage(ciphertext2, params);
3349 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3350
3351 // Decrypting corrupted ciphertext should fail.
3352 size_t offset_to_corrupt = random() % ciphertext1.size();
3353 char corrupt_byte;
3354 do {
3355 corrupt_byte = static_cast<char>(random() % 256);
3356 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3357 ciphertext1[offset_to_corrupt] = corrupt_byte;
3358
3359 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3360 string result;
3361 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3362 EXPECT_EQ(0U, result.size());
3363 }
3364}
3365
3366/*
3367 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3368 *
3369 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3370 * with incompatible MGF digest.
3371 */
3372TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3373 ASSERT_EQ(ErrorCode::OK,
3374 GenerateKey(AuthorizationSetBuilder()
3375 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3376 .Authorization(TAG_NO_AUTH_REQUIRED)
3377 .RsaEncryptionKey(2048, 65537)
3378 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003379 .Digest(Digest::SHA_2_256)
3380 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003381 string message = "Hello World!";
3382
3383 auto params = AuthorizationSetBuilder()
3384 .Padding(PaddingMode::RSA_OAEP)
3385 .Digest(Digest::SHA_2_256)
3386 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
3387 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3388}
3389
3390/*
3391 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
3392 *
3393 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3394 * with unsupported MGF digest.
3395 */
3396TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
3397 ASSERT_EQ(ErrorCode::OK,
3398 GenerateKey(AuthorizationSetBuilder()
3399 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3400 .Authorization(TAG_NO_AUTH_REQUIRED)
3401 .RsaEncryptionKey(2048, 65537)
3402 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003403 .Digest(Digest::SHA_2_256)
3404 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003405 string message = "Hello World!";
3406
3407 auto params = AuthorizationSetBuilder()
3408 .Padding(PaddingMode::RSA_OAEP)
3409 .Digest(Digest::SHA_2_256)
3410 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
3411 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3412}
3413
3414/*
Selene Huang31ab4042020-04-29 04:22:39 -07003415 * EncryptionOperationsTest.RsaPkcs1Success
3416 *
3417 * Verifies that RSA PKCS encryption/decrypts works.
3418 */
3419TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
3420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3421 .Authorization(TAG_NO_AUTH_REQUIRED)
3422 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003423 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3424 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003425
3426 string message = "Hello World!";
3427 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3428 string ciphertext1 = EncryptMessage(message, params);
3429 EXPECT_EQ(2048U / 8, ciphertext1.size());
3430
3431 string ciphertext2 = EncryptMessage(message, params);
3432 EXPECT_EQ(2048U / 8, ciphertext2.size());
3433
3434 // PKCS1 v1.5 randomizes padding so every result should be different.
3435 EXPECT_NE(ciphertext1, ciphertext2);
3436
3437 string plaintext = DecryptMessage(ciphertext1, params);
3438 EXPECT_EQ(message, plaintext);
3439
3440 // Decrypting corrupted ciphertext should fail.
3441 size_t offset_to_corrupt = random() % ciphertext1.size();
3442 char corrupt_byte;
3443 do {
3444 corrupt_byte = static_cast<char>(random() % 256);
3445 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3446 ciphertext1[offset_to_corrupt] = corrupt_byte;
3447
3448 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3449 string result;
3450 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3451 EXPECT_EQ(0U, result.size());
3452}
3453
3454/*
3455 * EncryptionOperationsTest.RsaPkcs1TooLarge
3456 *
3457 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
3458 */
3459TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
3460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3461 .Authorization(TAG_NO_AUTH_REQUIRED)
3462 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003463 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3464 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003465 string message(2048 / 8 - 10, 'a');
3466
3467 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3468 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3469 string result;
3470 ErrorCode error = Finish(message, &result);
3471 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3472 EXPECT_EQ(0U, result.size());
3473}
3474
3475/*
3476 * EncryptionOperationsTest.EcdsaEncrypt
3477 *
3478 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
3479 */
3480TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
3481 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3482 .Authorization(TAG_NO_AUTH_REQUIRED)
3483 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003484 .Digest(Digest::NONE)
3485 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003486 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3487 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3488 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3489}
3490
3491/*
3492 * EncryptionOperationsTest.HmacEncrypt
3493 *
3494 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
3495 */
3496TEST_P(EncryptionOperationsTest, HmacEncrypt) {
3497 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3498 .Authorization(TAG_NO_AUTH_REQUIRED)
3499 .HmacKey(128)
3500 .Digest(Digest::SHA_2_256)
3501 .Padding(PaddingMode::NONE)
3502 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3503 auto params = AuthorizationSetBuilder()
3504 .Digest(Digest::SHA_2_256)
3505 .Padding(PaddingMode::NONE)
3506 .Authorization(TAG_MAC_LENGTH, 128);
3507 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3508 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3509}
3510
3511/*
3512 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3513 *
3514 * Verifies that AES ECB mode works.
3515 */
3516TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
3517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3518 .Authorization(TAG_NO_AUTH_REQUIRED)
3519 .AesEncryptionKey(128)
3520 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3521 .Padding(PaddingMode::NONE)));
3522
3523 ASSERT_GT(key_blob_.size(), 0U);
3524 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3525
3526 // Two-block message.
3527 string message = "12345678901234567890123456789012";
3528 string ciphertext1 = EncryptMessage(message, params);
3529 EXPECT_EQ(message.size(), ciphertext1.size());
3530
3531 string ciphertext2 = EncryptMessage(string(message), params);
3532 EXPECT_EQ(message.size(), ciphertext2.size());
3533
3534 // ECB is deterministic.
3535 EXPECT_EQ(ciphertext1, ciphertext2);
3536
3537 string plaintext = DecryptMessage(ciphertext1, params);
3538 EXPECT_EQ(message, plaintext);
3539}
3540
3541/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003542 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07003543 *
3544 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
3545 */
3546TEST_P(EncryptionOperationsTest, AesWrongMode) {
3547 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3548 .Authorization(TAG_NO_AUTH_REQUIRED)
3549 .AesEncryptionKey(128)
3550 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3551 .Padding(PaddingMode::NONE)));
3552
3553 ASSERT_GT(key_blob_.size(), 0U);
3554
3555 // Two-block message.
3556 string message = "12345678901234567890123456789012";
3557 EXPECT_EQ(
3558 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
3559 Begin(KeyPurpose::ENCRYPT,
3560 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
3561}
3562
3563/*
3564 * EncryptionOperationsTest.AesWrongPurpose
3565 *
3566 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
3567 * specified.
3568 */
3569TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
3570 auto err = GenerateKey(AuthorizationSetBuilder()
3571 .Authorization(TAG_NO_AUTH_REQUIRED)
3572 .AesKey(128)
3573 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
3574 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3575 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3576 .Padding(PaddingMode::NONE));
3577 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
3578 ASSERT_GT(key_blob_.size(), 0U);
3579
3580 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3581 .BlockMode(BlockMode::GCM)
3582 .Padding(PaddingMode::NONE)
3583 .Authorization(TAG_MAC_LENGTH, 128));
3584 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3585
3586 CheckedDeleteKey();
3587
3588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3589 .Authorization(TAG_NO_AUTH_REQUIRED)
3590 .AesKey(128)
3591 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
3592 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3593 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3594 .Padding(PaddingMode::NONE)));
3595
3596 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3597 .BlockMode(BlockMode::GCM)
3598 .Padding(PaddingMode::NONE)
3599 .Authorization(TAG_MAC_LENGTH, 128));
3600 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3601}
3602
3603/*
3604 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
3605 *
3606 * Verifies that AES encryption fails in the correct way when provided an input that is not a
3607 * multiple of the block size and no padding is specified.
3608 */
3609TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
3610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3611 .Authorization(TAG_NO_AUTH_REQUIRED)
3612 .AesEncryptionKey(128)
3613 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3614 .Padding(PaddingMode::NONE)));
3615 // Message is slightly shorter than two blocks.
3616 string message(16 * 2 - 1, 'a');
3617
3618 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3619 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3620 string ciphertext;
3621 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
3622 EXPECT_EQ(0U, ciphertext.size());
3623}
3624
3625/*
3626 * EncryptionOperationsTest.AesEcbPkcs7Padding
3627 *
3628 * Verifies that AES PKCS7 padding works for any message length.
3629 */
3630TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
3631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3632 .Authorization(TAG_NO_AUTH_REQUIRED)
3633 .AesEncryptionKey(128)
3634 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3635 .Padding(PaddingMode::PKCS7)));
3636
3637 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3638
3639 // Try various message lengths; all should work.
3640 for (size_t i = 0; i < 32; ++i) {
3641 string message(i, 'a');
3642 string ciphertext = EncryptMessage(message, params);
3643 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
3644 string plaintext = DecryptMessage(ciphertext, params);
3645 EXPECT_EQ(message, plaintext);
3646 }
3647}
3648
3649/*
3650 * EncryptionOperationsTest.AesEcbWrongPadding
3651 *
3652 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
3653 * specified.
3654 */
3655TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
3656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3657 .Authorization(TAG_NO_AUTH_REQUIRED)
3658 .AesEncryptionKey(128)
3659 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3660 .Padding(PaddingMode::NONE)));
3661
3662 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3663
3664 // Try various message lengths; all should fail
3665 for (size_t i = 0; i < 32; ++i) {
3666 string message(i, 'a');
3667 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3668 }
3669}
3670
3671/*
3672 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
3673 *
3674 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
3675 */
3676TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
3677 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3678 .Authorization(TAG_NO_AUTH_REQUIRED)
3679 .AesEncryptionKey(128)
3680 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3681 .Padding(PaddingMode::PKCS7)));
3682
3683 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3684
3685 string message = "a";
3686 string ciphertext = EncryptMessage(message, params);
3687 EXPECT_EQ(16U, ciphertext.size());
3688 EXPECT_NE(ciphertext, message);
3689 ++ciphertext[ciphertext.size() / 2];
3690
3691 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3692 string plaintext;
3693 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3694}
3695
3696vector<uint8_t> CopyIv(const AuthorizationSet& set) {
3697 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003698 EXPECT_TRUE(iv);
3699 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07003700}
3701
3702/*
3703 * EncryptionOperationsTest.AesCtrRoundTripSuccess
3704 *
3705 * Verifies that AES CTR mode works.
3706 */
3707TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3709 .Authorization(TAG_NO_AUTH_REQUIRED)
3710 .AesEncryptionKey(128)
3711 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3712 .Padding(PaddingMode::NONE)));
3713
3714 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3715
3716 string message = "123";
3717 AuthorizationSet out_params;
3718 string ciphertext1 = EncryptMessage(message, params, &out_params);
3719 vector<uint8_t> iv1 = CopyIv(out_params);
3720 EXPECT_EQ(16U, iv1.size());
3721
3722 EXPECT_EQ(message.size(), ciphertext1.size());
3723
3724 out_params.Clear();
3725 string ciphertext2 = EncryptMessage(message, params, &out_params);
3726 vector<uint8_t> iv2 = CopyIv(out_params);
3727 EXPECT_EQ(16U, iv2.size());
3728
3729 // IVs should be random, so ciphertexts should differ.
3730 EXPECT_NE(ciphertext1, ciphertext2);
3731
3732 auto params_iv1 =
3733 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3734 auto params_iv2 =
3735 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3736
3737 string plaintext = DecryptMessage(ciphertext1, params_iv1);
3738 EXPECT_EQ(message, plaintext);
3739 plaintext = DecryptMessage(ciphertext2, params_iv2);
3740 EXPECT_EQ(message, plaintext);
3741
3742 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3743 plaintext = DecryptMessage(ciphertext1, params_iv2);
3744 EXPECT_NE(message, plaintext);
3745 plaintext = DecryptMessage(ciphertext2, params_iv1);
3746 EXPECT_NE(message, plaintext);
3747}
3748
3749/*
3750 * EncryptionOperationsTest.AesIncremental
3751 *
3752 * Verifies that AES works, all modes, when provided data in various size increments.
3753 */
3754TEST_P(EncryptionOperationsTest, AesIncremental) {
3755 auto block_modes = {
3756 BlockMode::ECB,
3757 BlockMode::CBC,
3758 BlockMode::CTR,
3759 BlockMode::GCM,
3760 };
3761
3762 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3763 .Authorization(TAG_NO_AUTH_REQUIRED)
3764 .AesEncryptionKey(128)
3765 .BlockMode(block_modes)
3766 .Padding(PaddingMode::NONE)
3767 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3768
3769 for (int increment = 1; increment <= 240; ++increment) {
3770 for (auto block_mode : block_modes) {
3771 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07003772 auto params =
3773 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
3774 if (block_mode == BlockMode::GCM) {
3775 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3776 }
Selene Huang31ab4042020-04-29 04:22:39 -07003777
3778 AuthorizationSet output_params;
3779 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3780
3781 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07003782 string to_send;
3783 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003784 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003785 }
Shawn Willden92d79c02021-02-19 07:31:55 -07003786 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
3787 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07003788
3789 switch (block_mode) {
3790 case BlockMode::GCM:
3791 EXPECT_EQ(message.size() + 16, ciphertext.size());
3792 break;
3793 case BlockMode::CTR:
3794 EXPECT_EQ(message.size(), ciphertext.size());
3795 break;
3796 case BlockMode::CBC:
3797 case BlockMode::ECB:
3798 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3799 break;
3800 }
3801
3802 auto iv = output_params.GetTagValue(TAG_NONCE);
3803 switch (block_mode) {
3804 case BlockMode::CBC:
3805 case BlockMode::GCM:
3806 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003807 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
3808 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
3809 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003810 break;
3811
3812 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003813 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07003814 break;
3815 }
3816
3817 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3818 << "Decrypt begin() failed for block mode " << block_mode;
3819
3820 string plaintext;
3821 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003822 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003823 }
3824 ErrorCode error = Finish(to_send, &plaintext);
3825 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
3826 << " and increment " << increment;
3827 if (error == ErrorCode::OK) {
3828 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3829 << block_mode << " and increment " << increment;
3830 }
3831 }
3832 }
3833}
3834
3835struct AesCtrSp80038aTestVector {
3836 const char* key;
3837 const char* nonce;
3838 const char* plaintext;
3839 const char* ciphertext;
3840};
3841
3842// These test vectors are taken from
3843// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3844static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3845 // AES-128
3846 {
3847 "2b7e151628aed2a6abf7158809cf4f3c",
3848 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3849 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3850 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3851 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3852 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3853 },
3854 // AES-192
3855 {
3856 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
3857 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3858 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3859 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3860 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3861 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3862 },
3863 // AES-256
3864 {
3865 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3866 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3867 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3868 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3869 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3870 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3871 },
3872};
3873
3874/*
3875 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3876 *
3877 * Verifies AES CTR implementation against SP800-38A test vectors.
3878 */
3879TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3880 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3881 for (size_t i = 0; i < 3; i++) {
3882 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3883 const string key = hex2str(test.key);
3884 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3885 InvalidSizes.end())
3886 continue;
3887 const string nonce = hex2str(test.nonce);
3888 const string plaintext = hex2str(test.plaintext);
3889 const string ciphertext = hex2str(test.ciphertext);
3890 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3891 }
3892}
3893
3894/*
3895 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3896 *
3897 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
3898 */
3899TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3901 .Authorization(TAG_NO_AUTH_REQUIRED)
3902 .AesEncryptionKey(128)
3903 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3904 .Padding(PaddingMode::PKCS7)));
3905 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3906 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3907}
3908
3909/*
3910 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3911 *
3912 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3913 */
3914TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3916 .Authorization(TAG_NO_AUTH_REQUIRED)
3917 .AesEncryptionKey(128)
3918 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3919 .Authorization(TAG_CALLER_NONCE)
3920 .Padding(PaddingMode::NONE)));
3921
3922 auto params = AuthorizationSetBuilder()
3923 .BlockMode(BlockMode::CTR)
3924 .Padding(PaddingMode::NONE)
3925 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
3926 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3927
3928 params = AuthorizationSetBuilder()
3929 .BlockMode(BlockMode::CTR)
3930 .Padding(PaddingMode::NONE)
3931 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
3932 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3933
3934 params = AuthorizationSetBuilder()
3935 .BlockMode(BlockMode::CTR)
3936 .Padding(PaddingMode::NONE)
3937 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
3938 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3939}
3940
3941/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003942 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003943 *
3944 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3945 */
3946TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3948 .Authorization(TAG_NO_AUTH_REQUIRED)
3949 .AesEncryptionKey(128)
3950 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3951 .Padding(PaddingMode::NONE)));
3952 // Two-block message.
3953 string message = "12345678901234567890123456789012";
3954 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3955 AuthorizationSet out_params;
3956 string ciphertext1 = EncryptMessage(message, params, &out_params);
3957 vector<uint8_t> iv1 = CopyIv(out_params);
3958 EXPECT_EQ(message.size(), ciphertext1.size());
3959
3960 out_params.Clear();
3961
3962 string ciphertext2 = EncryptMessage(message, params, &out_params);
3963 vector<uint8_t> iv2 = CopyIv(out_params);
3964 EXPECT_EQ(message.size(), ciphertext2.size());
3965
3966 // IVs should be random, so ciphertexts should differ.
3967 EXPECT_NE(ciphertext1, ciphertext2);
3968
3969 params.push_back(TAG_NONCE, iv1);
3970 string plaintext = DecryptMessage(ciphertext1, params);
3971 EXPECT_EQ(message, plaintext);
3972}
3973
3974/*
3975 * EncryptionOperationsTest.AesCallerNonce
3976 *
3977 * Verifies that AES caller-provided nonces work correctly.
3978 */
3979TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3980 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3981 .Authorization(TAG_NO_AUTH_REQUIRED)
3982 .AesEncryptionKey(128)
3983 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3984 .Authorization(TAG_CALLER_NONCE)
3985 .Padding(PaddingMode::NONE)));
3986
3987 string message = "12345678901234567890123456789012";
3988
3989 // Don't specify nonce, should get a random one.
3990 AuthorizationSetBuilder params =
3991 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3992 AuthorizationSet out_params;
3993 string ciphertext = EncryptMessage(message, params, &out_params);
3994 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003995 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003996
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003997 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003998 string plaintext = DecryptMessage(ciphertext, params);
3999 EXPECT_EQ(message, plaintext);
4000
4001 // Now specify a nonce, should also work.
4002 params = AuthorizationSetBuilder()
4003 .BlockMode(BlockMode::CBC)
4004 .Padding(PaddingMode::NONE)
4005 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4006 out_params.Clear();
4007 ciphertext = EncryptMessage(message, params, &out_params);
4008
4009 // Decrypt with correct nonce.
4010 plaintext = DecryptMessage(ciphertext, params);
4011 EXPECT_EQ(message, plaintext);
4012
4013 // Try with wrong nonce.
4014 params = AuthorizationSetBuilder()
4015 .BlockMode(BlockMode::CBC)
4016 .Padding(PaddingMode::NONE)
4017 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4018 plaintext = DecryptMessage(ciphertext, params);
4019 EXPECT_NE(message, plaintext);
4020}
4021
4022/*
4023 * EncryptionOperationsTest.AesCallerNonceProhibited
4024 *
4025 * Verifies that caller-provided nonces are not permitted when not specified in the key
4026 * authorizations.
4027 */
4028TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4029 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4030 .Authorization(TAG_NO_AUTH_REQUIRED)
4031 .AesEncryptionKey(128)
4032 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4033 .Padding(PaddingMode::NONE)));
4034
4035 string message = "12345678901234567890123456789012";
4036
4037 // Don't specify nonce, should get a random one.
4038 AuthorizationSetBuilder params =
4039 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4040 AuthorizationSet out_params;
4041 string ciphertext = EncryptMessage(message, params, &out_params);
4042 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004043 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004044
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004045 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004046 string plaintext = DecryptMessage(ciphertext, params);
4047 EXPECT_EQ(message, plaintext);
4048
4049 // Now specify a nonce, should fail
4050 params = AuthorizationSetBuilder()
4051 .BlockMode(BlockMode::CBC)
4052 .Padding(PaddingMode::NONE)
4053 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4054 out_params.Clear();
4055 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4056}
4057
4058/*
4059 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4060 *
4061 * Verifies that AES GCM mode works.
4062 */
4063TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4064 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4065 .Authorization(TAG_NO_AUTH_REQUIRED)
4066 .AesEncryptionKey(128)
4067 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4068 .Padding(PaddingMode::NONE)
4069 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4070
4071 string aad = "foobar";
4072 string message = "123456789012345678901234567890123456";
4073
4074 auto begin_params = AuthorizationSetBuilder()
4075 .BlockMode(BlockMode::GCM)
4076 .Padding(PaddingMode::NONE)
4077 .Authorization(TAG_MAC_LENGTH, 128);
4078
Selene Huang31ab4042020-04-29 04:22:39 -07004079 // Encrypt
4080 AuthorizationSet begin_out_params;
4081 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4082 << "Begin encrypt";
4083 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004084 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4085 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004086 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4087
4088 // Grab nonce
4089 begin_params.push_back(begin_out_params);
4090
4091 // Decrypt.
4092 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004093 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004094 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004095 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004096 EXPECT_EQ(message.length(), plaintext.length());
4097 EXPECT_EQ(message, plaintext);
4098}
4099
4100/*
4101 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4102 *
4103 * Verifies that AES GCM mode works, even when there's a long delay
4104 * between operations.
4105 */
4106TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4107 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4108 .Authorization(TAG_NO_AUTH_REQUIRED)
4109 .AesEncryptionKey(128)
4110 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4111 .Padding(PaddingMode::NONE)
4112 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4113
4114 string aad = "foobar";
4115 string message = "123456789012345678901234567890123456";
4116
4117 auto begin_params = AuthorizationSetBuilder()
4118 .BlockMode(BlockMode::GCM)
4119 .Padding(PaddingMode::NONE)
4120 .Authorization(TAG_MAC_LENGTH, 128);
4121
Selene Huang31ab4042020-04-29 04:22:39 -07004122 // Encrypt
4123 AuthorizationSet begin_out_params;
4124 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4125 << "Begin encrypt";
4126 string ciphertext;
4127 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004128 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004129 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004130 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004131
4132 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4133
4134 // Grab nonce
4135 begin_params.push_back(begin_out_params);
4136
4137 // Decrypt.
4138 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4139 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004140 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004141 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004142 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004143 sleep(5);
4144 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4145 EXPECT_EQ(message.length(), plaintext.length());
4146 EXPECT_EQ(message, plaintext);
4147}
4148
4149/*
4150 * EncryptionOperationsTest.AesGcmDifferentNonces
4151 *
4152 * Verifies that encrypting the same data with different nonces produces different outputs.
4153 */
4154TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4156 .Authorization(TAG_NO_AUTH_REQUIRED)
4157 .AesEncryptionKey(128)
4158 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4159 .Padding(PaddingMode::NONE)
4160 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4161 .Authorization(TAG_CALLER_NONCE)));
4162
4163 string aad = "foobar";
4164 string message = "123456789012345678901234567890123456";
4165 string nonce1 = "000000000000";
4166 string nonce2 = "111111111111";
4167 string nonce3 = "222222222222";
4168
4169 string ciphertext1 =
4170 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4171 string ciphertext2 =
4172 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4173 string ciphertext3 =
4174 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4175
4176 ASSERT_NE(ciphertext1, ciphertext2);
4177 ASSERT_NE(ciphertext1, ciphertext3);
4178 ASSERT_NE(ciphertext2, ciphertext3);
4179}
4180
4181/*
4182 * EncryptionOperationsTest.AesGcmTooShortTag
4183 *
4184 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4185 */
4186TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4187 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4188 .Authorization(TAG_NO_AUTH_REQUIRED)
4189 .AesEncryptionKey(128)
4190 .BlockMode(BlockMode::GCM)
4191 .Padding(PaddingMode::NONE)
4192 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4193 string message = "123456789012345678901234567890123456";
4194 auto params = AuthorizationSetBuilder()
4195 .BlockMode(BlockMode::GCM)
4196 .Padding(PaddingMode::NONE)
4197 .Authorization(TAG_MAC_LENGTH, 96);
4198
4199 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4200}
4201
4202/*
4203 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4204 *
4205 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4206 */
4207TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4208 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4209 .Authorization(TAG_NO_AUTH_REQUIRED)
4210 .AesEncryptionKey(128)
4211 .BlockMode(BlockMode::GCM)
4212 .Padding(PaddingMode::NONE)
4213 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4214 string aad = "foobar";
4215 string message = "123456789012345678901234567890123456";
4216 auto params = AuthorizationSetBuilder()
4217 .BlockMode(BlockMode::GCM)
4218 .Padding(PaddingMode::NONE)
4219 .Authorization(TAG_MAC_LENGTH, 128);
4220
Selene Huang31ab4042020-04-29 04:22:39 -07004221 // Encrypt
4222 AuthorizationSet begin_out_params;
4223 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4224 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004225 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004226
4227 AuthorizationSet finish_out_params;
4228 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004229 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4230 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004231
4232 params = AuthorizationSetBuilder()
4233 .Authorizations(begin_out_params)
4234 .BlockMode(BlockMode::GCM)
4235 .Padding(PaddingMode::NONE)
4236 .Authorization(TAG_MAC_LENGTH, 96);
4237
4238 // Decrypt.
4239 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4240}
4241
4242/*
4243 * EncryptionOperationsTest.AesGcmCorruptKey
4244 *
4245 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4246 */
4247TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4248 const uint8_t nonce_bytes[] = {
4249 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4250 };
4251 string nonce = make_string(nonce_bytes);
4252 const uint8_t ciphertext_bytes[] = {
4253 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4254 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4255 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4256 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4257 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4258 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4259 };
4260 string ciphertext = make_string(ciphertext_bytes);
4261
4262 auto params = AuthorizationSetBuilder()
4263 .BlockMode(BlockMode::GCM)
4264 .Padding(PaddingMode::NONE)
4265 .Authorization(TAG_MAC_LENGTH, 128)
4266 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4267
4268 auto import_params = AuthorizationSetBuilder()
4269 .Authorization(TAG_NO_AUTH_REQUIRED)
4270 .AesEncryptionKey(128)
4271 .BlockMode(BlockMode::GCM)
4272 .Padding(PaddingMode::NONE)
4273 .Authorization(TAG_CALLER_NONCE)
4274 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4275
4276 // Import correct key and decrypt
4277 const uint8_t key_bytes[] = {
4278 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
4279 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
4280 };
4281 string key = make_string(key_bytes);
4282 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4283 string plaintext = DecryptMessage(ciphertext, params);
4284 CheckedDeleteKey();
4285
4286 // Corrupt key and attempt to decrypt
4287 key[0] = 0;
4288 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
4289 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4290 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
4291 CheckedDeleteKey();
4292}
4293
4294/*
4295 * EncryptionOperationsTest.AesGcmAadNoData
4296 *
4297 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
4298 * encrypt.
4299 */
4300TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
4301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4302 .Authorization(TAG_NO_AUTH_REQUIRED)
4303 .AesEncryptionKey(128)
4304 .BlockMode(BlockMode::GCM)
4305 .Padding(PaddingMode::NONE)
4306 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4307
4308 string aad = "1234567890123456";
4309 auto params = AuthorizationSetBuilder()
4310 .BlockMode(BlockMode::GCM)
4311 .Padding(PaddingMode::NONE)
4312 .Authorization(TAG_MAC_LENGTH, 128);
4313
Selene Huang31ab4042020-04-29 04:22:39 -07004314 // Encrypt
4315 AuthorizationSet begin_out_params;
4316 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4317 string ciphertext;
4318 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004319 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4320 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004321 EXPECT_TRUE(finish_out_params.empty());
4322
4323 // Grab nonce
4324 params.push_back(begin_out_params);
4325
4326 // Decrypt.
4327 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004328 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004329 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004330 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004331
4332 EXPECT_TRUE(finish_out_params.empty());
4333
4334 EXPECT_EQ("", plaintext);
4335}
4336
4337/*
4338 * EncryptionOperationsTest.AesGcmMultiPartAad
4339 *
4340 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
4341 * chunks.
4342 */
4343TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
4344 const size_t tag_bits = 128;
4345 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4346 .Authorization(TAG_NO_AUTH_REQUIRED)
4347 .AesEncryptionKey(128)
4348 .BlockMode(BlockMode::GCM)
4349 .Padding(PaddingMode::NONE)
4350 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4351
4352 string message = "123456789012345678901234567890123456";
4353 auto begin_params = AuthorizationSetBuilder()
4354 .BlockMode(BlockMode::GCM)
4355 .Padding(PaddingMode::NONE)
4356 .Authorization(TAG_MAC_LENGTH, tag_bits);
4357 AuthorizationSet begin_out_params;
4358
Selene Huang31ab4042020-04-29 04:22:39 -07004359 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4360
4361 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07004362 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
4363 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004364 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004365 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4366 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004367
Selene Huang31ab4042020-04-29 04:22:39 -07004368 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07004369 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004370
4371 // Grab nonce.
4372 begin_params.push_back(begin_out_params);
4373
4374 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004375 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004376 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004377 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004378 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004379 EXPECT_EQ(message, plaintext);
4380}
4381
4382/*
4383 * EncryptionOperationsTest.AesGcmAadOutOfOrder
4384 *
4385 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
4386 */
4387TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
4388 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4389 .Authorization(TAG_NO_AUTH_REQUIRED)
4390 .AesEncryptionKey(128)
4391 .BlockMode(BlockMode::GCM)
4392 .Padding(PaddingMode::NONE)
4393 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4394
4395 string message = "123456789012345678901234567890123456";
4396 auto begin_params = AuthorizationSetBuilder()
4397 .BlockMode(BlockMode::GCM)
4398 .Padding(PaddingMode::NONE)
4399 .Authorization(TAG_MAC_LENGTH, 128);
4400 AuthorizationSet begin_out_params;
4401
Selene Huang31ab4042020-04-29 04:22:39 -07004402 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4403
Shawn Willden92d79c02021-02-19 07:31:55 -07004404 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004405 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004406 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4407 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004408
Shawn Willden92d79c02021-02-19 07:31:55 -07004409 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07004410}
4411
4412/*
4413 * EncryptionOperationsTest.AesGcmBadAad
4414 *
4415 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
4416 */
4417TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
4418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4419 .Authorization(TAG_NO_AUTH_REQUIRED)
4420 .AesEncryptionKey(128)
4421 .BlockMode(BlockMode::GCM)
4422 .Padding(PaddingMode::NONE)
4423 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4424
4425 string message = "12345678901234567890123456789012";
4426 auto begin_params = AuthorizationSetBuilder()
4427 .BlockMode(BlockMode::GCM)
4428 .Padding(PaddingMode::NONE)
4429 .Authorization(TAG_MAC_LENGTH, 128);
4430
Selene Huang31ab4042020-04-29 04:22:39 -07004431 // Encrypt
4432 AuthorizationSet begin_out_params;
4433 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004434 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004435 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004436 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004437
4438 // Grab nonce
4439 begin_params.push_back(begin_out_params);
4440
Selene Huang31ab4042020-04-29 04:22:39 -07004441 // Decrypt.
4442 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004443 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004444 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004445 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004446}
4447
4448/*
4449 * EncryptionOperationsTest.AesGcmWrongNonce
4450 *
4451 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
4452 */
4453TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
4454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4455 .Authorization(TAG_NO_AUTH_REQUIRED)
4456 .AesEncryptionKey(128)
4457 .BlockMode(BlockMode::GCM)
4458 .Padding(PaddingMode::NONE)
4459 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4460
4461 string message = "12345678901234567890123456789012";
4462 auto begin_params = AuthorizationSetBuilder()
4463 .BlockMode(BlockMode::GCM)
4464 .Padding(PaddingMode::NONE)
4465 .Authorization(TAG_MAC_LENGTH, 128);
4466
Selene Huang31ab4042020-04-29 04:22:39 -07004467 // Encrypt
4468 AuthorizationSet begin_out_params;
4469 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004470 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004471 string ciphertext;
4472 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004473 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004474
4475 // Wrong nonce
4476 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
4477
4478 // Decrypt.
4479 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004480 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004481 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004482 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004483
4484 // With wrong nonce, should have gotten garbage plaintext (or none).
4485 EXPECT_NE(message, plaintext);
4486}
4487
4488/*
4489 * EncryptionOperationsTest.AesGcmCorruptTag
4490 *
4491 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
4492 */
4493TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
4494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4495 .Authorization(TAG_NO_AUTH_REQUIRED)
4496 .AesEncryptionKey(128)
4497 .BlockMode(BlockMode::GCM)
4498 .Padding(PaddingMode::NONE)
4499 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4500
4501 string aad = "1234567890123456";
4502 string message = "123456789012345678901234567890123456";
4503
4504 auto params = AuthorizationSetBuilder()
4505 .BlockMode(BlockMode::GCM)
4506 .Padding(PaddingMode::NONE)
4507 .Authorization(TAG_MAC_LENGTH, 128);
4508
Selene Huang31ab4042020-04-29 04:22:39 -07004509 // Encrypt
4510 AuthorizationSet begin_out_params;
4511 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004512 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004513 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004514 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004515
4516 // Corrupt tag
4517 ++(*ciphertext.rbegin());
4518
4519 // Grab nonce
4520 params.push_back(begin_out_params);
4521
4522 // Decrypt.
4523 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004524 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004525 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004526 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004527}
4528
4529/*
4530 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
4531 *
4532 * Verifies that 3DES is basically functional.
4533 */
4534TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
4535 auto auths = AuthorizationSetBuilder()
4536 .TripleDesEncryptionKey(168)
4537 .BlockMode(BlockMode::ECB)
4538 .Authorization(TAG_NO_AUTH_REQUIRED)
4539 .Padding(PaddingMode::NONE);
4540
4541 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
4542 // Two-block message.
4543 string message = "1234567890123456";
4544 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4545 string ciphertext1 = EncryptMessage(message, inParams);
4546 EXPECT_EQ(message.size(), ciphertext1.size());
4547
4548 string ciphertext2 = EncryptMessage(string(message), inParams);
4549 EXPECT_EQ(message.size(), ciphertext2.size());
4550
4551 // ECB is deterministic.
4552 EXPECT_EQ(ciphertext1, ciphertext2);
4553
4554 string plaintext = DecryptMessage(ciphertext1, inParams);
4555 EXPECT_EQ(message, plaintext);
4556}
4557
4558/*
4559 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
4560 *
4561 * Verifies that CBC keys reject ECB usage.
4562 */
4563TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
4564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4565 .TripleDesEncryptionKey(168)
4566 .BlockMode(BlockMode::CBC)
4567 .Authorization(TAG_NO_AUTH_REQUIRED)
4568 .Padding(PaddingMode::NONE)));
4569
4570 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4571 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4572}
4573
4574/*
4575 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
4576 *
4577 * Tests ECB mode with PKCS#7 padding, various message sizes.
4578 */
4579TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
4580 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4581 .TripleDesEncryptionKey(168)
4582 .BlockMode(BlockMode::ECB)
4583 .Authorization(TAG_NO_AUTH_REQUIRED)
4584 .Padding(PaddingMode::PKCS7)));
4585
4586 for (size_t i = 0; i < 32; ++i) {
4587 string message(i, 'a');
4588 auto inParams =
4589 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4590 string ciphertext = EncryptMessage(message, inParams);
4591 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4592 string plaintext = DecryptMessage(ciphertext, inParams);
4593 EXPECT_EQ(message, plaintext);
4594 }
4595}
4596
4597/*
4598 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
4599 *
4600 * Verifies that keys configured for no padding reject PKCS7 padding
4601 */
4602TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
4603 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4604 .TripleDesEncryptionKey(168)
4605 .BlockMode(BlockMode::ECB)
4606 .Authorization(TAG_NO_AUTH_REQUIRED)
4607 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00004608 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4609 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07004610}
4611
4612/*
4613 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
4614 *
4615 * Verifies that corrupted padding is detected.
4616 */
4617TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
4618 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4619 .TripleDesEncryptionKey(168)
4620 .BlockMode(BlockMode::ECB)
4621 .Authorization(TAG_NO_AUTH_REQUIRED)
4622 .Padding(PaddingMode::PKCS7)));
4623
4624 string message = "a";
4625 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
4626 EXPECT_EQ(8U, ciphertext.size());
4627 EXPECT_NE(ciphertext, message);
4628 ++ciphertext[ciphertext.size() / 2];
4629
4630 AuthorizationSetBuilder begin_params;
4631 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
4632 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
4633 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4634 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004635 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004636 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4637}
4638
4639struct TripleDesTestVector {
4640 const char* name;
4641 const KeyPurpose purpose;
4642 const BlockMode block_mode;
4643 const PaddingMode padding_mode;
4644 const char* key;
4645 const char* iv;
4646 const char* input;
4647 const char* output;
4648};
4649
4650// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
4651// of the NIST vectors are multiples of the block size.
4652static const TripleDesTestVector kTripleDesTestVectors[] = {
4653 {
4654 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4655 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
4656 "", // IV
4657 "329d86bdf1bc5af4", // input
4658 "d946c2756d78633f", // output
4659 },
4660 {
4661 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4662 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
4663 "", // IV
4664 "6b1540781b01ce1997adae102dbf3c5b", // input
4665 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
4666 },
4667 {
4668 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4669 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
4670 "", // IV
4671 "6daad94ce08acfe7", // input
4672 "660e7d32dcc90e79", // output
4673 },
4674 {
4675 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4676 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
4677 "", // IV
4678 "e9653a0a1f05d31b9acd12d73aa9879d", // input
4679 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
4680 },
4681 {
4682 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4683 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
4684 "43f791134c5647ba", // IV
4685 "dcc153cef81d6f24", // input
4686 "92538bd8af18d3ba", // output
4687 },
4688 {
4689 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4690 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4691 "c2e999cb6249023c", // IV
4692 "c689aee38a301bb316da75db36f110b5", // input
4693 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
4694 },
4695 {
4696 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
4697 PaddingMode::PKCS7,
4698 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4699 "c2e999cb6249023c", // IV
4700 "c689aee38a301bb316da75db36f110b500", // input
4701 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
4702 },
4703 {
4704 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
4705 PaddingMode::PKCS7,
4706 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4707 "c2e999cb6249023c", // IV
4708 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
4709 "c689aee38a301bb316da75db36f110b500", // output
4710 },
4711 {
4712 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4713 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
4714 "41746c7e442d3681", // IV
4715 "c53a7b0ec40600fe", // input
4716 "d4f00eb455de1034", // output
4717 },
4718 {
4719 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4720 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
4721 "3982bc02c3727d45", // IV
4722 "6006f10adef52991fcc777a1238bbb65", // input
4723 "edae09288e9e3bc05746d872b48e3b29", // output
4724 },
4725};
4726
4727/*
4728 * EncryptionOperationsTest.TripleDesTestVector
4729 *
4730 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
4731 */
4732TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
4733 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
4734 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
4735 SCOPED_TRACE(test->name);
4736 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
4737 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
4738 hex2str(test->output));
4739 }
4740}
4741
4742/*
4743 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
4744 *
4745 * Validates CBC mode functionality.
4746 */
4747TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
4748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4749 .TripleDesEncryptionKey(168)
4750 .BlockMode(BlockMode::CBC)
4751 .Authorization(TAG_NO_AUTH_REQUIRED)
4752 .Padding(PaddingMode::NONE)));
4753
4754 ASSERT_GT(key_blob_.size(), 0U);
4755
4756 // Two-block message.
4757 string message = "1234567890123456";
4758 vector<uint8_t> iv1;
4759 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
4760 EXPECT_EQ(message.size(), ciphertext1.size());
4761
4762 vector<uint8_t> iv2;
4763 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
4764 EXPECT_EQ(message.size(), ciphertext2.size());
4765
4766 // IVs should be random, so ciphertexts should differ.
4767 EXPECT_NE(iv1, iv2);
4768 EXPECT_NE(ciphertext1, ciphertext2);
4769
4770 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
4771 EXPECT_EQ(message, plaintext);
4772}
4773
4774/*
4775 * EncryptionOperationsTest.TripleDesCallerIv
4776 *
4777 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
4778 */
4779TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
4780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4781 .TripleDesEncryptionKey(168)
4782 .BlockMode(BlockMode::CBC)
4783 .Authorization(TAG_NO_AUTH_REQUIRED)
4784 .Authorization(TAG_CALLER_NONCE)
4785 .Padding(PaddingMode::NONE)));
4786 string message = "1234567890123456";
4787 vector<uint8_t> iv;
4788 // Don't specify IV, should get a random one.
4789 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4790 EXPECT_EQ(message.size(), ciphertext1.size());
4791 EXPECT_EQ(8U, iv.size());
4792
4793 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4794 EXPECT_EQ(message, plaintext);
4795
4796 // Now specify an IV, should also work.
4797 iv = AidlBuf("abcdefgh");
4798 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
4799
4800 // Decrypt with correct IV.
4801 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
4802 EXPECT_EQ(message, plaintext);
4803
4804 // Now try with wrong IV.
4805 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
4806 EXPECT_NE(message, plaintext);
4807}
4808
4809/*
4810 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
4811 *
4812 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
4813 */
4814TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
4815 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4816 .TripleDesEncryptionKey(168)
4817 .BlockMode(BlockMode::CBC)
4818 .Authorization(TAG_NO_AUTH_REQUIRED)
4819 .Padding(PaddingMode::NONE)));
4820
4821 string message = "12345678901234567890123456789012";
4822 vector<uint8_t> iv;
4823 // Don't specify nonce, should get a random one.
4824 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4825 EXPECT_EQ(message.size(), ciphertext1.size());
4826 EXPECT_EQ(8U, iv.size());
4827
4828 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4829 EXPECT_EQ(message, plaintext);
4830
4831 // Now specify a nonce, should fail.
4832 auto input_params = AuthorizationSetBuilder()
4833 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
4834 .BlockMode(BlockMode::CBC)
4835 .Padding(PaddingMode::NONE);
4836 AuthorizationSet output_params;
4837 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
4838 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4839}
4840
4841/*
4842 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
4843 *
4844 * Verifies that 3DES ECB-only keys do not allow CBC usage.
4845 */
4846TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
4847 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4848 .TripleDesEncryptionKey(168)
4849 .BlockMode(BlockMode::ECB)
4850 .Authorization(TAG_NO_AUTH_REQUIRED)
4851 .Padding(PaddingMode::NONE)));
4852 // Two-block message.
4853 string message = "1234567890123456";
4854 auto begin_params =
4855 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4856 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4857}
4858
4859/*
4860 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4861 *
4862 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4863 */
4864TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4865 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4866 .TripleDesEncryptionKey(168)
4867 .BlockMode(BlockMode::CBC)
4868 .Authorization(TAG_NO_AUTH_REQUIRED)
4869 .Padding(PaddingMode::NONE)));
4870 // Message is slightly shorter than two blocks.
4871 string message = "123456789012345";
4872
4873 auto begin_params =
4874 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4875 AuthorizationSet output_params;
4876 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4877 string ciphertext;
4878 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4879}
4880
4881/*
4882 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4883 *
4884 * Verifies that PKCS7 padding works correctly in CBC mode.
4885 */
4886TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4888 .TripleDesEncryptionKey(168)
4889 .BlockMode(BlockMode::CBC)
4890 .Authorization(TAG_NO_AUTH_REQUIRED)
4891 .Padding(PaddingMode::PKCS7)));
4892
4893 // Try various message lengths; all should work.
4894 for (size_t i = 0; i < 32; ++i) {
4895 string message(i, 'a');
4896 vector<uint8_t> iv;
4897 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4898 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4899 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4900 EXPECT_EQ(message, plaintext);
4901 }
4902}
4903
4904/*
4905 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4906 *
4907 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4908 */
4909TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4910 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4911 .TripleDesEncryptionKey(168)
4912 .BlockMode(BlockMode::CBC)
4913 .Authorization(TAG_NO_AUTH_REQUIRED)
4914 .Padding(PaddingMode::NONE)));
4915
4916 // Try various message lengths; all should fail.
4917 for (size_t i = 0; i < 32; ++i) {
4918 auto begin_params =
4919 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4920 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4921 }
4922}
4923
4924/*
4925 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4926 *
4927 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4928 */
4929TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4930 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4931 .TripleDesEncryptionKey(168)
4932 .BlockMode(BlockMode::CBC)
4933 .Authorization(TAG_NO_AUTH_REQUIRED)
4934 .Padding(PaddingMode::PKCS7)));
4935
4936 string message = "a";
4937 vector<uint8_t> iv;
4938 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4939 EXPECT_EQ(8U, ciphertext.size());
4940 EXPECT_NE(ciphertext, message);
4941 ++ciphertext[ciphertext.size() / 2];
4942
4943 auto begin_params = AuthorizationSetBuilder()
4944 .BlockMode(BlockMode::CBC)
4945 .Padding(PaddingMode::PKCS7)
4946 .Authorization(TAG_NONCE, iv);
4947 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4948 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004949 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004950 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4951}
4952
4953/*
4954 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4955 *
4956 * Verifies that 3DES CBC works with many different input sizes.
4957 */
4958TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4959 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4960 .TripleDesEncryptionKey(168)
4961 .BlockMode(BlockMode::CBC)
4962 .Authorization(TAG_NO_AUTH_REQUIRED)
4963 .Padding(PaddingMode::NONE)));
4964
4965 int increment = 7;
4966 string message(240, 'a');
4967 AuthorizationSet input_params =
4968 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4969 AuthorizationSet output_params;
4970 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4971
4972 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004973 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004974 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004975 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4976 EXPECT_EQ(message.size(), ciphertext.size());
4977
4978 // Move TAG_NONCE into input_params
4979 input_params = output_params;
4980 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4981 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4982 output_params.Clear();
4983
4984 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4985 string plaintext;
4986 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004987 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004988 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4989 EXPECT_EQ(ciphertext.size(), plaintext.size());
4990 EXPECT_EQ(message, plaintext);
4991}
4992
4993INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4994
4995typedef KeyMintAidlTestBase MaxOperationsTest;
4996
4997/*
4998 * MaxOperationsTest.TestLimitAes
4999 *
5000 * Verifies that the max uses per boot tag works correctly with AES keys.
5001 */
5002TEST_P(MaxOperationsTest, TestLimitAes) {
5003 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5004
5005 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5006 .Authorization(TAG_NO_AUTH_REQUIRED)
5007 .AesEncryptionKey(128)
5008 .EcbMode()
5009 .Padding(PaddingMode::NONE)
5010 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5011
5012 string message = "1234567890123456";
5013
5014 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5015
5016 EncryptMessage(message, params);
5017 EncryptMessage(message, params);
5018 EncryptMessage(message, params);
5019
5020 // Fourth time should fail.
5021 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5022}
5023
5024/*
Qi Wud22ec842020-11-26 13:27:53 +08005025 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005026 *
5027 * Verifies that the max uses per boot tag works correctly with RSA keys.
5028 */
5029TEST_P(MaxOperationsTest, TestLimitRsa) {
5030 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5031
5032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5033 .Authorization(TAG_NO_AUTH_REQUIRED)
5034 .RsaSigningKey(1024, 65537)
5035 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005036 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5037 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005038
5039 string message = "1234567890123456";
5040
5041 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5042
5043 SignMessage(message, params);
5044 SignMessage(message, params);
5045 SignMessage(message, params);
5046
5047 // Fourth time should fail.
5048 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5049}
5050
5051INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5052
Qi Wud22ec842020-11-26 13:27:53 +08005053typedef KeyMintAidlTestBase UsageCountLimitTest;
5054
5055/*
Qi Wubeefae42021-01-28 23:16:37 +08005056 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005057 *
Qi Wubeefae42021-01-28 23:16:37 +08005058 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005059 */
Qi Wubeefae42021-01-28 23:16:37 +08005060TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005061 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5062
5063 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5064 .Authorization(TAG_NO_AUTH_REQUIRED)
5065 .AesEncryptionKey(128)
5066 .EcbMode()
5067 .Padding(PaddingMode::NONE)
5068 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5069
5070 // Check the usage count limit tag appears in the authorizations.
5071 AuthorizationSet auths;
5072 for (auto& entry : key_characteristics_) {
5073 auths.push_back(AuthorizationSet(entry.authorizations));
5074 }
5075 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5076 << "key usage count limit " << 1U << " missing";
5077
5078 string message = "1234567890123456";
5079 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5080
Qi Wubeefae42021-01-28 23:16:37 +08005081 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5082 AuthorizationSet keystore_auths =
5083 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5084
Qi Wud22ec842020-11-26 13:27:53 +08005085 // First usage of AES key should work.
5086 EncryptMessage(message, params);
5087
Qi Wud22ec842020-11-26 13:27:53 +08005088 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5089 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5090 // must be invalidated from secure storage (such as RPMB partition).
5091 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5092 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005093 // Usage count limit tag is enforced by keystore, keymint does nothing.
5094 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005095 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5096 }
5097}
5098
5099/*
Qi Wubeefae42021-01-28 23:16:37 +08005100 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005101 *
Qi Wubeefae42021-01-28 23:16:37 +08005102 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005103 */
Qi Wubeefae42021-01-28 23:16:37 +08005104TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5105 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5106
5107 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5108 .Authorization(TAG_NO_AUTH_REQUIRED)
5109 .AesEncryptionKey(128)
5110 .EcbMode()
5111 .Padding(PaddingMode::NONE)
5112 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5113
5114 // Check the usage count limit tag appears in the authorizations.
5115 AuthorizationSet auths;
5116 for (auto& entry : key_characteristics_) {
5117 auths.push_back(AuthorizationSet(entry.authorizations));
5118 }
5119 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5120 << "key usage count limit " << 3U << " missing";
5121
5122 string message = "1234567890123456";
5123 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5124
5125 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5126 AuthorizationSet keystore_auths =
5127 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5128
5129 EncryptMessage(message, params);
5130 EncryptMessage(message, params);
5131 EncryptMessage(message, params);
5132
5133 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5134 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5135 // must be invalidated from secure storage (such as RPMB partition).
5136 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5137 } else {
5138 // Usage count limit tag is enforced by keystore, keymint does nothing.
5139 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5140 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5141 }
5142}
5143
5144/*
5145 * UsageCountLimitTest.TestSingleUseRsa
5146 *
5147 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5148 */
5149TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005150 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5151
5152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5153 .Authorization(TAG_NO_AUTH_REQUIRED)
5154 .RsaSigningKey(1024, 65537)
5155 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005156 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5157 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005158
5159 // Check the usage count limit tag appears in the authorizations.
5160 AuthorizationSet auths;
5161 for (auto& entry : key_characteristics_) {
5162 auths.push_back(AuthorizationSet(entry.authorizations));
5163 }
5164 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5165 << "key usage count limit " << 1U << " missing";
5166
5167 string message = "1234567890123456";
5168 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5169
Qi Wubeefae42021-01-28 23:16:37 +08005170 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5171 AuthorizationSet keystore_auths =
5172 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5173
Qi Wud22ec842020-11-26 13:27:53 +08005174 // First usage of RSA key should work.
5175 SignMessage(message, params);
5176
Qi Wud22ec842020-11-26 13:27:53 +08005177 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5178 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5179 // must be invalidated from secure storage (such as RPMB partition).
5180 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5181 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005182 // Usage count limit tag is enforced by keystore, keymint does nothing.
5183 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5184 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5185 }
5186}
5187
5188/*
5189 * UsageCountLimitTest.TestLimitUseRsa
5190 *
5191 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5192 */
5193TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5194 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5195
5196 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5197 .Authorization(TAG_NO_AUTH_REQUIRED)
5198 .RsaSigningKey(1024, 65537)
5199 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005200 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5201 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005202
5203 // Check the usage count limit tag appears in the authorizations.
5204 AuthorizationSet auths;
5205 for (auto& entry : key_characteristics_) {
5206 auths.push_back(AuthorizationSet(entry.authorizations));
5207 }
5208 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5209 << "key usage count limit " << 3U << " missing";
5210
5211 string message = "1234567890123456";
5212 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5213
5214 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5215 AuthorizationSet keystore_auths =
5216 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5217
5218 SignMessage(message, params);
5219 SignMessage(message, params);
5220 SignMessage(message, params);
5221
5222 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5223 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5224 // must be invalidated from secure storage (such as RPMB partition).
5225 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5226 } else {
5227 // Usage count limit tag is enforced by keystore, keymint does nothing.
5228 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08005229 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5230 }
5231}
5232
Qi Wu8e727f72021-02-11 02:49:33 +08005233/*
5234 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
5235 *
5236 * Verifies that when rollback resistance is supported by the KeyMint implementation with
5237 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
5238 * in hardware.
5239 */
5240TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
5241 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5242
5243 auto error = GenerateKey(AuthorizationSetBuilder()
5244 .RsaSigningKey(2048, 65537)
5245 .Digest(Digest::NONE)
5246 .Padding(PaddingMode::NONE)
5247 .Authorization(TAG_NO_AUTH_REQUIRED)
5248 .Authorization(TAG_ROLLBACK_RESISTANCE)
5249 .SetDefaultValidity());
5250 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5251
5252 if (error == ErrorCode::OK) {
5253 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
5254 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
5255 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5256 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5257
5258 // The KeyMint should also enforce single use key in hardware when it supports rollback
5259 // resistance.
5260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5261 .Authorization(TAG_NO_AUTH_REQUIRED)
5262 .RsaSigningKey(1024, 65537)
5263 .NoDigestOrPadding()
5264 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5265 .SetDefaultValidity()));
5266
5267 // Check the usage count limit tag appears in the hardware authorizations.
5268 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5269 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5270 << "key usage count limit " << 1U << " missing";
5271
5272 string message = "1234567890123456";
5273 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5274
5275 // First usage of RSA key should work.
5276 SignMessage(message, params);
5277
5278 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5279 // must be invalidated from secure storage (such as RPMB partition).
5280 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5281 }
5282}
5283
Qi Wud22ec842020-11-26 13:27:53 +08005284INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
5285
David Drysdale7de9feb2021-03-05 14:56:19 +00005286typedef KeyMintAidlTestBase GetHardwareInfoTest;
5287
5288TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
5289 // Retrieving hardware info should give the same result each time.
5290 KeyMintHardwareInfo info;
5291 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
5292 KeyMintHardwareInfo info2;
5293 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
5294 EXPECT_EQ(info, info2);
5295}
5296
5297INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
5298
Selene Huang31ab4042020-04-29 04:22:39 -07005299typedef KeyMintAidlTestBase AddEntropyTest;
5300
5301/*
5302 * AddEntropyTest.AddEntropy
5303 *
5304 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
5305 * is actually added.
5306 */
5307TEST_P(AddEntropyTest, AddEntropy) {
5308 string data = "foo";
5309 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
5310}
5311
5312/*
5313 * AddEntropyTest.AddEmptyEntropy
5314 *
5315 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
5316 */
5317TEST_P(AddEntropyTest, AddEmptyEntropy) {
5318 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
5319}
5320
5321/*
5322 * AddEntropyTest.AddLargeEntropy
5323 *
5324 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
5325 */
5326TEST_P(AddEntropyTest, AddLargeEntropy) {
5327 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
5328}
5329
David Drysdalebb3d85e2021-04-13 11:15:51 +01005330/*
5331 * AddEntropyTest.AddTooLargeEntropy
5332 *
5333 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
5334 */
5335TEST_P(AddEntropyTest, AddTooLargeEntropy) {
5336 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
5337 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
5338}
5339
Selene Huang31ab4042020-04-29 04:22:39 -07005340INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
5341
Selene Huang31ab4042020-04-29 04:22:39 -07005342typedef KeyMintAidlTestBase KeyDeletionTest;
5343
5344/**
5345 * KeyDeletionTest.DeleteKey
5346 *
5347 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
5348 * valid key blob.
5349 */
5350TEST_P(KeyDeletionTest, DeleteKey) {
5351 auto error = GenerateKey(AuthorizationSetBuilder()
5352 .RsaSigningKey(2048, 65537)
5353 .Digest(Digest::NONE)
5354 .Padding(PaddingMode::NONE)
5355 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005356 .Authorization(TAG_ROLLBACK_RESISTANCE)
5357 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005358 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5359
5360 // Delete must work if rollback protection is implemented
5361 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005362 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005363 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5364
5365 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
5366
5367 string message = "12345678901234567890123456789012";
5368 AuthorizationSet begin_out_params;
5369 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5370 Begin(KeyPurpose::SIGN, key_blob_,
5371 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5372 &begin_out_params));
5373 AbortIfNeeded();
5374 key_blob_ = AidlBuf();
5375 }
5376}
5377
5378/**
5379 * KeyDeletionTest.DeleteInvalidKey
5380 *
5381 * This test checks that the HAL excepts invalid key blobs..
5382 */
5383TEST_P(KeyDeletionTest, DeleteInvalidKey) {
5384 // Generate key just to check if rollback protection is implemented
5385 auto error = GenerateKey(AuthorizationSetBuilder()
5386 .RsaSigningKey(2048, 65537)
5387 .Digest(Digest::NONE)
5388 .Padding(PaddingMode::NONE)
5389 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08005390 .Authorization(TAG_ROLLBACK_RESISTANCE)
5391 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07005392 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5393
5394 // Delete must work if rollback protection is implemented
5395 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005396 AuthorizationSet enforced(SecLevelAuthorizations());
5397 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005398
5399 // Delete the key we don't care about the result at this point.
5400 DeleteKey();
5401
5402 // Now create an invalid key blob and delete it.
5403 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
5404
5405 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5406 }
5407}
5408
5409/**
5410 * KeyDeletionTest.DeleteAllKeys
5411 *
5412 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
5413 *
5414 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
5415 * FBE/FDE encryption keys, which means that the device will not even boot until after the
5416 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
5417 * been provisioned. Use this test only on dedicated testing devices that have no valuable
5418 * credentials stored in Keystore/Keymint.
5419 */
5420TEST_P(KeyDeletionTest, DeleteAllKeys) {
5421 if (!arm_deleteAllKeys) return;
5422 auto error = GenerateKey(AuthorizationSetBuilder()
5423 .RsaSigningKey(2048, 65537)
5424 .Digest(Digest::NONE)
5425 .Padding(PaddingMode::NONE)
5426 .Authorization(TAG_NO_AUTH_REQUIRED)
5427 .Authorization(TAG_ROLLBACK_RESISTANCE));
5428 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5429
5430 // Delete must work if rollback protection is implemented
5431 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005432 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005433 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5434
5435 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
5436
5437 string message = "12345678901234567890123456789012";
5438 AuthorizationSet begin_out_params;
5439
5440 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5441 Begin(KeyPurpose::SIGN, key_blob_,
5442 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5443 &begin_out_params));
5444 AbortIfNeeded();
5445 key_blob_ = AidlBuf();
5446 }
5447}
5448
5449INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
5450
5451using UpgradeKeyTest = KeyMintAidlTestBase;
5452
5453/*
5454 * UpgradeKeyTest.UpgradeKey
5455 *
5456 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
5457 */
5458TEST_P(UpgradeKeyTest, UpgradeKey) {
5459 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5460 .AesEncryptionKey(128)
5461 .Padding(PaddingMode::NONE)
5462 .Authorization(TAG_NO_AUTH_REQUIRED)));
5463
5464 auto result = UpgradeKey(key_blob_);
5465
5466 // Key doesn't need upgrading. Should get okay, but no new key blob.
5467 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
5468}
5469
5470INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
5471
5472using ClearOperationsTest = KeyMintAidlTestBase;
5473
5474/*
5475 * ClearSlotsTest.TooManyOperations
5476 *
5477 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
5478 * operations are started without being finished or aborted. Also verifies
5479 * that aborting the operations clears the operations.
5480 *
5481 */
5482TEST_P(ClearOperationsTest, TooManyOperations) {
5483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5484 .Authorization(TAG_NO_AUTH_REQUIRED)
5485 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005486 .Padding(PaddingMode::NONE)
5487 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005488
5489 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5490 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08005491 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07005492 AuthorizationSet out_params;
5493 ErrorCode result;
5494 size_t i;
5495
5496 for (i = 0; i < max_operations; i++) {
5497 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
5498 if (ErrorCode::OK != result) {
5499 break;
5500 }
5501 }
5502 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
5503 // Try again just in case there's a weird overflow bug
5504 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
5505 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5506 for (size_t j = 0; j < i; j++) {
5507 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
5508 << "Aboort failed for i = " << j << std::endl;
5509 }
5510 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5511 AbortIfNeeded();
5512}
5513
5514INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
5515
5516typedef KeyMintAidlTestBase TransportLimitTest;
5517
5518/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005519 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07005520 *
5521 * Verifies that passing input data to finish succeeds as expected.
5522 */
5523TEST_P(TransportLimitTest, LargeFinishInput) {
5524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5525 .Authorization(TAG_NO_AUTH_REQUIRED)
5526 .AesEncryptionKey(128)
5527 .BlockMode(BlockMode::ECB)
5528 .Padding(PaddingMode::NONE)));
5529
5530 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
5531 auto cipher_params =
5532 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5533
5534 AuthorizationSet out_params;
5535 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
5536
5537 string plain_message = std::string(1 << msg_size, 'x');
5538 string encrypted_message;
5539 auto rc = Finish(plain_message, &encrypted_message);
5540
5541 EXPECT_EQ(ErrorCode::OK, rc);
5542 EXPECT_EQ(plain_message.size(), encrypted_message.size())
5543 << "Encrypt finish returned OK, but did not consume all of the given input";
5544 cipher_params.push_back(out_params);
5545
5546 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
5547
5548 string decrypted_message;
5549 rc = Finish(encrypted_message, &decrypted_message);
5550 EXPECT_EQ(ErrorCode::OK, rc);
5551 EXPECT_EQ(plain_message.size(), decrypted_message.size())
5552 << "Decrypt finish returned OK, did not consume all of the given input";
5553 }
5554}
5555
5556INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
5557
David Zeuthene0c40892021-01-08 12:54:11 -05005558typedef KeyMintAidlTestBase KeyAgreementTest;
5559
5560int CurveToOpenSslCurveName(EcCurve curve) {
5561 switch (curve) {
5562 case EcCurve::P_224:
5563 return NID_secp224r1;
5564 case EcCurve::P_256:
5565 return NID_X9_62_prime256v1;
5566 case EcCurve::P_384:
5567 return NID_secp384r1;
5568 case EcCurve::P_521:
5569 return NID_secp521r1;
5570 }
5571}
5572
5573/*
5574 * KeyAgreementTest.Ecdh
5575 *
5576 * Verifies that ECDH works for all curves
5577 */
5578TEST_P(KeyAgreementTest, Ecdh) {
5579 // Because it's possible to use this API with keys on different curves, we
5580 // check all N^2 combinations where N is the number of supported
5581 // curves.
5582 //
5583 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
5584 // lot more curves we can be smart about things and just pick |otherCurve| so
5585 // it's not |curve| and that way we end up with only 2*N runs
5586 //
5587 for (auto curve : ValidCurves()) {
5588 for (auto localCurve : ValidCurves()) {
5589 // Generate EC key locally (with access to private key material)
5590 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
5591 int curveName = CurveToOpenSslCurveName(localCurve);
5592 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
5593 ASSERT_NE(group, nullptr);
5594 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
5595 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
5596 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
5597 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
5598
5599 // Get encoded form of the public part of the locally generated key...
5600 unsigned char* p = nullptr;
5601 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
5602 ASSERT_GT(encodedPublicKeySize, 0);
5603 vector<uint8_t> encodedPublicKey(
5604 reinterpret_cast<const uint8_t*>(p),
5605 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
5606 OPENSSL_free(p);
5607
5608 // Generate EC key in KeyMint (only access to public key material)
5609 vector<uint8_t> challenge = {0x41, 0x42};
5610 EXPECT_EQ(
5611 ErrorCode::OK,
5612 GenerateKey(AuthorizationSetBuilder()
5613 .Authorization(TAG_NO_AUTH_REQUIRED)
5614 .Authorization(TAG_EC_CURVE, curve)
5615 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
5616 .Authorization(TAG_ALGORITHM, Algorithm::EC)
5617 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08005618 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
5619 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05005620 << "Failed to generate key";
5621 ASSERT_GT(cert_chain_.size(), 0);
5622 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
5623 ASSERT_NE(kmKeyCert, nullptr);
5624 // Check that keyAgreement (bit 4) is set in KeyUsage
5625 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
5626 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
5627 ASSERT_NE(kmPkey, nullptr);
5628 if (dump_Attestations) {
5629 for (size_t n = 0; n < cert_chain_.size(); n++) {
5630 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
5631 }
5632 }
5633
5634 // Now that we have the two keys, we ask KeyMint to perform ECDH...
5635 if (curve != localCurve) {
5636 // If the keys are using different curves KeyMint should fail with
5637 // ErrorCode:INVALID_ARGUMENT. Check that.
5638 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5639 string ZabFromKeyMintStr;
5640 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
5641 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5642 &ZabFromKeyMintStr));
5643
5644 } else {
5645 // Otherwise if the keys are using the same curve, it should work.
5646 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5647 string ZabFromKeyMintStr;
5648 EXPECT_EQ(ErrorCode::OK,
5649 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5650 &ZabFromKeyMintStr));
5651 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
5652
5653 // Perform local ECDH between the two keys so we can check if we get the same Zab..
5654 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
5655 ASSERT_NE(ctx, nullptr);
5656 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
5657 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
5658 size_t ZabFromTestLen = 0;
5659 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
5660 vector<uint8_t> ZabFromTest;
5661 ZabFromTest.resize(ZabFromTestLen);
5662 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
5663
5664 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
5665 }
5666
5667 CheckedDeleteKey();
5668 }
5669 }
5670}
5671
5672INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
5673
Shawn Willdend659c7c2021-02-19 14:51:51 -07005674using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005675
5676TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
5677 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5678 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5679
5680 CheckedDeleteKey(&aesKeyData.blob);
5681 CheckedDeleteKey(&hmacKeyData.blob);
5682 CheckedDeleteKey(&rsaKeyData.blob);
5683 CheckedDeleteKey(&ecdsaKeyData.blob);
5684}
5685
5686// This is a more comprenhensive test, but it can only be run on a machine which is still in early
5687// boot stage, which no proper Android device is by the time we can run VTS. To use this,
5688// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
5689// early boot, so you'll have to reboot between runs.
5690TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
5691 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5692 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5693 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
5694 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5695 EXPECT_TRUE(
5696 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5697 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5698 EXPECT_TRUE(
5699 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5700
5701 // Should be able to use keys, since early boot has not ended
5702 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5703 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5704 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5705 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5706
5707 // End early boot
5708 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
5709 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
5710
5711 // Should not be able to use already-created keys.
5712 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
5713 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
5714 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
5715 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
5716
5717 CheckedDeleteKey(&aesKeyData.blob);
5718 CheckedDeleteKey(&hmacKeyData.blob);
5719 CheckedDeleteKey(&rsaKeyData.blob);
5720 CheckedDeleteKey(&ecdsaKeyData.blob);
5721
5722 // Should not be able to create new keys
5723 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
5724 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
5725
5726 CheckedDeleteKey(&aesKeyData.blob);
5727 CheckedDeleteKey(&hmacKeyData.blob);
5728 CheckedDeleteKey(&rsaKeyData.blob);
5729 CheckedDeleteKey(&ecdsaKeyData.blob);
5730}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005731
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005732INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
5733
Shawn Willdend659c7c2021-02-19 14:51:51 -07005734using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005735
5736// This may be a problematic test. It can't be run repeatedly without unlocking the device in
5737// between runs... and on most test devices there are no enrolled credentials so it can't be
5738// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
5739// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
5740// a manual test process, which includes unlocking between runs, which is why it's included here.
5741// Well, that and the fact that it's the only test we can do without also making calls into the
5742// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
5743// implications might be, so that may or may not be a solution.
5744TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
5745 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5746 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
5747
5748 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5749 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5750 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5751 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5752
5753 ErrorCode rc = GetReturnErrorCode(
5754 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
5755 ASSERT_EQ(ErrorCode::OK, rc);
5756 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
5757 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
5758 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
5759 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
5760
5761 CheckedDeleteKey(&aesKeyData.blob);
5762 CheckedDeleteKey(&hmacKeyData.blob);
5763 CheckedDeleteKey(&rsaKeyData.blob);
5764 CheckedDeleteKey(&ecdsaKeyData.blob);
5765}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005766
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005767INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
5768
Janis Danisevskis24c04702020-12-16 18:28:39 -08005769} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07005770
5771int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07005772 std::cout << "Testing ";
5773 auto halInstances =
5774 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
5775 std::cout << "HAL instances:\n";
5776 for (auto& entry : halInstances) {
5777 std::cout << " " << entry << '\n';
5778 }
5779
Selene Huang31ab4042020-04-29 04:22:39 -07005780 ::testing::InitGoogleTest(&argc, argv);
5781 for (int i = 1; i < argc; ++i) {
5782 if (argv[i][0] == '-') {
5783 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07005784 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5785 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07005786 }
5787 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07005788 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5789 dump_Attestations = true;
5790 } else {
5791 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07005792 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01005793 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
5794 if (std::string(argv[i]) == "--check_patchLevels") {
5795 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
5796 }
Selene Huang31ab4042020-04-29 04:22:39 -07005797 }
5798 }
Shawn Willden08a7e432020-12-11 13:05:27 +00005799 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07005800}