blob: 0e5562d144a1bd5311b7253db60082e974968908 [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>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Drysdalead785f52023-03-27 19:53:01 +010029#include <openssl/x509.h>
David Zeuthene0c40892021-01-08 12:54:11 -050030#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070031
32#include <cutils/properties.h>
33
David Drysdale4dc01072021-04-01 12:17:35 +010034#include <android/binder_manager.h>
35
36#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080037#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070038
Shawn Willden08a7e432020-12-11 13:05:27 +000039#include <keymint_support/key_param_output.h>
40#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070041
42#include "KeyMintAidlTestBase.h"
43
Janis Danisevskis24c04702020-12-16 18:28:39 -080044using aidl::android::hardware::security::keymint::AuthorizationSet;
45using aidl::android::hardware::security::keymint::KeyCharacteristics;
46using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070047
Selene Huang31ab4042020-04-29 04:22:39 -070048namespace std {
49
Janis Danisevskis24c04702020-12-16 18:28:39 -080050using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070051
52template <>
53struct std::equal_to<KeyCharacteristics> {
54 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070055 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070056
Shawn Willden7f424372021-01-10 18:06:50 -070057 // this isn't very efficient. Oh, well.
58 AuthorizationSet a_auths(a.authorizations);
59 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070060
Shawn Willden7f424372021-01-10 18:06:50 -070061 a_auths.Sort();
62 b_auths.Sort();
63
64 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070065 }
66};
67
68} // namespace std
69
Janis Danisevskis24c04702020-12-16 18:28:39 -080070namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000071
Selene Huang31ab4042020-04-29 04:22:39 -070072namespace {
73
David Drysdalefeab5d92022-01-06 15:46:23 +000074// Maximum supported Ed25519 message size.
75const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
76
David Drysdaledbbbe2e2021-12-02 07:44:23 +000077// Whether to check that BOOT_PATCHLEVEL is populated.
78bool check_boot_pl = true;
79
Seth Moore7a55ae32021-06-23 14:28:11 -070080// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000081// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070082// is a small (roughly 1/256) chance that corrupting ciphertext still results
83// in valid PKCS7 padding.
84constexpr size_t kMaxPaddingCorruptionRetries = 8;
85
Selene Huang31ab4042020-04-29 04:22:39 -070086template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
88 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070089 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080090 if (auto p = authorizationValue(ttag, param)) {
91 return *p == expected_value;
92 }
93 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070094 });
95 return (it != set.end());
96}
97
98template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000099bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -0700100 auto it = std::find_if(set.begin(), set.end(),
101 [&](const KeyParameter& param) { return param.tag == tag; });
102 return (it != set.end());
103}
104
105constexpr char hex_value[256] = {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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
109 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
121
122string hex2str(string a) {
123 string b;
124 size_t num = a.size() / 2;
125 b.resize(num);
126 for (size_t i = 0; i < num; i++) {
127 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
128 }
129 return b;
130}
131
David Drysdaled2cc8c22021-04-15 13:29:45 +0100132string rsa_key = hex2str(
133 // RFC 5208 s5
134 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
135 "020100" // INTEGER length 1 value 0x00 (version)
136 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
137 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
138 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
139 "0500" // NULL (parameters)
140 // } end SEQUENCE (AlgorithmIdentifier)
141 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
142 // RFC 8017 A.1.2
143 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
144 "020100" // INTEGER length 1 value 0x00 (version)
145 "028181" // INTEGER length 0x81 value (modulus) ...
146 "00c6095409047d8634812d5a218176e4"
147 "5c41d60a75b13901f234226cffe77652"
148 "1c5a77b9e389417b71c0b6a44d13afe4"
149 "e4a2805d46c9da2935adb1ff0c1f24ea"
150 "06e62b20d776430a4d435157233c6f91"
151 "6783c30e310fcbd89b85c2d567711697"
152 "85ac12bca244abda72bfb19fc44d27c8"
153 "1e1d92de284f4061edfd99280745ea6d"
154 "25"
155 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
156 "028180" // INTEGER length 0x80 (privateExponent) value...
157 "1be0f04d9cae3718691f035338308e91"
158 "564b55899ffb5084d2460e6630257e05"
159 "b3ceab02972dfabcd6ce5f6ee2589eb6"
160 "7911ed0fac16e43a444b8c861e544a05"
161 "93365772f8baf6b22fc9e3c5f1024b06"
162 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
163 "ace7240290bef16c0b3f7f3cdd64ce3a"
164 "b5912cf6e32f39ab188358afcccd8081"
165 "0241" // INTEGER length 0x41 (prime1)
166 "00e4b49ef50f765d3b24dde01aceaaf1"
167 "30f2c76670a91a61ae08af497b4a82be"
168 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
169 "8c92bfab137fba2285227b83c342ff7c"
170 "55"
171 "0241" // INTEGER length 0x41 (prime2)
172 "00ddabb5839c4c7f6bf3d4183231f005"
173 "b31aa58affdda5c79e4cce217f6bc930"
174 "dbe563d480706c24e9ebfcab28a6cdef"
175 "d324b77e1bf7251b709092c24ff501fd"
176 "91"
177 "0240" // INTEGER length 0x40 (exponent1)
178 "23d4340eda3445d8cd26c14411da6fdc"
179 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
180 "842c1d280405bc2f6c1bea214a1d742a"
181 "b996b35b63a82a5e470fa88dbf823cdd"
182 "0240" // INTEGER length 0x40 (exponent2)
183 "1b7b57449ad30d1518249a5f56bb9829"
184 "4d4b6ac12ffc86940497a5a5837a6cf9"
185 "46262b494526d328c11e1126380fde04"
186 "c24f916dec250892db09a6d77cdba351"
187 "0240" // INTEGER length 0x40 (coefficient)
188 "7762cd8f4d050da56bd591adb515d24d"
189 "7ccd32cca0d05f866d583514bd7324d5"
190 "f33645e8ed8b4a1cb3cc4a1d67987399"
191 "f2a09f5b3fb68c88d5e5d90ac33492d6"
192 // } end SEQUENCE (PrivateKey)
193 // } end SEQUENCE (PrivateKeyInfo)
194);
Selene Huang31ab4042020-04-29 04:22:39 -0700195
Selene Huange5727e62021-04-13 22:41:20 -0700196/*
197 * DER-encoded PKCS#8 format RSA key. Generated using:
198 *
199 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
200 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100201string rsa_2048_key = hex2str(
202 // RFC 5208 s5
203 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
204 "020100" // INTEGER length 1 value 0x00 (version)
205 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
206 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
207 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
208 "0500" // NULL (parameters)
209 // } end SEQUENCE (AlgorithmIdentifier)
210 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
211 // RFC 8017 A.1.2
212 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
213 "020100" // INTEGER length 1 value 0x00 (version)
214 "02820101" // INTEGER length 0x101 value (modulus) ...
215 "00BEBC342B56D443B1299F9A6A7056E8"
216 "0A897E318476A5A18029E63B2ED739A6"
217 "1791D339F58DC763D9D14911F2EDEC38"
218 "3DEE11F6319B44510E7A3ECD9B79B973"
219 "82E49500ACF8117DC89CAF0E621F7775"
220 "6554A2FD4664BFE7AB8B59AB48340DBF"
221 "A27B93B5A81F6ECDEB02D0759307128D"
222 "F3E3BAD4055C8B840216DFAA5700670E"
223 "6C5126F0962FCB70FF308F25049164CC"
224 "F76CC2DA66A7DD9A81A714C2809D6918"
225 "6133D29D84568E892B6FFBF3199BDB14"
226 "383EE224407F190358F111A949552ABA"
227 "6714227D1BD7F6B20DD0CB88F9467B71"
228 "9339F33BFF35B3870B3F62204E4286B0"
229 "948EA348B524544B5F9838F29EE643B0"
230 "79EEF8A713B220D7806924CDF7295070"
231 "C5"
232 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
233 "02820100" // INTEGER length 0x100 (privateExponent) value...
234 "69F377F35F2F584EF075353CCD1CA997"
235 "38DB3DBC7C7FF35F9366CE176DFD1B13"
236 "5AB10030344ABF5FBECF1D4659FDEF1C"
237 "0FC430834BE1BE3911951377BB3D563A"
238 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
239 "2686C7B4B3C09A7B8354133E6F93F790"
240 "D59EAEB92E84C9A4339302CCE28FDF04"
241 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
242 "6AB706645BF074A4E4090D06FB163124"
243 "365FD5EE7A20D350E9958CC30D91326E"
244 "1B292E9EF5DB408EC42DAF737D201497"
245 "04D0A678A0FB5B5446863B099228A352"
246 "D604BA8091A164D01D5AB05397C71EAD"
247 "20BE2A08FC528FE442817809C787FEE4"
248 "AB97F97B9130D022153EDC6EB6CBE7B0"
249 "F8E3473F2E901209B5DB10F93604DB01"
250 "028181" // INTEGER length 0x81 (prime1)
251 "00E83C0998214941EA4F9293F1B77E2E"
252 "99E6CF305FAF358238E126124FEAF2EB"
253 "9724B2EA7B78E6032343821A80E55D1D"
254 "88FB12D220C3F41A56142FEC85796D19"
255 "17F1E8C774F142B67D3D6E7B7E6B4383"
256 "E94DB5929089DBB346D5BDAB40CC2D96"
257 "EE0409475E175C63BF78CFD744136740"
258 "838127EA723FF3FE7FA368C1311B4A4E"
259 "05"
260 "028181" // INTEGER length 0x81 (prime2)
261 "00D240FCC0F5D7715CDE21CB2DC86EA1"
262 "46132EA3B06F61FF2AF54BF38473F59D"
263 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
264 "B1B58C39F95E4798CCBB43E83D0119AC"
265 "F532F359CA743C85199F0286610E2009"
266 "97D7312917179AC9B67558773212EC96"
267 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
268 "94D94E066A0900B7B70E82A44FB30053"
269 "C1"
270 "028181" // INTEGER length 0x81 (exponent1)
271 "00AD15DA1CBD6A492B66851BA8C316D3"
272 "8AB700E2CFDDD926A658003513C54BAA"
273 "152B30021D667D20078F500F8AD3E7F3"
274 "945D74A891ED1A28EAD0FEEAEC8C14A8"
275 "E834CF46A13D1378C99D18940823CFDD"
276 "27EC5810D59339E0C34198AC638E09C8"
277 "7CBB1B634A9864AE9F4D5EB2D53514F6"
278 "7B4CAEC048C8AB849A02E397618F3271"
279 "35"
280 "028180" // INTEGER length 0x80 (exponent2)
281 "1FA2C1A5331880A92D8F3E281C617108"
282 "BF38244F16E352E69ED417C7153F9EC3"
283 "18F211839C643DCF8B4DD67CE2AC312E"
284 "95178D5D952F06B1BF779F4916924B70"
285 "F582A23F11304E02A5E7565AE22A35E7"
286 "4FECC8B6FDC93F92A1A37703E4CF0E63"
287 "783BD02EB716A7ECBBFA606B10B74D01"
288 "579522E7EF84D91FC522292108D902C1"
289 "028180" // INTEGER length 0x80 (coefficient)
290 "796FE3825F9DCC85DF22D58690065D93"
291 "898ACD65C087BEA8DA3A63BF4549B795"
292 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
293 "0D74F40DED8E1102C52152A31B6165F8"
294 "3A6722AECFCC35A493D7634664B888A0"
295 "8D3EB034F12EA28BFEE346E205D33482"
296 "7F778B16ED40872BD29FCB36536B6E93"
297 "FFB06778696B4A9D81BB0A9423E63DE5"
298 // } end SEQUENCE (PrivateKey)
299 // } end SEQUENCE (PrivateKeyInfo)
300);
Selene Huange5727e62021-04-13 22:41:20 -0700301
David Drysdaled2cc8c22021-04-15 13:29:45 +0100302string ec_256_key = hex2str(
303 // RFC 5208 s5
304 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
305 "020100" // INTEGER length 1 value 0 (version)
306 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
307 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
308 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
309 "0608" // OBJECT IDENTIFIER length 8 (param)
310 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
311 // } end SEQUENCE (AlgorithmIdentifier)
312 "046d" // OCTET STRING length 0x6d (privateKey) holding...
313 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
314 "020101" // INTEGER length 1 value 1 (version)
315 "0420" // OCTET STRING length 0x20 (privateKey)
316 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
317 "941eed09366bc03299986481f3a4d859"
318 "a144" // TAG [1] len 0x44 (publicKey) {
319 "03420004bf85d7720d07c25461683bc6"
320 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
321 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
322 "bcc41c6eb00083cf3376d11fd44949e0"
323 "b2183bfe"
324 // } end SEQUENCE (ECPrivateKey)
325 // } end SEQUENCE (PrivateKeyInfo)
326);
Selene Huang31ab4042020-04-29 04:22:39 -0700327
David Drysdaled2cc8c22021-04-15 13:29:45 +0100328string ec_521_key = hex2str(
329 // RFC 5208 s5
330 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
331 "020100" // INTEGER length 1 value 0 (version)
332 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
333 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
334 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
335 "0605" // OBJECT IDENTIFIER length 5 (param)
336 "2B81040023" // 1.3.132.0.35 (secp521r1)
337 // } end SEQUENCE (AlgorithmIdentifier)
338 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
339 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
340 "020101" // INTEGER length 1 value 1 (version)
341 "0442" // OCTET STRING length 0x42 (privateKey)
342 "0011458C586DB5DAA92AFAB03F4FE46A"
343 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
344 "9D18D7D08B5BCFA0E53C75B064AD51C4"
345 "49BAE0258D54B94B1E885DED08ED4FB2"
346 "5CE9"
347 "A18189" // TAG [1] len 0x89 (publicKey) {
348 "03818600040149EC11C6DF0FA122C6A9"
349 "AFD9754A4FA9513A627CA329E349535A"
350 "5629875A8ADFBE27DCB932C051986377"
351 "108D054C28C6F39B6F2C9AF81802F9F3"
352 "26B842FF2E5F3C00AB7635CFB36157FC"
353 "0882D574A10D839C1A0C049DC5E0D775"
354 "E2EE50671A208431BB45E78E70BEFE93"
355 "0DB34818EE4D5C26259F5C6B8E28A652"
356 "950F9F88D7B4B2C9D9"
357 // } end SEQUENCE (ECPrivateKey)
358 // } end SEQUENCE (PrivateKeyInfo)
359);
Selene Huang31ab4042020-04-29 04:22:39 -0700360
David Drysdaled2cc8c22021-04-15 13:29:45 +0100361string ec_256_key_rfc5915 = hex2str(
362 // RFC 5208 s5
363 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
364 "020100" // INTEGER length 1 value 0 (version)
365 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
366 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
367 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
368 "0608" // OBJECT IDENTIFIER length 8 (param)
369 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
370 // } end SEQUENCE (AlgorithmIdentifier)
371 "0479" // OCTET STRING length 0x79 (privateKey) holding...
372 // RFC 5915 s3
373 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
374 "020101" // INTEGER length 1 value 1 (version)
375 "0420" // OCTET STRING length 0x42 (privateKey)
376 "782370a8c8ce5537baadd04dcff079c8"
377 "158cfa9c67b818b38e8d21c9fa750c1d"
378 "a00a" // TAG [0] length 0xa (parameters)
379 "0608" // OBJECT IDENTIFIER length 8
380 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
381 // } end TAG [0]
382 "a144" // TAG [1] length 0x44 (publicKey) {
383 "0342" // BIT STRING length 0x42
384 "00" // no pad bits
385 "04e2cc561ee701da0ad0ef0d176bb0c9"
386 "19d42e79c393fdc1bd6c4010d85cf2cf"
387 "8e68c905464666f98dad4f01573ba810"
388 "78b3428570a439ba3229fbc026c55068"
389 "2f"
390 // } end SEQUENCE (ECPrivateKey)
391 // } end SEQUENCE (PrivateKeyInfo)
392);
Selene Huang31ab4042020-04-29 04:22:39 -0700393
David Drysdaled2cc8c22021-04-15 13:29:45 +0100394string ec_256_key_sec1 = hex2str(
395 // RFC 5208 s5
396 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
397 "020100" // INTEGER length 1 value 0 (version)
398 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
399 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
400 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
401 "0608" // OBJECT IDENTIFIER length 8 (param)
402 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
403 // } end SEQUENCE (AlgorithmIdentifier)
404 "046d" // OCTET STRING length 0x6d (privateKey) holding...
405 // SEC1-v2 C.4
406 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
407 "020101" // INTEGER length 1 value 0x01 (version)
408 "0420" // OCTET STRING length 0x20 (privateKey)
409 "782370a8c8ce5537baadd04dcff079c8"
410 "158cfa9c67b818b38e8d21c9fa750c1d"
411 "a144" // TAG [1] length 0x44 (publicKey) {
412 "0342" // BIT STRING length 0x42
413 "00" // no pad bits
414 "04e2cc561ee701da0ad0ef0d176bb0c9"
415 "19d42e79c393fdc1bd6c4010d85cf2cf"
416 "8e68c905464666f98dad4f01573ba810"
417 "78b3428570a439ba3229fbc026c55068"
418 "2f"
419 // } end TAG [1] (publicKey)
420 // } end SEQUENCE (PrivateKeyInfo)
421);
Selene Huang31ab4042020-04-29 04:22:39 -0700422
David Drysdale42fe1892021-10-14 14:43:46 +0100423/**
424 * Ed25519 key pair generated as follows:
425 * ```
426 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
427 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
428 * Generating a ED25519 private key writing new private key to
429 * 'ed25519_priv.key'
430 * -----
431 * % cat ed25519_priv.key
432 * -----BEGIN PRIVATE KEY-----
433 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
434 * -----END PRIVATE KEY-----
435 * % der2ascii -pem -i ed25519_priv.key
436 * SEQUENCE {
437 * INTEGER { 0 }
438 * SEQUENCE {
439 * # ed25519
440 * OBJECT_IDENTIFIER { 1.3.101.112 }
441 * }
442 * OCTET_STRING {
443 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
444 * }
445 * }
446 * % cat ed25519.pem
447 * -----BEGIN CERTIFICATE-----
448 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
449 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
450 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
451 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
452 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
453 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
454 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
455 * -----END CERTIFICATE-----
456 * % openssl x509 -in ed25519.pem -text -noout
457 * Certificate:
458 * Data:
459 * Version: 3 (0x2)
460 * Serial Number:
461 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
462 * Signature Algorithm: ED25519
463 * Issuer: CN = fake.ed25519.com
464 * Validity
465 * Not Before: Oct 20 08:27:42 2021 GMT
466 * Not After : Sep 20 08:27:42 2023 GMT
467 * Subject: CN = fake.ed25519.com
468 * Subject Public Key Info:
469 * Public Key Algorithm: ED25519
470 * ED25519 Public-Key:
471 * pub:
472 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
473 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
474 * 56:91
475 * X509v3 extensions:
476 * X509v3 Subject Key Identifier:
477 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
478 * X509v3 Authority Key Identifier:
479 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
480 *
481 * X509v3 Basic Constraints: critical
482 * CA:TRUE
483 * Signature Algorithm: ED25519
484 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
485 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
486 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
487 * e7:07:32:60:32:8d:bb:eb:f6:0f
488 * ```
489 */
490string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
491string ed25519_pkcs8_key = hex2str(
492 // RFC 5208 s5
493 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
494 "0201" // INTEGER length 1 (Version)
495 "00" // version 0
496 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
497 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
498 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
499 // } end SEQUENCE (AlgorithmIdentifier)
500 "0422" // OCTET STRING length 0x22 (PrivateKey)
501 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
502 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
503 // } end SEQUENCE (PrivateKeyInfo)
504);
505string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
506
507/**
508 * X25519 key pair generated as follows:
509 * ```
510 * % openssl genpkey -algorithm X25519 > x25519_priv.key
511 * % cat x25519_priv.key
512 * -----BEGIN PRIVATE KEY-----
513 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
514 * -----END PRIVATE KEY-----
515 * % der2ascii -pem -i x25519_priv.key
516 * SEQUENCE {
517 * INTEGER { 0 }
518 * SEQUENCE {
519 * # x25519
520 * OBJECT_IDENTIFIER { 1.3.101.110 }
521 * }
522 * OCTET_STRING {
523 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
524 * }
525 * }
526 * ```
527 */
528
529string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
530string x25519_pkcs8_key = hex2str(
531 // RFC 5208 s5
532 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
533 "0201" // INTEGER length 1 (Version)
534 "00" // version 0
535 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
536 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
537 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
538 "0422" // OCTET STRING length 0x22 (PrivateKey)
539 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
540 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
541string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
542
Selene Huang31ab4042020-04-29 04:22:39 -0700543struct RSA_Delete {
544 void operator()(RSA* p) { RSA_free(p); }
545};
546
Selene Huang31ab4042020-04-29 04:22:39 -0700547std::string make_string(const uint8_t* data, size_t length) {
548 return std::string(reinterpret_cast<const char*>(data), length);
549}
550
551template <size_t N>
552std::string make_string(const uint8_t (&a)[N]) {
553 return make_string(a, N);
554}
555
556class AidlBuf : public vector<uint8_t> {
557 typedef vector<uint8_t> super;
558
559 public:
560 AidlBuf() {}
561 AidlBuf(const super& other) : super(other) {}
562 AidlBuf(super&& other) : super(std::move(other)) {}
563 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
564
565 AidlBuf& operator=(const super& other) {
566 super::operator=(other);
567 return *this;
568 }
569
570 AidlBuf& operator=(super&& other) {
571 super::operator=(std::move(other));
572 return *this;
573 }
574
575 AidlBuf& operator=(const string& other) {
576 resize(other.size());
577 for (size_t i = 0; i < other.size(); ++i) {
578 (*this)[i] = static_cast<uint8_t>(other[i]);
579 }
580 return *this;
581 }
582
583 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
584};
585
David Drysdale4dc01072021-04-01 12:17:35 +0100586string device_suffix(const string& name) {
587 size_t pos = name.find('/');
588 if (pos == string::npos) {
589 return name;
590 }
591 return name.substr(pos + 1);
592}
593
Seth Moore5a0320f2023-03-24 12:29:08 -0700594std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700604 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100605 }
606 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700607 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100608}
609
Selene Huang31ab4042020-04-29 04:22:39 -0700610} // namespace
611
612class NewKeyGenerationTest : public KeyMintAidlTestBase {
613 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700614 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000615 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700616 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700617
Selene Huang31ab4042020-04-29 04:22:39 -0700618 // Check that some unexpected tags/values are NOT present.
619 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000621 }
622
623 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000624 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000625 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
627
628 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000629 }
630
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000631 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
632 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100696 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000697
698 EXPECT_GT(key_blob.size(), 0U);
699 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100700 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
703
704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
705 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
706 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000707 }
708 }
709 }
710}
711
712/*
713 * NewKeyGenerationTest.AesInvalidSize
714 *
715 * Verifies that specifying an invalid key size for AES key generation returns
716 * UNSUPPORTED_KEY_SIZE.
717 */
718TEST_P(NewKeyGenerationTest, AesInvalidSize) {
719 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
720 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
721 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
722 SCOPED_TRACE(testing::Message()
723 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
724 vector<uint8_t> key_blob;
725 vector<KeyCharacteristics> key_characteristics;
726 auto builder = AuthorizationSetBuilder()
727 .AesEncryptionKey(key_size)
728 .BlockMode(block_mode)
729 .Padding(padding_mode)
730 .SetDefaultValidity();
731 if (block_mode == BlockMode::GCM) {
732 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
733 }
734 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
735 GenerateKey(builder, &key_blob, &key_characteristics));
736 }
737 }
738 }
739
740 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
741 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100742 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100879 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000880
881 EXPECT_GT(key_blob.size(), 0U);
882 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100883 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000884
885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000890 }
891 }
892 }
893}
894
895/*
896 * NewKeyGenerationTest.TripleDesWithAttestation
897 *
898 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
899 * have correct characteristics.
900 *
901 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
902 * put in a certificate) but which isn't an error.
903 */
904TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
905 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
906 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
907 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
908 SCOPED_TRACE(testing::Message()
909 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
910
911 auto challenge = "hello";
912 auto app_id = "foo";
913
914 vector<uint8_t> key_blob;
915 vector<KeyCharacteristics> key_characteristics;
916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
917 .TripleDesEncryptionKey(key_size)
918 .BlockMode(block_mode)
919 .Padding(padding_mode)
920 .Authorization(TAG_NO_AUTH_REQUIRED)
921 .AttestationChallenge(challenge)
922 .AttestationApplicationId(app_id)
923 .SetDefaultValidity(),
924 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100925 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000936 }
937 }
938 }
939}
940
941/*
942 * NewKeyGenerationTest.TripleDesInvalidSize
943 *
944 * Verifies that specifying an invalid key size for 3-DES key generation returns
945 * UNSUPPORTED_KEY_SIZE.
946 */
947TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
948 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
949 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
950 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
951 SCOPED_TRACE(testing::Message()
952 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
953 vector<uint8_t> key_blob;
954 vector<KeyCharacteristics> key_characteristics;
955 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
956 GenerateKey(AuthorizationSetBuilder()
957 .TripleDesEncryptionKey(key_size)
958 .BlockMode(block_mode)
959 .Padding(padding_mode)
960 .Authorization(TAG_NO_AUTH_REQUIRED)
961 .SetDefaultValidity(),
962 &key_blob, &key_characteristics));
963 }
964 }
965 }
966
967 // Omitting the key size fails.
968 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
969 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
970 SCOPED_TRACE(testing::Message()
971 << "3DES-default-" << block_mode << "-" << padding_mode);
972 vector<uint8_t> key_blob;
973 vector<KeyCharacteristics> key_characteristics;
974 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
975 GenerateKey(AuthorizationSetBuilder()
976 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
977 .BlockMode(block_mode)
978 .Padding(padding_mode)
979 .Authorization(TAG_NO_AUTH_REQUIRED)
980 .SetDefaultValidity(),
981 &key_blob, &key_characteristics));
982 }
983 }
984}
985
986/*
Selene Huang31ab4042020-04-29 04:22:39 -0700987 * NewKeyGenerationTest.Rsa
988 *
989 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
990 * have correct characteristics.
991 */
992TEST_P(NewKeyGenerationTest, Rsa) {
993 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100994 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700995 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700996 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700997 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
998 .RsaSigningKey(key_size, 65537)
999 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001000 .Padding(PaddingMode::NONE)
1001 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001002 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001003 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
Selene Huang31ab4042020-04-29 04:22:39 -07001015 }
1016}
1017
1018/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001019 * NewKeyGenerationTest.RsaWithMissingValidity
1020 *
1021 * Verifies that keymint returns an error while generating asymmetric key
1022 * without providing NOT_BEFORE and NOT_AFTER parameters.
1023 */
1024TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001025 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001026 /*
1027 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1028 * specified for asymmetric key generation. However, this was not
1029 * checked at the time so we can only be strict about checking this for
1030 * implementations of KeyMint version 2 and above.
1031 */
1032 GTEST_SKIP() << "Validity strict since KeyMint v2";
1033 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001034 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1035 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1036 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1037
1038 vector<uint8_t> key_blob;
1039 vector<KeyCharacteristics> key_characteristics;
1040 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1041 GenerateKey(AuthorizationSetBuilder()
1042 .RsaSigningKey(2048, 65537)
1043 .Digest(Digest::NONE)
1044 .Padding(PaddingMode::NONE)
1045 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1046 kUndefinedExpirationDateTime),
1047 &key_blob, &key_characteristics));
1048
1049 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1050 GenerateKey(AuthorizationSetBuilder()
1051 .RsaSigningKey(2048, 65537)
1052 .Digest(Digest::NONE)
1053 .Padding(PaddingMode::NONE)
1054 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1055 &key_blob, &key_characteristics));
1056}
1057
1058/*
David Drysdalead785f52023-03-27 19:53:01 +01001059 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1060 *
1061 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1062 */
1063TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1064 vector<uint8_t> key_blob;
1065 vector<KeyCharacteristics> key_characteristics;
1066 ASSERT_EQ(ErrorCode::OK,
1067 GenerateKey(AuthorizationSetBuilder()
1068 .RsaSigningKey(2048, 65537)
1069 .Digest(Digest::NONE)
1070 .Padding(PaddingMode::NONE)
1071 .Authorization(TAG_CERTIFICATE_NOT_BEFORE,
1072 1183806000000 /* 2007-07-07T11:00:00Z */)
1073 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1074 1916049600000 /* 2030-09-19T12:00:00Z */),
1075 &key_blob, &key_characteristics));
1076 ASSERT_GT(cert_chain_.size(), 0);
1077
1078 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1079 ASSERT_TRUE(!!cert.get());
1080
1081 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1082 ASSERT_NE(not_before, nullptr);
1083 time_t not_before_time;
1084 ASSERT_EQ(ASN1_TIME_to_time_t(not_before, &not_before_time), 1);
1085 EXPECT_EQ(not_before_time, 1183806000);
1086
1087 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1088 ASSERT_NE(not_after, nullptr);
1089 time_t not_after_time;
1090 ASSERT_EQ(ASN1_TIME_to_time_t(not_after, &not_after_time), 1);
1091 EXPECT_EQ(not_after_time, 1916049600);
1092}
1093
1094/*
Qi Wud22ec842020-11-26 13:27:53 +08001095 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001096 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001097 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1098 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001099 */
1100TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001101 auto challenge = "hello";
1102 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001103
Selene Huang6e46f142021-04-20 19:20:11 -07001104 auto subject = "cert subj 2";
1105 vector<uint8_t> subject_der(make_name_from_str(subject));
1106
1107 uint64_t serial_int = 66;
1108 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1109
Selene Huang4f64c222021-04-13 19:54:36 -07001110 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001111 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001112 vector<uint8_t> key_blob;
1113 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001114 auto builder = AuthorizationSetBuilder()
1115 .RsaSigningKey(key_size, 65537)
1116 .Digest(Digest::NONE)
1117 .Padding(PaddingMode::NONE)
1118 .AttestationChallenge(challenge)
1119 .AttestationApplicationId(app_id)
1120 .Authorization(TAG_NO_AUTH_REQUIRED)
1121 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1122 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1123 .SetDefaultValidity();
1124
1125 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001126 // Strongbox may not support factory provisioned attestation key.
1127 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001128 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1129 result = GenerateKeyWithSelfSignedAttestKey(
1130 AuthorizationSetBuilder()
1131 .RsaKey(key_size, 65537)
1132 .AttestKey()
1133 .SetDefaultValidity(), /* attest key params */
1134 builder, &key_blob, &key_characteristics);
1135 }
subrahmanyaman05642492022-02-05 07:10:56 +00001136 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001137 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001138 KeyBlobDeleter deleter(keymint_, key_blob);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001139 ASSERT_GT(key_blob.size(), 0U);
1140 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001141 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001142
1143 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1144
1145 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1146 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1147 << "Key size " << key_size << "missing";
1148 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1149
David Drysdalea8a888e2022-06-08 12:43:56 +01001150 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001151 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001152 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001153
1154 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1155 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001156 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001157 sw_enforced, hw_enforced, SecLevel(),
1158 cert_chain_[0].encodedCertificate));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001159 }
1160}
1161
1162/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001163 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001164 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001165 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001166 * that has been generated using an associate IRemotelyProvisionedComponent.
1167 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001168TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001169 if (!IsRkpSupportRequired()) {
1170 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001171 }
1172
Seth Moore5a0320f2023-03-24 12:29:08 -07001173 // Check for an IRemotelyProvisionedComponent instance associated with the
1174 // KeyMint instance.
1175 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1176 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1177 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1178 }
1179 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1180 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001181
1182 // Generate a P-256 keypair to use as an attestation key.
1183 MacedPublicKey macedPubKey;
1184 std::vector<uint8_t> privateKeyBlob;
1185 auto status =
1186 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1187 ASSERT_TRUE(status.isOk());
1188 vector<uint8_t> coseKeyData;
1189 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1190
1191 AttestationKey attestation_key;
1192 attestation_key.keyBlob = std::move(privateKeyBlob);
1193 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1194
1195 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001196 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001197 auto challenge = "hello";
1198 auto app_id = "foo";
1199
1200 vector<uint8_t> key_blob;
1201 vector<KeyCharacteristics> key_characteristics;
1202 ASSERT_EQ(ErrorCode::OK,
1203 GenerateKey(AuthorizationSetBuilder()
1204 .RsaSigningKey(key_size, 65537)
1205 .Digest(Digest::NONE)
1206 .Padding(PaddingMode::NONE)
1207 .AttestationChallenge(challenge)
1208 .AttestationApplicationId(app_id)
1209 .Authorization(TAG_NO_AUTH_REQUIRED)
1210 .SetDefaultValidity(),
1211 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001212 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale4dc01072021-04-01 12:17:35 +01001213
1214 ASSERT_GT(key_blob.size(), 0U);
1215 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001216 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001217
1218 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1219
1220 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1221 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1222 << "Key size " << key_size << "missing";
1223 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1224
1225 // Attestation by itself is not valid (last entry is not self-signed).
1226 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1227
1228 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001229 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001230 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1231 ASSERT_TRUE(key_cert.get());
1232 EVP_PKEY_Ptr signing_pubkey;
1233 p256_pub_key(coseKeyData, &signing_pubkey);
1234 ASSERT_TRUE(signing_pubkey.get());
1235
1236 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1237 << "Verification of attested certificate failed "
1238 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
David Drysdale4dc01072021-04-01 12:17:35 +01001239 }
1240}
1241
1242/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001243 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1244 *
1245 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1246 * that has been generated using an associate IRemotelyProvisionedComponent.
1247 */
1248TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001249 if (!IsRkpSupportRequired()) {
1250 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001251 }
1252
Seth Moore5a0320f2023-03-24 12:29:08 -07001253 // Check for an IRemotelyProvisionedComponent instance associated with the
1254 // KeyMint instance.
1255 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1256 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1257 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1258 }
1259 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1260 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001261
1262 // Generate a P-256 keypair to use as an attestation key.
1263 MacedPublicKey macedPubKey;
1264 std::vector<uint8_t> privateKeyBlob;
1265 auto status =
1266 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1267 ASSERT_TRUE(status.isOk());
1268 vector<uint8_t> coseKeyData;
1269 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1270
1271 AttestationKey attestation_key;
1272 attestation_key.keyBlob = std::move(privateKeyBlob);
1273 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1274
1275 for (auto curve : ValidCurves()) {
1276 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1277 auto challenge = "hello";
1278 auto app_id = "foo";
1279
1280 vector<uint8_t> key_blob;
1281 vector<KeyCharacteristics> key_characteristics;
1282 ASSERT_EQ(ErrorCode::OK,
1283 GenerateKey(AuthorizationSetBuilder()
1284 .EcdsaSigningKey(curve)
1285 .Digest(Digest::NONE)
1286 .AttestationChallenge(challenge)
1287 .AttestationApplicationId(app_id)
1288 .Authorization(TAG_NO_AUTH_REQUIRED)
1289 .SetDefaultValidity(),
1290 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001291 KeyBlobDeleter deleter(keymint_, key_blob);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001292
1293 ASSERT_GT(key_blob.size(), 0U);
1294 CheckBaseParams(key_characteristics);
1295 CheckCharacteristics(key_blob, key_characteristics);
1296
1297 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1298
1299 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1300 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1301
1302 // Attestation by itself is not valid (last entry is not self-signed).
1303 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1304
1305 // The signature over the attested key should correspond to the P256 public key.
1306 ASSERT_GT(cert_chain_.size(), 0);
1307 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1308 ASSERT_TRUE(key_cert.get());
1309 EVP_PKEY_Ptr signing_pubkey;
1310 p256_pub_key(coseKeyData, &signing_pubkey);
1311 ASSERT_TRUE(signing_pubkey.get());
1312
1313 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1314 << "Verification of attested certificate failed "
1315 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001316 }
1317}
1318
1319/*
Selene Huang4f64c222021-04-13 19:54:36 -07001320 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1321 *
1322 * Verifies that keymint attestation for RSA encryption keys with challenge and
1323 * app id is also successful.
1324 */
1325TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1326 auto key_size = 2048;
1327 auto challenge = "hello";
1328 auto app_id = "foo";
1329
Selene Huang6e46f142021-04-20 19:20:11 -07001330 auto subject = "subj 2";
1331 vector<uint8_t> subject_der(make_name_from_str(subject));
1332
1333 uint64_t serial_int = 111166;
1334 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1335
Selene Huang4f64c222021-04-13 19:54:36 -07001336 vector<uint8_t> key_blob;
1337 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001338 auto builder = AuthorizationSetBuilder()
1339 .RsaEncryptionKey(key_size, 65537)
1340 .Padding(PaddingMode::NONE)
1341 .AttestationChallenge(challenge)
1342 .AttestationApplicationId(app_id)
1343 .Authorization(TAG_NO_AUTH_REQUIRED)
1344 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1345 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1346 .SetDefaultValidity();
1347
1348 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001349 // Strongbox may not support factory provisioned attestation key.
1350 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001351 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1352 result = GenerateKeyWithSelfSignedAttestKey(
1353 AuthorizationSetBuilder()
1354 .RsaKey(key_size, 65537)
1355 .AttestKey()
1356 .SetDefaultValidity(), /* attest key params */
1357 builder, &key_blob, &key_characteristics);
1358 }
subrahmanyaman05642492022-02-05 07:10:56 +00001359 }
1360 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001361 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001362
1363 ASSERT_GT(key_blob.size(), 0U);
1364 AuthorizationSet auths;
1365 for (auto& entry : key_characteristics) {
1366 auths.push_back(AuthorizationSet(entry.authorizations));
1367 }
1368
1369 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1370 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1371
1372 // Verify that App data and ROT are NOT included.
1373 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1374 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1375
1376 // Check that some unexpected tags/values are NOT present.
1377 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1378 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1379
1380 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1381
1382 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1383 ASSERT_TRUE(os_ver);
1384 EXPECT_EQ(*os_ver, os_version());
1385
1386 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1387
1388 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1389 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1390 << "Key size " << key_size << "missing";
1391 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1392
David Drysdalea8a888e2022-06-08 12:43:56 +01001393 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001394 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001395 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001396
1397 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1398 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001399 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001400 sw_enforced, hw_enforced, SecLevel(),
1401 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001402}
1403
1404/*
1405 * NewKeyGenerationTest.RsaWithSelfSign
1406 *
1407 * Verifies that attesting to RSA key generation is successful, and returns
1408 * self signed certificate if no challenge is provided. And signing etc
1409 * works as expected.
1410 */
1411TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001412 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1413 vector<uint8_t> subject_der(make_name_from_str(subject));
1414
1415 uint64_t serial_int = 0;
1416 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1417
Selene Huang4f64c222021-04-13 19:54:36 -07001418 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001419 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001420 vector<uint8_t> key_blob;
1421 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001422 ASSERT_EQ(ErrorCode::OK,
1423 GenerateKey(AuthorizationSetBuilder()
1424 .RsaSigningKey(key_size, 65537)
1425 .Digest(Digest::NONE)
1426 .Padding(PaddingMode::NONE)
1427 .Authorization(TAG_NO_AUTH_REQUIRED)
1428 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1429 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1430 .SetDefaultValidity(),
1431 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001432 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001433
1434 ASSERT_GT(key_blob.size(), 0U);
1435 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001436 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001437
1438 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1439
1440 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1441 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1442 << "Key size " << key_size << "missing";
1443 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1444
David Drysdalea8a888e2022-06-08 12:43:56 +01001445 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001446 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001447 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001448 }
1449}
1450
1451/*
1452 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1453 *
1454 * Verifies that attesting to RSA checks for missing app ID.
1455 */
1456TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1457 auto challenge = "hello";
1458 vector<uint8_t> key_blob;
1459 vector<KeyCharacteristics> key_characteristics;
1460
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001461 auto builder = AuthorizationSetBuilder()
1462 .RsaSigningKey(2048, 65537)
1463 .Digest(Digest::NONE)
1464 .Padding(PaddingMode::NONE)
1465 .AttestationChallenge(challenge)
1466 .Authorization(TAG_NO_AUTH_REQUIRED)
1467 .SetDefaultValidity();
1468
1469 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001470 // Strongbox may not support factory provisioned attestation key.
1471 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001472 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1473 result = GenerateKeyWithSelfSignedAttestKey(
1474 AuthorizationSetBuilder()
1475 .RsaKey(2048, 65537)
1476 .AttestKey()
1477 .SetDefaultValidity(), /* attest key params */
1478 builder, &key_blob, &key_characteristics);
1479 }
subrahmanyaman05642492022-02-05 07:10:56 +00001480 }
1481 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001482}
1483
1484/*
1485 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1486 *
1487 * Verifies that attesting to RSA ignores app id if challenge is missing.
1488 */
1489TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1490 auto key_size = 2048;
1491 auto app_id = "foo";
1492
Selene Huang6e46f142021-04-20 19:20:11 -07001493 auto subject = "cert subj 2";
1494 vector<uint8_t> subject_der(make_name_from_str(subject));
1495
1496 uint64_t serial_int = 1;
1497 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1498
Selene Huang4f64c222021-04-13 19:54:36 -07001499 vector<uint8_t> key_blob;
1500 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001501 ASSERT_EQ(ErrorCode::OK,
1502 GenerateKey(AuthorizationSetBuilder()
1503 .RsaSigningKey(key_size, 65537)
1504 .Digest(Digest::NONE)
1505 .Padding(PaddingMode::NONE)
1506 .AttestationApplicationId(app_id)
1507 .Authorization(TAG_NO_AUTH_REQUIRED)
1508 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1509 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1510 .SetDefaultValidity(),
1511 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001512 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001513
1514 ASSERT_GT(key_blob.size(), 0U);
1515 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001516 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001517
1518 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1519
1520 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1521 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1522 << "Key size " << key_size << "missing";
1523 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1524
David Drysdalea8a888e2022-06-08 12:43:56 +01001525 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001526 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001527 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1528 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang4f64c222021-04-13 19:54:36 -07001529}
1530
1531/*
Qi Wud22ec842020-11-26 13:27:53 +08001532 * NewKeyGenerationTest.LimitedUsageRsa
1533 *
1534 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1535 * resulting keys have correct characteristics.
1536 */
1537TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1538 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001539 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001540 vector<uint8_t> key_blob;
1541 vector<KeyCharacteristics> key_characteristics;
1542 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1543 .RsaSigningKey(key_size, 65537)
1544 .Digest(Digest::NONE)
1545 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001546 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1547 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001548 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001549 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08001550
1551 ASSERT_GT(key_blob.size(), 0U);
1552 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001553 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001554
1555 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1556
1557 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1558 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1559 << "Key size " << key_size << "missing";
1560 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1561
1562 // Check the usage count limit tag appears in the authorizations.
1563 AuthorizationSet auths;
1564 for (auto& entry : key_characteristics) {
1565 auths.push_back(AuthorizationSet(entry.authorizations));
1566 }
1567 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1568 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08001569 }
1570}
1571
1572/*
Qi Wubeefae42021-01-28 23:16:37 +08001573 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1574 *
1575 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1576 * resulting keys have correct characteristics and attestation.
1577 */
1578TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001579 auto challenge = "hello";
1580 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001581
Selene Huang6e46f142021-04-20 19:20:11 -07001582 auto subject = "cert subj 2";
1583 vector<uint8_t> subject_der(make_name_from_str(subject));
1584
1585 uint64_t serial_int = 66;
1586 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1587
Selene Huang4f64c222021-04-13 19:54:36 -07001588 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001589 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001590 vector<uint8_t> key_blob;
1591 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001592 auto builder = AuthorizationSetBuilder()
1593 .RsaSigningKey(key_size, 65537)
1594 .Digest(Digest::NONE)
1595 .Padding(PaddingMode::NONE)
1596 .AttestationChallenge(challenge)
1597 .AttestationApplicationId(app_id)
1598 .Authorization(TAG_NO_AUTH_REQUIRED)
1599 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1600 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1601 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1602 .SetDefaultValidity();
1603
1604 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001605 // Strongbox may not support factory provisioned attestation key.
1606 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001607 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1608 result = GenerateKeyWithSelfSignedAttestKey(
1609 AuthorizationSetBuilder()
1610 .RsaKey(key_size, 65537)
1611 .AttestKey()
1612 .SetDefaultValidity(), /* attest key params */
1613 builder, &key_blob, &key_characteristics);
1614 }
subrahmanyaman05642492022-02-05 07:10:56 +00001615 }
1616 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001617 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wubeefae42021-01-28 23:16:37 +08001618
1619 ASSERT_GT(key_blob.size(), 0U);
1620 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001621 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001622
1623 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1624
1625 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1626 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1627 << "Key size " << key_size << "missing";
1628 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1629
1630 // Check the usage count limit tag appears in the authorizations.
1631 AuthorizationSet auths;
1632 for (auto& entry : key_characteristics) {
1633 auths.push_back(AuthorizationSet(entry.authorizations));
1634 }
1635 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1636 << "key usage count limit " << 1U << " missing";
1637
1638 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001639 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001640 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001641 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001642
1643 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1644 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001645 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001646 sw_enforced, hw_enforced, SecLevel(),
1647 cert_chain_[0].encodedCertificate));
Qi Wubeefae42021-01-28 23:16:37 +08001648 }
1649}
1650
1651/*
Selene Huang31ab4042020-04-29 04:22:39 -07001652 * NewKeyGenerationTest.NoInvalidRsaSizes
1653 *
1654 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1655 */
1656TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1657 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001658 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001659 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001660 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001661 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1662 GenerateKey(AuthorizationSetBuilder()
1663 .RsaSigningKey(key_size, 65537)
1664 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001665 .Padding(PaddingMode::NONE)
1666 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001667 &key_blob, &key_characteristics));
1668 }
1669}
1670
1671/*
1672 * NewKeyGenerationTest.RsaNoDefaultSize
1673 *
1674 * Verifies that failing to specify a key size for RSA key generation returns
1675 * UNSUPPORTED_KEY_SIZE.
1676 */
1677TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1678 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1679 GenerateKey(AuthorizationSetBuilder()
1680 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1681 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001682 .SigningKey()
1683 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001684}
1685
1686/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001687 * NewKeyGenerationTest.RsaMissingParams
1688 *
1689 * Verifies that omitting optional tags works.
1690 */
1691TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1692 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001693 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001694 ASSERT_EQ(ErrorCode::OK,
1695 GenerateKey(
1696 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1697 CheckedDeleteKey();
1698 }
1699}
1700
1701/*
Selene Huang31ab4042020-04-29 04:22:39 -07001702 * NewKeyGenerationTest.Ecdsa
1703 *
David Drysdale42fe1892021-10-14 14:43:46 +01001704 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001705 * have correct characteristics.
1706 */
1707TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001708 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001709 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001710 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001711 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001712 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001713 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001714 .Digest(Digest::NONE)
1715 .SetDefaultValidity(),
1716 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001717 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001718 ASSERT_GT(key_blob.size(), 0U);
1719 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001720 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001721
Shawn Willden7f424372021-01-10 18:06:50 -07001722 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001723
1724 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001725 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001726 }
1727}
1728
1729/*
David Drysdale42fe1892021-10-14 14:43:46 +01001730 * NewKeyGenerationTest.EcdsaCurve25519
1731 *
1732 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1733 * has correct characteristics.
1734 */
1735TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1736 if (!Curve25519Supported()) {
1737 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1738 }
1739
1740 EcCurve curve = EcCurve::CURVE_25519;
1741 vector<uint8_t> key_blob;
1742 vector<KeyCharacteristics> key_characteristics;
1743 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1744 .EcdsaSigningKey(curve)
1745 .Digest(Digest::NONE)
1746 .SetDefaultValidity(),
1747 &key_blob, &key_characteristics);
1748 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001749 KeyBlobDeleter deleter(keymint_, key_blob);
1750
David Drysdale42fe1892021-10-14 14:43:46 +01001751 ASSERT_GT(key_blob.size(), 0U);
1752
1753 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1754 ASSERT_GT(cert_chain_.size(), 0);
1755
1756 CheckBaseParams(key_characteristics);
1757 CheckCharacteristics(key_blob, key_characteristics);
1758
1759 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1760
1761 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1762 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
David Drysdale42fe1892021-10-14 14:43:46 +01001763}
1764
1765/*
1766 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1767 *
1768 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1769 * SIGN and AGREE_KEY.
1770 */
1771TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1772 if (!Curve25519Supported()) {
1773 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1774 }
1775
1776 EcCurve curve = EcCurve::CURVE_25519;
1777 vector<uint8_t> key_blob;
1778 vector<KeyCharacteristics> key_characteristics;
1779 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1780 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1781 .EcdsaSigningKey(curve)
1782 .Digest(Digest::NONE)
1783 .SetDefaultValidity(),
1784 &key_blob, &key_characteristics);
1785 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1786}
1787
1788/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001789 * NewKeyGenerationTest.EcdsaWithMissingValidity
1790 *
1791 * Verifies that keymint returns an error while generating asymmetric key
1792 * without providing NOT_BEFORE and NOT_AFTER parameters.
1793 */
1794TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001795 if (AidlVersion() < 2) {
1796 /*
1797 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1798 * specified for asymmetric key generation. However, this was not
1799 * checked at the time so we can only be strict about checking this for
1800 * implementations of KeyMint version 2 and above.
1801 */
1802 GTEST_SKIP() << "Validity strict since KeyMint v2";
1803 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001804 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1805 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1806 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1807
1808 vector<uint8_t> key_blob;
1809 vector<KeyCharacteristics> key_characteristics;
1810 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1811 GenerateKey(AuthorizationSetBuilder()
1812 .EcdsaSigningKey(EcCurve::P_256)
1813 .Digest(Digest::NONE)
1814 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1815 kUndefinedExpirationDateTime),
1816 &key_blob, &key_characteristics));
1817
1818 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1819 GenerateKey(AuthorizationSetBuilder()
1820 .EcdsaSigningKey(EcCurve::P_256)
1821 .Digest(Digest::NONE)
1822 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1823 &key_blob, &key_characteristics));
1824}
1825
1826/*
Selene Huang4f64c222021-04-13 19:54:36 -07001827 * NewKeyGenerationTest.EcdsaAttestation
1828 *
1829 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1830 * an attestation will be generated.
1831 */
1832TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1833 auto challenge = "hello";
1834 auto app_id = "foo";
1835
Selene Huang6e46f142021-04-20 19:20:11 -07001836 auto subject = "cert subj 2";
1837 vector<uint8_t> subject_der(make_name_from_str(subject));
1838
1839 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1840 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1841
David Drysdaledf09e542021-06-08 15:46:11 +01001842 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001843 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001844 vector<uint8_t> key_blob;
1845 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001846 auto builder = AuthorizationSetBuilder()
1847 .Authorization(TAG_NO_AUTH_REQUIRED)
1848 .EcdsaSigningKey(curve)
1849 .Digest(Digest::NONE)
1850 .AttestationChallenge(challenge)
1851 .AttestationApplicationId(app_id)
1852 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1853 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1854 .SetDefaultValidity();
1855
1856 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001857 // Strongbox may not support factory provisioned attestation key.
1858 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001859 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1860 result = GenerateKeyWithSelfSignedAttestKey(
1861 AuthorizationSetBuilder()
1862 .EcdsaKey(curve)
1863 .AttestKey()
1864 .SetDefaultValidity(), /* attest key params */
1865 builder, &key_blob, &key_characteristics);
1866 }
subrahmanyaman05642492022-02-05 07:10:56 +00001867 }
1868 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001869 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001870 ASSERT_GT(key_blob.size(), 0U);
1871 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001872 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001873
1874 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1875
1876 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001877 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001878
1879 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1880 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001881 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001882
1883 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1884 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001885 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001886 sw_enforced, hw_enforced, SecLevel(),
1887 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001888 }
1889}
1890
1891/*
David Drysdale42fe1892021-10-14 14:43:46 +01001892 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1893 *
1894 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1895 * an attestation will be generated.
1896 */
1897TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1898 if (!Curve25519Supported()) {
1899 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1900 }
1901
1902 EcCurve curve = EcCurve::CURVE_25519;
1903 auto challenge = "hello";
1904 auto app_id = "foo";
1905
1906 auto subject = "cert subj 2";
1907 vector<uint8_t> subject_der(make_name_from_str(subject));
1908
1909 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1910 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1911
1912 vector<uint8_t> key_blob;
1913 vector<KeyCharacteristics> key_characteristics;
1914 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1915 .Authorization(TAG_NO_AUTH_REQUIRED)
1916 .EcdsaSigningKey(curve)
1917 .Digest(Digest::NONE)
1918 .AttestationChallenge(challenge)
1919 .AttestationApplicationId(app_id)
1920 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1921 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1922 .SetDefaultValidity(),
1923 &key_blob, &key_characteristics);
1924 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001925 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale42fe1892021-10-14 14:43:46 +01001926 ASSERT_GT(key_blob.size(), 0U);
1927 CheckBaseParams(key_characteristics);
1928 CheckCharacteristics(key_blob, key_characteristics);
1929
1930 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1931
1932 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1933 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1934
1935 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1936 ASSERT_GT(cert_chain_.size(), 0);
1937 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1938
1939 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1940 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1941 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1942 sw_enforced, hw_enforced, SecLevel(),
1943 cert_chain_[0].encodedCertificate));
David Drysdale42fe1892021-10-14 14:43:46 +01001944}
1945
1946/*
David Drysdale37af4b32021-05-14 16:46:59 +01001947 * NewKeyGenerationTest.EcdsaAttestationTags
1948 *
1949 * Verifies that creation of an attested ECDSA key includes various tags in the
1950 * attestation extension.
1951 */
1952TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1953 auto challenge = "hello";
1954 auto app_id = "foo";
1955 auto subject = "cert subj 2";
1956 vector<uint8_t> subject_der(make_name_from_str(subject));
1957 uint64_t serial_int = 0x1010;
1958 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1959 const AuthorizationSetBuilder base_builder =
1960 AuthorizationSetBuilder()
1961 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001962 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001963 .Digest(Digest::NONE)
1964 .AttestationChallenge(challenge)
1965 .AttestationApplicationId(app_id)
1966 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1967 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1968 .SetDefaultValidity();
1969
1970 // Various tags that map to fields in the attestation extension ASN.1 schema.
1971 auto extra_tags = AuthorizationSetBuilder()
1972 .Authorization(TAG_ROLLBACK_RESISTANCE)
1973 .Authorization(TAG_EARLY_BOOT_ONLY)
1974 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1975 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1976 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1977 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1978 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1979 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1980 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1981 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1982 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1983 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001984
David Drysdale37af4b32021-05-14 16:46:59 +01001985 for (const KeyParameter& tag : extra_tags) {
1986 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1987 vector<uint8_t> key_blob;
1988 vector<KeyCharacteristics> key_characteristics;
1989 AuthorizationSetBuilder builder = base_builder;
1990 builder.push_back(tag);
1991 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1992 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1993 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1994 continue;
1995 }
Seth Mooreb393b082021-07-12 14:18:28 -07001996 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1997 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001998 continue;
1999 }
subrahmanyaman05642492022-02-05 07:10:56 +00002000 // Strongbox may not support factory provisioned attestation key.
2001 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002002 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2003 result = GenerateKeyWithSelfSignedAttestKey(
2004 AuthorizationSetBuilder()
2005 .EcdsaKey(EcCurve::P_256)
2006 .AttestKey()
2007 .SetDefaultValidity(), /* attest key params */
2008 builder, &key_blob, &key_characteristics);
2009 }
subrahmanyaman05642492022-02-05 07:10:56 +00002010 }
David Drysdale37af4b32021-05-14 16:46:59 +01002011 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002012 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002013 ASSERT_GT(key_blob.size(), 0U);
2014
2015 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2016 ASSERT_GT(cert_chain_.size(), 0);
2017 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2018
2019 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2020 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07002021 // Some tags are optional, so don't require them to be in the enforcements.
2022 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01002023 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2024 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2025 }
2026
2027 // Verifying the attestation record will check for the specific tag because
2028 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002029 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2030 hw_enforced, SecLevel(),
2031 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002032 }
2033
David Drysdalec53b7d92021-10-11 12:35:58 +01002034 // Collection of invalid attestation ID tags.
2035 auto invalid_tags =
2036 AuthorizationSetBuilder()
2037 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2038 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2039 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2040 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2041 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2042 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2043 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2044 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002045 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002046 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002047 vector<uint8_t> key_blob;
2048 vector<KeyCharacteristics> key_characteristics;
2049 AuthorizationSetBuilder builder =
2050 AuthorizationSetBuilder()
2051 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002052 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002053 .Digest(Digest::NONE)
2054 .AttestationChallenge(challenge)
2055 .AttestationApplicationId(app_id)
2056 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2057 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2058 .SetDefaultValidity();
2059 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002060
2061 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2062 // Strongbox may not support factory provisioned attestation key.
2063 if (SecLevel() == SecurityLevel::STRONGBOX) {
2064 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2065 error = GenerateKeyWithSelfSignedAttestKey(
2066 AuthorizationSetBuilder()
2067 .EcdsaKey(EcCurve::P_256)
2068 .AttestKey()
2069 .SetDefaultValidity(), /* attest key params */
2070 builder, &key_blob, &key_characteristics);
2071 }
2072 }
David Drysdalec68dc932023-07-06 10:05:12 +01002073
2074 device_id_attestation_check_acceptable_error(tag.tag, error);
David Drysdale37af4b32021-05-14 16:46:59 +01002075 }
2076}
2077
2078/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002079 * NewKeyGenerationTest.EcdsaAttestationIdTags
2080 *
2081 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2082 * attestation extension.
2083 */
2084TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002085 if (is_gsi_image()) {
2086 // GSI sets up a standard set of device identifiers that may not match
2087 // the device identifiers held by the device.
2088 GTEST_SKIP() << "Test not applicable under GSI";
2089 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002090 auto challenge = "hello";
2091 auto app_id = "foo";
2092 auto subject = "cert subj 2";
2093 vector<uint8_t> subject_der(make_name_from_str(subject));
2094 uint64_t serial_int = 0x1010;
2095 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2096 const AuthorizationSetBuilder base_builder =
2097 AuthorizationSetBuilder()
2098 .Authorization(TAG_NO_AUTH_REQUIRED)
2099 .EcdsaSigningKey(EcCurve::P_256)
2100 .Digest(Digest::NONE)
2101 .AttestationChallenge(challenge)
2102 .AttestationApplicationId(app_id)
2103 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2104 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2105 .SetDefaultValidity();
2106
2107 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2108 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil8d779bf2022-09-28 16:09:29 +01002109 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2110 // to ro.product.brand
2111 std::string prop_value =
2112 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2113 if (!prop_value.empty()) {
2114 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2115 "ro.product.brand_for_attestation");
2116 } else {
2117 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2118 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002119 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002120 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2121 // to ro.product.name
2122 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2123 if (!prop_value.empty()) {
2124 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2125 "ro.product.name_for_attestation");
2126 } else {
2127 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2128 }
Tri Vo799e4352022-11-07 17:23:50 -08002129 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002130 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002131 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2132 // to ro.product.model
2133 prop_value =
2134 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2135 if (!prop_value.empty()) {
2136 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2137 "ro.product.model_for_attestation");
2138 } else {
2139 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2140 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002141
2142 for (const KeyParameter& tag : extra_tags) {
2143 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2144 vector<uint8_t> key_blob;
2145 vector<KeyCharacteristics> key_characteristics;
2146 AuthorizationSetBuilder builder = base_builder;
2147 builder.push_back(tag);
2148 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002149 // Strongbox may not support factory provisioned attestation key.
2150 if (SecLevel() == SecurityLevel::STRONGBOX) {
2151 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2152 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002153 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2154 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002155 continue;
2156 }
2157 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002158 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002159 ASSERT_GT(key_blob.size(), 0U);
2160
2161 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2162 ASSERT_GT(cert_chain_.size(), 0);
2163 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2164
2165 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2166 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2167
2168 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2169 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2170 // attestation extension should contain them, so make sure the extra tag is added.
2171 hw_enforced.push_back(tag);
2172
2173 // Verifying the attestation record will check for the specific tag because
2174 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002175 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2176 hw_enforced, SecLevel(),
2177 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002178 }
2179}
2180
2181/*
David Drysdale565ccc72021-10-11 12:49:50 +01002182 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2183 *
2184 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2185 */
2186TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2187 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002188 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002189 auto challenge = "hello";
2190 auto subject = "cert subj 2";
2191 vector<uint8_t> subject_der(make_name_from_str(subject));
2192 uint64_t serial_int = 0x1010;
2193 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002194 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002195 AuthorizationSetBuilder()
2196 .Authorization(TAG_NO_AUTH_REQUIRED)
2197 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2198 .EcdsaSigningKey(EcCurve::P_256)
2199 .Digest(Digest::NONE)
2200 .AttestationChallenge(challenge)
2201 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2202 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2203 .AttestationApplicationId(app_id)
2204 .Authorization(TAG_CREATION_DATETIME, datetime)
2205 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002206 if (reset) {
2207 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2208 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002209 auto result = GenerateKey(builder);
2210 if (SecLevel() == SecurityLevel::STRONGBOX) {
2211 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2212 result = GenerateKeyWithSelfSignedAttestKey(
2213 AuthorizationSetBuilder()
2214 .EcdsaKey(EcCurve::P_256)
2215 .AttestKey()
2216 .SetDefaultValidity(), /* attest key params */
2217 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2218 }
2219 }
2220 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002221 ASSERT_GT(key_blob_.size(), 0U);
2222
2223 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2224 ASSERT_GT(cert_chain_.size(), 0);
2225 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2226
2227 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2228 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2229
2230 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002231 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2232 hw_enforced, SecLevel(),
2233 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002234 EXPECT_GT(unique_id->size(), 0);
2235 CheckedDeleteKey();
2236 };
2237
2238 // Generate unique ID
2239 auto app_id = "foo";
2240 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2241 vector<uint8_t> unique_id;
2242 get_unique_id(app_id, cert_date, &unique_id);
2243
2244 // Generating a new key with the same parameters should give the same unique ID.
2245 vector<uint8_t> unique_id2;
2246 get_unique_id(app_id, cert_date, &unique_id2);
2247 EXPECT_EQ(unique_id, unique_id2);
2248
2249 // Generating a new key with a slightly different date should give the same unique ID.
2250 uint64_t rounded_date = cert_date / 2592000000LLU;
2251 uint64_t min_date = rounded_date * 2592000000LLU;
2252 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2253
2254 vector<uint8_t> unique_id3;
2255 get_unique_id(app_id, min_date, &unique_id3);
2256 EXPECT_EQ(unique_id, unique_id3);
2257
2258 vector<uint8_t> unique_id4;
2259 get_unique_id(app_id, max_date, &unique_id4);
2260 EXPECT_EQ(unique_id, unique_id4);
2261
2262 // A different attestation application ID should yield a different unique ID.
2263 auto app_id2 = "different_foo";
2264 vector<uint8_t> unique_id5;
2265 get_unique_id(app_id2, cert_date, &unique_id5);
2266 EXPECT_NE(unique_id, unique_id5);
2267
2268 // A radically different date should yield a different unique ID.
2269 vector<uint8_t> unique_id6;
2270 get_unique_id(app_id, 1611621648000, &unique_id6);
2271 EXPECT_NE(unique_id, unique_id6);
2272
2273 vector<uint8_t> unique_id7;
2274 get_unique_id(app_id, max_date + 1, &unique_id7);
2275 EXPECT_NE(unique_id, unique_id7);
2276
2277 vector<uint8_t> unique_id8;
2278 get_unique_id(app_id, min_date - 1, &unique_id8);
2279 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002280
2281 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2282 vector<uint8_t> unique_id9;
2283 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2284 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002285}
2286
2287/*
David Drysdale37af4b32021-05-14 16:46:59 +01002288 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2289 *
2290 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2291 */
2292TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2293 auto challenge = "hello";
2294 auto attest_app_id = "foo";
2295 auto subject = "cert subj 2";
2296 vector<uint8_t> subject_der(make_name_from_str(subject));
2297 uint64_t serial_int = 0x1010;
2298 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2299
2300 // Earlier versions of the attestation extension schema included a slot:
2301 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2302 // This should never have been included, and should never be filled in.
2303 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2304 // to confirm that this field never makes it into the attestation extension.
2305 vector<uint8_t> key_blob;
2306 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002307 auto builder = AuthorizationSetBuilder()
2308 .Authorization(TAG_NO_AUTH_REQUIRED)
2309 .EcdsaSigningKey(EcCurve::P_256)
2310 .Digest(Digest::NONE)
2311 .AttestationChallenge(challenge)
2312 .AttestationApplicationId(attest_app_id)
2313 .Authorization(TAG_APPLICATION_ID, "client_id")
2314 .Authorization(TAG_APPLICATION_DATA, "appdata")
2315 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2316 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2317 .SetDefaultValidity();
2318
2319 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002320 // Strongbox may not support factory provisioned attestation key.
2321 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002322 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2323 result = GenerateKeyWithSelfSignedAttestKey(
2324 AuthorizationSetBuilder()
2325 .EcdsaKey(EcCurve::P_256)
2326 .AttestKey()
2327 .SetDefaultValidity(), /* attest key params */
2328 builder, &key_blob, &key_characteristics);
2329 }
subrahmanyaman05642492022-02-05 07:10:56 +00002330 }
David Drysdale37af4b32021-05-14 16:46:59 +01002331 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002332 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002333 ASSERT_GT(key_blob.size(), 0U);
2334
2335 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2336 ASSERT_GT(cert_chain_.size(), 0);
2337 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2338
2339 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2340 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002341 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2342 hw_enforced, SecLevel(),
2343 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002344
2345 // Check that the app id is not in the cert.
2346 string app_id = "clientid";
2347 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2348 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2349 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2350 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2351 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002352}
2353
2354/*
Selene Huang4f64c222021-04-13 19:54:36 -07002355 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2356 *
2357 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2358 * the key will generate a self signed attestation.
2359 */
2360TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002361 auto subject = "cert subj 2";
2362 vector<uint8_t> subject_der(make_name_from_str(subject));
2363
2364 uint64_t serial_int = 0x123456FFF1234;
2365 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2366
David Drysdaledf09e542021-06-08 15:46:11 +01002367 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002368 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002369 vector<uint8_t> key_blob;
2370 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002371 ASSERT_EQ(ErrorCode::OK,
2372 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002373 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002374 .Digest(Digest::NONE)
2375 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2376 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2377 .SetDefaultValidity(),
2378 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002379 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002380 ASSERT_GT(key_blob.size(), 0U);
2381 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002382 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002383
2384 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2385
2386 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002387 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002388
2389 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2390 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002391 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002392
2393 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2394 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002395 }
2396}
2397
2398/*
2399 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2400 *
2401 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2402 * app id must also be provided or else it will fail.
2403 */
2404TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2405 auto challenge = "hello";
2406 vector<uint8_t> key_blob;
2407 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002408 auto builder = AuthorizationSetBuilder()
2409 .EcdsaSigningKey(EcCurve::P_256)
2410 .Digest(Digest::NONE)
2411 .AttestationChallenge(challenge)
2412 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002413
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002414 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002415 // Strongbox may not support factory provisioned attestation key.
2416 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002417 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2418 result = GenerateKeyWithSelfSignedAttestKey(
2419 AuthorizationSetBuilder()
2420 .EcdsaKey(EcCurve::P_256)
2421 .AttestKey()
2422 .SetDefaultValidity(), /* attest key params */
2423 builder, &key_blob, &key_characteristics);
2424 }
subrahmanyaman05642492022-02-05 07:10:56 +00002425 }
2426 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002427}
2428
2429/*
2430 * NewKeyGenerationTest.EcdsaIgnoreAppId
2431 *
2432 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2433 * any appid will be ignored, and keymint will generate a self sign certificate.
2434 */
2435TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2436 auto app_id = "foo";
2437
David Drysdaledf09e542021-06-08 15:46:11 +01002438 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002439 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002440 vector<uint8_t> key_blob;
2441 vector<KeyCharacteristics> key_characteristics;
2442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002443 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002444 .Digest(Digest::NONE)
2445 .AttestationApplicationId(app_id)
2446 .SetDefaultValidity(),
2447 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002448 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002449
2450 ASSERT_GT(key_blob.size(), 0U);
2451 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002452 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002453
2454 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2455
2456 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002457 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002458
2459 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2460 ASSERT_EQ(cert_chain_.size(), 1);
2461
2462 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2463 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002464 }
2465}
2466
2467/*
2468 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2469 *
2470 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2471 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2472 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2473 * to specify how many following bytes will be used to encode the length.
2474 */
2475TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2476 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002477 std::vector<uint32_t> app_id_lengths{143, 258};
2478
2479 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002480 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002481 const string app_id(length, 'a');
2482 vector<uint8_t> key_blob;
2483 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002484 auto builder = AuthorizationSetBuilder()
2485 .Authorization(TAG_NO_AUTH_REQUIRED)
2486 .EcdsaSigningKey(EcCurve::P_256)
2487 .Digest(Digest::NONE)
2488 .AttestationChallenge(challenge)
2489 .AttestationApplicationId(app_id)
2490 .SetDefaultValidity();
2491
2492 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002493 // Strongbox may not support factory provisioned attestation key.
2494 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002495 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2496 result = GenerateKeyWithSelfSignedAttestKey(
2497 AuthorizationSetBuilder()
2498 .EcdsaKey(EcCurve::P_256)
2499 .AttestKey()
2500 .SetDefaultValidity(), /* attest key params */
2501 builder, &key_blob, &key_characteristics);
2502 }
subrahmanyaman05642492022-02-05 07:10:56 +00002503 }
2504 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002505 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002506 ASSERT_GT(key_blob.size(), 0U);
2507 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002508 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002509
2510 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2511
2512 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002513 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002514
2515 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2516 ASSERT_GT(cert_chain_.size(), 0);
2517
2518 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2519 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002520 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002521 sw_enforced, hw_enforced, SecLevel(),
2522 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002523 }
2524}
2525
2526/*
Qi Wud22ec842020-11-26 13:27:53 +08002527 * NewKeyGenerationTest.LimitedUsageEcdsa
2528 *
2529 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2530 * resulting keys have correct characteristics.
2531 */
2532TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002533 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002534 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002535 vector<uint8_t> key_blob;
2536 vector<KeyCharacteristics> key_characteristics;
2537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002538 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002539 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002540 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2541 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002542 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002543 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002544
2545 ASSERT_GT(key_blob.size(), 0U);
2546 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002547 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002548
2549 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2550
2551 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002552 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002553
2554 // Check the usage count limit tag appears in the authorizations.
2555 AuthorizationSet auths;
2556 for (auto& entry : key_characteristics) {
2557 auths.push_back(AuthorizationSet(entry.authorizations));
2558 }
2559 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2560 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002561 }
2562}
2563
2564/*
Selene Huang31ab4042020-04-29 04:22:39 -07002565 * NewKeyGenerationTest.EcdsaDefaultSize
2566 *
David Drysdaledf09e542021-06-08 15:46:11 +01002567 * Verifies that failing to specify a curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002568 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002569 */
2570TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
David Drysdale84b685a2023-08-09 07:00:34 +01002571 auto result = GenerateKey(AuthorizationSetBuilder()
2572 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2573 .SigningKey()
2574 .Digest(Digest::NONE)
2575 .SetDefaultValidity());
2576 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2577 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2578 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002579}
2580
2581/*
David Drysdale42fe1892021-10-14 14:43:46 +01002582 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002583 *
David Drysdale42fe1892021-10-14 14:43:46 +01002584 * Verifies that specifying an invalid curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002585 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002586 */
David Drysdale42fe1892021-10-14 14:43:46 +01002587TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002588 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002589 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002590 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002591 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002592 auto result = GenerateKey(AuthorizationSetBuilder()
2593 .EcdsaSigningKey(curve)
2594 .Digest(Digest::NONE)
2595 .SetDefaultValidity(),
2596 &key_blob, &key_characteristics);
2597 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale84b685a2023-08-09 07:00:34 +01002598 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2599 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002600 }
2601
David Drysdaledf09e542021-06-08 15:46:11 +01002602 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2603 GenerateKey(AuthorizationSetBuilder()
2604 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2605 .Authorization(TAG_KEY_SIZE, 190)
2606 .SigningKey()
2607 .Digest(Digest::NONE)
2608 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002609}
2610
2611/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002612 * NewKeyGenerationTest.EcdsaMissingCurve
2613 *
2614 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2615 */
2616TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2617 if (AidlVersion() < 2) {
2618 /*
2619 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2620 * However, this was not checked at the time so we can only be strict about checking this
2621 * for implementations of KeyMint version 2 and above.
2622 */
2623 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2624 }
2625 /* If EC_CURVE not provided, generateKey
2626 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2627 */
2628 auto result = GenerateKey(
2629 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2630 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2631 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2632}
2633
2634/*
Selene Huang31ab4042020-04-29 04:22:39 -07002635 * NewKeyGenerationTest.EcdsaMismatchKeySize
2636 *
2637 * Verifies that specifying mismatched key size and curve for EC key generation returns
2638 * INVALID_ARGUMENT.
2639 */
2640TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002641 if (SecLevel() == SecurityLevel::STRONGBOX) {
2642 GTEST_SKIP() << "Test not applicable to StrongBox device";
2643 }
Selene Huang31ab4042020-04-29 04:22:39 -07002644
David Drysdaledf09e542021-06-08 15:46:11 +01002645 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002646 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002647 .Authorization(TAG_KEY_SIZE, 224)
2648 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002649 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002650 .Digest(Digest::NONE)
2651 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002652 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002653}
2654
2655/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002656 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002657 *
2658 * Verifies that keymint does not support any curve designated as unsupported.
2659 */
2660TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2661 Digest digest;
2662 if (SecLevel() == SecurityLevel::STRONGBOX) {
2663 digest = Digest::SHA_2_256;
2664 } else {
2665 digest = Digest::SHA_2_512;
2666 }
2667 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002668 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002669 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2670 .EcdsaSigningKey(curve)
2671 .Digest(digest)
2672 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002673 << "Failed to generate key on curve: " << curve;
2674 CheckedDeleteKey();
2675 }
2676}
2677
2678/*
2679 * NewKeyGenerationTest.Hmac
2680 *
2681 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2682 * characteristics.
2683 */
2684TEST_P(NewKeyGenerationTest, Hmac) {
2685 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002686 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002687 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002688 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002689 constexpr size_t key_size = 128;
2690 ASSERT_EQ(ErrorCode::OK,
2691 GenerateKey(
2692 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2693 TAG_MIN_MAC_LENGTH, 128),
2694 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002695 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002696
2697 ASSERT_GT(key_blob.size(), 0U);
2698 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002699 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002700
Shawn Willden7f424372021-01-10 18:06:50 -07002701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2702 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2703 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2704 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002705 }
2706}
2707
2708/*
Selene Huang4f64c222021-04-13 19:54:36 -07002709 * NewKeyGenerationTest.HmacNoAttestation
2710 *
2711 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2712 * and app id are provided.
2713 */
2714TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2715 auto challenge = "hello";
2716 auto app_id = "foo";
2717
2718 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002719 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002720 vector<uint8_t> key_blob;
2721 vector<KeyCharacteristics> key_characteristics;
2722 constexpr size_t key_size = 128;
2723 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2724 .HmacKey(key_size)
2725 .Digest(digest)
2726 .AttestationChallenge(challenge)
2727 .AttestationApplicationId(app_id)
2728 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2729 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002730 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002731
2732 ASSERT_GT(key_blob.size(), 0U);
2733 ASSERT_EQ(cert_chain_.size(), 0);
2734 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002735 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002736
2737 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2738 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2739 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2740 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002741 }
2742}
2743
2744/*
Qi Wud22ec842020-11-26 13:27:53 +08002745 * NewKeyGenerationTest.LimitedUsageHmac
2746 *
2747 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2748 * resulting keys have correct characteristics.
2749 */
2750TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2751 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002752 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002753 vector<uint8_t> key_blob;
2754 vector<KeyCharacteristics> key_characteristics;
2755 constexpr size_t key_size = 128;
2756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2757 .HmacKey(key_size)
2758 .Digest(digest)
2759 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2760 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2761 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002762 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002763
2764 ASSERT_GT(key_blob.size(), 0U);
2765 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002766 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002767
2768 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2769 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2770 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2771 << "Key size " << key_size << "missing";
2772
2773 // Check the usage count limit tag appears in the authorizations.
2774 AuthorizationSet auths;
2775 for (auto& entry : key_characteristics) {
2776 auths.push_back(AuthorizationSet(entry.authorizations));
2777 }
2778 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2779 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002780 }
2781}
2782
2783/*
Selene Huang31ab4042020-04-29 04:22:39 -07002784 * NewKeyGenerationTest.HmacCheckKeySizes
2785 *
2786 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2787 */
2788TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2789 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002790 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002791 if (key_size < 64 || key_size % 8 != 0) {
2792 // To keep this test from being very slow, we only test a random fraction of
2793 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2794 // them, we expect to run ~40 of them in each run.
2795 if (key_size % 8 == 0 || random() % 10 == 0) {
2796 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2797 GenerateKey(AuthorizationSetBuilder()
2798 .HmacKey(key_size)
2799 .Digest(Digest::SHA_2_256)
2800 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2801 << "HMAC key size " << key_size << " invalid";
2802 }
2803 } else {
2804 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2805 .HmacKey(key_size)
2806 .Digest(Digest::SHA_2_256)
2807 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2808 << "Failed to generate HMAC key of size " << key_size;
2809 CheckedDeleteKey();
2810 }
2811 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002812 if (SecLevel() == SecurityLevel::STRONGBOX) {
2813 // STRONGBOX devices must not support keys larger than 512 bits.
2814 size_t key_size = 520;
2815 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2816 GenerateKey(AuthorizationSetBuilder()
2817 .HmacKey(key_size)
2818 .Digest(Digest::SHA_2_256)
2819 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2820 << "HMAC key size " << key_size << " unexpectedly valid";
2821 }
Selene Huang31ab4042020-04-29 04:22:39 -07002822}
2823
2824/*
2825 * NewKeyGenerationTest.HmacCheckMinMacLengths
2826 *
2827 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2828 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2829 * specific MAC length that failed, so reproducing a failed run will be easy.
2830 */
2831TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2832 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002833 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002834 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2835 // To keep this test from being very long, we only test a random fraction of
2836 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2837 // we expect to run ~17 of them in each run.
2838 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2839 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2840 GenerateKey(AuthorizationSetBuilder()
2841 .HmacKey(128)
2842 .Digest(Digest::SHA_2_256)
2843 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2844 << "HMAC min mac length " << min_mac_length << " invalid.";
2845 }
2846 } else {
2847 EXPECT_EQ(ErrorCode::OK,
2848 GenerateKey(AuthorizationSetBuilder()
2849 .HmacKey(128)
2850 .Digest(Digest::SHA_2_256)
2851 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2852 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2853 CheckedDeleteKey();
2854 }
2855 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002856
2857 // Minimum MAC length must be no more than 512 bits.
2858 size_t min_mac_length = 520;
2859 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2860 GenerateKey(AuthorizationSetBuilder()
2861 .HmacKey(128)
2862 .Digest(Digest::SHA_2_256)
2863 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2864 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002865}
2866
2867/*
2868 * NewKeyGenerationTest.HmacMultipleDigests
2869 *
2870 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2871 */
2872TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002873 if (SecLevel() == SecurityLevel::STRONGBOX) {
2874 GTEST_SKIP() << "Test not applicable to StrongBox device";
2875 }
Selene Huang31ab4042020-04-29 04:22:39 -07002876
2877 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2878 GenerateKey(AuthorizationSetBuilder()
2879 .HmacKey(128)
2880 .Digest(Digest::SHA1)
2881 .Digest(Digest::SHA_2_256)
2882 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2883}
2884
2885/*
2886 * NewKeyGenerationTest.HmacDigestNone
2887 *
2888 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2889 */
2890TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2891 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2892 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2893 128)));
2894
2895 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2896 GenerateKey(AuthorizationSetBuilder()
2897 .HmacKey(128)
2898 .Digest(Digest::NONE)
2899 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2900}
2901
Selene Huang4f64c222021-04-13 19:54:36 -07002902/*
2903 * NewKeyGenerationTest.AesNoAttestation
2904 *
2905 * Verifies that attestation parameters to AES keys are ignored and generateKey
2906 * will succeed.
2907 */
2908TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2909 auto challenge = "hello";
2910 auto app_id = "foo";
2911
2912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2913 .Authorization(TAG_NO_AUTH_REQUIRED)
2914 .AesEncryptionKey(128)
2915 .EcbMode()
2916 .Padding(PaddingMode::PKCS7)
2917 .AttestationChallenge(challenge)
2918 .AttestationApplicationId(app_id)));
2919
2920 ASSERT_EQ(cert_chain_.size(), 0);
2921}
2922
2923/*
2924 * NewKeyGenerationTest.TripleDesNoAttestation
2925 *
2926 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2927 * will be successful. No attestation should be generated.
2928 */
2929TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2930 auto challenge = "hello";
2931 auto app_id = "foo";
2932
2933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2934 .TripleDesEncryptionKey(168)
2935 .BlockMode(BlockMode::ECB)
2936 .Authorization(TAG_NO_AUTH_REQUIRED)
2937 .Padding(PaddingMode::NONE)
2938 .AttestationChallenge(challenge)
2939 .AttestationApplicationId(app_id)));
2940 ASSERT_EQ(cert_chain_.size(), 0);
2941}
2942
Selene Huang31ab4042020-04-29 04:22:39 -07002943INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2944
2945typedef KeyMintAidlTestBase SigningOperationsTest;
2946
2947/*
2948 * SigningOperationsTest.RsaSuccess
2949 *
2950 * Verifies that raw RSA signature operations succeed.
2951 */
2952TEST_P(SigningOperationsTest, RsaSuccess) {
2953 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2954 .RsaSigningKey(2048, 65537)
2955 .Digest(Digest::NONE)
2956 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002957 .Authorization(TAG_NO_AUTH_REQUIRED)
2958 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002959 string message = "12345678901234567890123456789012";
2960 string signature = SignMessage(
2961 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002962 LocalVerifyMessage(message, signature,
2963 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2964}
2965
2966/*
2967 * SigningOperationsTest.RsaAllPaddingsAndDigests
2968 *
2969 * Verifies RSA signature/verification for all padding modes and digests.
2970 */
2971TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2972 auto authorizations = AuthorizationSetBuilder()
2973 .Authorization(TAG_NO_AUTH_REQUIRED)
2974 .RsaSigningKey(2048, 65537)
2975 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2976 .Padding(PaddingMode::NONE)
2977 .Padding(PaddingMode::RSA_PSS)
2978 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2979 .SetDefaultValidity();
2980
2981 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2982
2983 string message(128, 'a');
2984 string corrupt_message(message);
2985 ++corrupt_message[corrupt_message.size() / 2];
2986
2987 for (auto padding :
2988 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2989 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002990 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002991 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2992 // Digesting only makes sense with padding.
2993 continue;
2994 }
2995
2996 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2997 // PSS requires digesting.
2998 continue;
2999 }
3000
3001 string signature =
3002 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
3003 LocalVerifyMessage(message, signature,
3004 AuthorizationSetBuilder().Digest(digest).Padding(padding));
3005 }
3006 }
Selene Huang31ab4042020-04-29 04:22:39 -07003007}
3008
3009/*
3010 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3011 *
Shawn Willden7f424372021-01-10 18:06:50 -07003012 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003013 */
3014TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3015 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3016 .Authorization(TAG_NO_AUTH_REQUIRED)
3017 .RsaSigningKey(2048, 65537)
3018 .Digest(Digest::NONE)
3019 .Padding(PaddingMode::NONE)
3020 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003021 .Authorization(TAG_APPLICATION_DATA, "appdata")
3022 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003023
3024 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3025
Selene Huang31ab4042020-04-29 04:22:39 -07003026 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3027 Begin(KeyPurpose::SIGN,
3028 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3029 AbortIfNeeded();
3030 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3031 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3032 .Digest(Digest::NONE)
3033 .Padding(PaddingMode::NONE)
3034 .Authorization(TAG_APPLICATION_ID, "clientid")));
3035 AbortIfNeeded();
3036 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3037 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3038 .Digest(Digest::NONE)
3039 .Padding(PaddingMode::NONE)
3040 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3041 AbortIfNeeded();
3042 EXPECT_EQ(ErrorCode::OK,
3043 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3044 .Digest(Digest::NONE)
3045 .Padding(PaddingMode::NONE)
3046 .Authorization(TAG_APPLICATION_DATA, "appdata")
3047 .Authorization(TAG_APPLICATION_ID, "clientid")));
3048 AbortIfNeeded();
3049}
3050
3051/*
3052 * SigningOperationsTest.RsaPssSha256Success
3053 *
3054 * Verifies that RSA-PSS signature operations succeed.
3055 */
3056TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3058 .RsaSigningKey(2048, 65537)
3059 .Digest(Digest::SHA_2_256)
3060 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003061 .Authorization(TAG_NO_AUTH_REQUIRED)
3062 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003063 // Use large message, which won't work without digesting.
3064 string message(1024, 'a');
3065 string signature = SignMessage(
3066 message,
3067 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3068}
3069
3070/*
3071 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3072 *
3073 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3074 * supports only unpadded operations.
3075 */
3076TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3078 .RsaSigningKey(2048, 65537)
3079 .Digest(Digest::NONE)
3080 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003081 .Padding(PaddingMode::NONE)
3082 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003083 string message = "12345678901234567890123456789012";
3084 string signature;
3085
3086 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3087 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3088 .Digest(Digest::NONE)
3089 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3090}
3091
3092/*
3093 * SigningOperationsTest.NoUserConfirmation
3094 *
3095 * Verifies that keymint rejects signing operations for keys with
3096 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3097 * presented.
3098 */
3099TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003101 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003102 .Digest(Digest::NONE)
3103 .Padding(PaddingMode::NONE)
3104 .Authorization(TAG_NO_AUTH_REQUIRED)
3105 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3106 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003107
3108 const string message = "12345678901234567890123456789012";
3109 EXPECT_EQ(ErrorCode::OK,
3110 Begin(KeyPurpose::SIGN,
3111 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3112 string signature;
3113 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3114}
3115
3116/*
3117 * SigningOperationsTest.RsaPkcs1Sha256Success
3118 *
3119 * Verifies that digested RSA-PKCS1 signature operations succeed.
3120 */
3121TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3122 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3123 .RsaSigningKey(2048, 65537)
3124 .Digest(Digest::SHA_2_256)
3125 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003126 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3127 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003128 string message(1024, 'a');
3129 string signature = SignMessage(message, AuthorizationSetBuilder()
3130 .Digest(Digest::SHA_2_256)
3131 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3132}
3133
3134/*
3135 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3136 *
3137 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3138 */
3139TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3141 .RsaSigningKey(2048, 65537)
3142 .Digest(Digest::NONE)
3143 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003144 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3145 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003146 string message(53, 'a');
3147 string signature = SignMessage(message, AuthorizationSetBuilder()
3148 .Digest(Digest::NONE)
3149 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3150}
3151
3152/*
3153 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3154 *
3155 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3156 * given a too-long message.
3157 */
3158TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3159 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3160 .RsaSigningKey(2048, 65537)
3161 .Digest(Digest::NONE)
3162 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003163 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3164 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003165 string message(257, 'a');
3166
3167 EXPECT_EQ(ErrorCode::OK,
3168 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3169 .Digest(Digest::NONE)
3170 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3171 string signature;
3172 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3173}
3174
3175/*
3176 * SigningOperationsTest.RsaPssSha512TooSmallKey
3177 *
3178 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3179 * used with a key that is too small for the message.
3180 *
3181 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3182 * keymint specification requires that salt_size == digest_size, so the message will be
3183 * digest_size * 2 +
3184 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3185 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3186 * for a 1024-bit key.
3187 */
3188TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003189 if (SecLevel() == SecurityLevel::STRONGBOX) {
3190 GTEST_SKIP() << "Test not applicable to StrongBox device";
3191 }
Selene Huang31ab4042020-04-29 04:22:39 -07003192 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3193 .RsaSigningKey(1024, 65537)
3194 .Digest(Digest::SHA_2_512)
3195 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003196 .Padding(PaddingMode::RSA_PSS)
3197 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003198 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3199 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3200 .Digest(Digest::SHA_2_512)
3201 .Padding(PaddingMode::RSA_PSS)));
3202}
3203
3204/*
3205 * SigningOperationsTest.RsaNoPaddingTooLong
3206 *
3207 * Verifies that raw RSA signature operations fail with the correct error code when
3208 * given a too-long message.
3209 */
3210TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3211 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3212 .RsaSigningKey(2048, 65537)
3213 .Digest(Digest::NONE)
3214 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003215 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3216 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003217 // One byte too long
3218 string message(2048 / 8 + 1, 'a');
3219 ASSERT_EQ(ErrorCode::OK,
3220 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3221 .Digest(Digest::NONE)
3222 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3223 string result;
3224 ErrorCode finish_error_code = Finish(message, &result);
3225 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3226 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3227
3228 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3229 message = string(128 * 1024, 'a');
3230 ASSERT_EQ(ErrorCode::OK,
3231 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3232 .Digest(Digest::NONE)
3233 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3234 finish_error_code = Finish(message, &result);
3235 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3236 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3237}
3238
3239/*
3240 * SigningOperationsTest.RsaAbort
3241 *
3242 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3243 * test, but the behavior should be algorithm and purpose-independent.
3244 */
3245TEST_P(SigningOperationsTest, RsaAbort) {
3246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3247 .RsaSigningKey(2048, 65537)
3248 .Digest(Digest::NONE)
3249 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003250 .Padding(PaddingMode::NONE)
3251 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003252
3253 ASSERT_EQ(ErrorCode::OK,
3254 Begin(KeyPurpose::SIGN,
3255 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3256 EXPECT_EQ(ErrorCode::OK, Abort());
3257
3258 // Another abort should fail
3259 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3260
3261 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003262 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003263}
3264
3265/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003266 * SigningOperationsTest.RsaNonUniqueParams
3267 *
3268 * Verifies that an operation with multiple padding modes is rejected.
3269 */
3270TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3271 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3272 .RsaSigningKey(2048, 65537)
3273 .Digest(Digest::NONE)
3274 .Digest(Digest::SHA1)
3275 .Authorization(TAG_NO_AUTH_REQUIRED)
3276 .Padding(PaddingMode::NONE)
3277 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3278 .SetDefaultValidity()));
3279
3280 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3281 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3282 .Digest(Digest::NONE)
3283 .Padding(PaddingMode::NONE)
3284 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3285
Tommy Chiuc93c4392021-05-11 18:36:50 +08003286 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3287 .Digest(Digest::NONE)
3288 .Digest(Digest::SHA1)
3289 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3290 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003291
3292 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3293 Begin(KeyPurpose::SIGN,
3294 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3295}
3296
3297/*
Selene Huang31ab4042020-04-29 04:22:39 -07003298 * SigningOperationsTest.RsaUnsupportedPadding
3299 *
3300 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3301 * with a padding mode inappropriate for RSA.
3302 */
3303TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3304 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3305 .RsaSigningKey(2048, 65537)
3306 .Authorization(TAG_NO_AUTH_REQUIRED)
3307 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003308 .Padding(PaddingMode::PKCS7)
3309 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003310 ASSERT_EQ(
3311 ErrorCode::UNSUPPORTED_PADDING_MODE,
3312 Begin(KeyPurpose::SIGN,
3313 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003314 CheckedDeleteKey();
3315
3316 ASSERT_EQ(ErrorCode::OK,
3317 GenerateKey(
3318 AuthorizationSetBuilder()
3319 .RsaSigningKey(2048, 65537)
3320 .Authorization(TAG_NO_AUTH_REQUIRED)
3321 .Digest(Digest::SHA_2_256 /* supported digest */)
3322 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3323 .SetDefaultValidity()));
3324 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3325 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3326 .Digest(Digest::SHA_2_256)
3327 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003328}
3329
3330/*
3331 * SigningOperationsTest.RsaPssNoDigest
3332 *
3333 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3334 */
3335TEST_P(SigningOperationsTest, RsaNoDigest) {
3336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3337 .RsaSigningKey(2048, 65537)
3338 .Authorization(TAG_NO_AUTH_REQUIRED)
3339 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003340 .Padding(PaddingMode::RSA_PSS)
3341 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003342 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3343 Begin(KeyPurpose::SIGN,
3344 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3345
3346 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3347 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3348}
3349
3350/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003351 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003352 *
3353 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3354 * supported in some cases (as validated in other tests), but a mode must be specified.
3355 */
3356TEST_P(SigningOperationsTest, RsaNoPadding) {
3357 // Padding must be specified
3358 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3359 .RsaKey(2048, 65537)
3360 .Authorization(TAG_NO_AUTH_REQUIRED)
3361 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003362 .Digest(Digest::NONE)
3363 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003364 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3365 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3366}
3367
3368/*
3369 * SigningOperationsTest.RsaShortMessage
3370 *
3371 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3372 */
3373TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3375 .Authorization(TAG_NO_AUTH_REQUIRED)
3376 .RsaSigningKey(2048, 65537)
3377 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003378 .Padding(PaddingMode::NONE)
3379 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003380
3381 // Barely shorter
3382 string message(2048 / 8 - 1, 'a');
3383 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3384
3385 // Much shorter
3386 message = "a";
3387 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3388}
3389
3390/*
3391 * SigningOperationsTest.RsaSignWithEncryptionKey
3392 *
3393 * Verifies that RSA encryption keys cannot be used to sign.
3394 */
3395TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3397 .Authorization(TAG_NO_AUTH_REQUIRED)
3398 .RsaEncryptionKey(2048, 65537)
3399 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003400 .Padding(PaddingMode::NONE)
3401 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003402 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3403 Begin(KeyPurpose::SIGN,
3404 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3405}
3406
3407/*
3408 * SigningOperationsTest.RsaSignTooLargeMessage
3409 *
3410 * Verifies that attempting a raw signature of a message which is the same length as the key,
3411 * but numerically larger than the public modulus, fails with the correct error.
3412 */
3413TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3415 .Authorization(TAG_NO_AUTH_REQUIRED)
3416 .RsaSigningKey(2048, 65537)
3417 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003418 .Padding(PaddingMode::NONE)
3419 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003420
3421 // Largest possible message will always be larger than the public modulus.
3422 string message(2048 / 8, static_cast<char>(0xff));
3423 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3424 .Authorization(TAG_NO_AUTH_REQUIRED)
3425 .Digest(Digest::NONE)
3426 .Padding(PaddingMode::NONE)));
3427 string signature;
3428 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3429}
3430
3431/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003432 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3433 *
David Drysdale42fe1892021-10-14 14:43:46 +01003434 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003435 */
3436TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003437 string message = "1234567890";
3438 string corrupt_message = "2234567890";
3439 for (auto curve : ValidCurves()) {
3440 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003441 // Ed25519 only allows Digest::NONE.
3442 auto digests = (curve == EcCurve::CURVE_25519)
3443 ? std::vector<Digest>(1, Digest::NONE)
3444 : ValidDigests(true /* withNone */, false /* withMD5 */);
3445
David Drysdaledf8f52e2021-05-06 08:10:58 +01003446 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3447 .Authorization(TAG_NO_AUTH_REQUIRED)
3448 .EcdsaSigningKey(curve)
3449 .Digest(digests)
3450 .SetDefaultValidity());
3451 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3452 if (error != ErrorCode::OK) {
3453 continue;
3454 }
3455
3456 for (auto digest : digests) {
3457 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3458 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3459 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3460 }
3461
3462 auto rc = DeleteKey();
3463 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3464 }
3465}
3466
3467/*
Selene Huang31ab4042020-04-29 04:22:39 -07003468 * SigningOperationsTest.EcdsaAllCurves
3469 *
David Drysdale42fe1892021-10-14 14:43:46 +01003470 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003471 */
3472TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3473 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003474 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3475 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003476 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3477 .Authorization(TAG_NO_AUTH_REQUIRED)
3478 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003479 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003480 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003481 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3482 if (error != ErrorCode::OK) continue;
3483
3484 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003485 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003486 CheckedDeleteKey();
3487 }
3488}
3489
3490/*
David Drysdale42fe1892021-10-14 14:43:46 +01003491 * SigningOperationsTest.EcdsaCurve25519
3492 *
3493 * Verifies that ECDSA operations succeed with curve25519.
3494 */
3495TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3496 if (!Curve25519Supported()) {
3497 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3498 }
3499
3500 EcCurve curve = EcCurve::CURVE_25519;
3501 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3502 .Authorization(TAG_NO_AUTH_REQUIRED)
3503 .EcdsaSigningKey(curve)
3504 .Digest(Digest::NONE)
3505 .SetDefaultValidity());
3506 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3507
3508 string message(1024, 'a');
3509 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3510 CheckedDeleteKey();
3511}
3512
3513/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003514 * SigningOperationsTest.EcdsaCurve25519MaxSize
3515 *
3516 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3517 */
3518TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3519 if (!Curve25519Supported()) {
3520 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3521 }
3522
3523 EcCurve curve = EcCurve::CURVE_25519;
3524 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3525 .Authorization(TAG_NO_AUTH_REQUIRED)
3526 .EcdsaSigningKey(curve)
3527 .Digest(Digest::NONE)
3528 .SetDefaultValidity());
3529 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3530
3531 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3532
3533 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3534 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3535 string message(msg_size, 'a');
3536
3537 // Attempt to sign via Begin+Finish.
3538 AuthorizationSet out_params;
3539 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3540 EXPECT_TRUE(out_params.empty());
3541 string signature;
3542 auto result = Finish(message, &signature);
3543 EXPECT_EQ(result, ErrorCode::OK);
3544 LocalVerifyMessage(message, signature, params);
3545
3546 // Attempt to sign via Begin+Update+Finish
3547 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3548 EXPECT_TRUE(out_params.empty());
3549 string output;
3550 result = Update(message, &output);
3551 EXPECT_EQ(result, ErrorCode::OK);
3552 EXPECT_EQ(output.size(), 0);
3553 string signature2;
3554 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3555 LocalVerifyMessage(message, signature2, params);
3556 }
3557
3558 CheckedDeleteKey();
3559}
3560
3561/*
3562 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3563 *
3564 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3565 */
3566TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3567 if (!Curve25519Supported()) {
3568 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3569 }
3570
3571 EcCurve curve = EcCurve::CURVE_25519;
3572 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3573 .Authorization(TAG_NO_AUTH_REQUIRED)
3574 .EcdsaSigningKey(curve)
3575 .Digest(Digest::NONE)
3576 .SetDefaultValidity());
3577 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3578
3579 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3580
3581 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3582 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3583 string message(msg_size, 'a');
3584
3585 // Attempt to sign via Begin+Finish.
3586 AuthorizationSet out_params;
3587 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3588 EXPECT_TRUE(out_params.empty());
3589 string signature;
3590 auto result = Finish(message, &signature);
3591 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3592
3593 // Attempt to sign via Begin+Update (but never get to Finish)
3594 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3595 EXPECT_TRUE(out_params.empty());
3596 string output;
3597 result = Update(message, &output);
3598 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3599 }
3600
3601 CheckedDeleteKey();
3602}
3603
3604/*
Selene Huang31ab4042020-04-29 04:22:39 -07003605 * SigningOperationsTest.EcdsaNoDigestHugeData
3606 *
3607 * Verifies that ECDSA operations support very large messages, even without digesting. This
3608 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3609 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3610 * the framework.
3611 */
3612TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3613 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3614 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003615 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003616 .Digest(Digest::NONE)
3617 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003618 string message(1 * 1024, 'a');
3619 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3620}
3621
3622/*
3623 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3624 *
3625 * Verifies that using an EC key requires the correct app ID/data.
3626 */
3627TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3629 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003630 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003631 .Digest(Digest::NONE)
3632 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003633 .Authorization(TAG_APPLICATION_DATA, "appdata")
3634 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003635
3636 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3637
Selene Huang31ab4042020-04-29 04:22:39 -07003638 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3639 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3640 AbortIfNeeded();
3641 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3642 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3643 .Digest(Digest::NONE)
3644 .Authorization(TAG_APPLICATION_ID, "clientid")));
3645 AbortIfNeeded();
3646 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3647 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3648 .Digest(Digest::NONE)
3649 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3650 AbortIfNeeded();
3651 EXPECT_EQ(ErrorCode::OK,
3652 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3653 .Digest(Digest::NONE)
3654 .Authorization(TAG_APPLICATION_DATA, "appdata")
3655 .Authorization(TAG_APPLICATION_ID, "clientid")));
3656 AbortIfNeeded();
3657}
3658
3659/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003660 * SigningOperationsTest.EcdsaIncompatibleDigest
3661 *
3662 * Verifies that using an EC key requires compatible digest.
3663 */
3664TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3665 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3666 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003667 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003668 .Digest(Digest::NONE)
3669 .Digest(Digest::SHA1)
3670 .SetDefaultValidity()));
3671 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3672 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3673 AbortIfNeeded();
3674}
3675
3676/*
Selene Huang31ab4042020-04-29 04:22:39 -07003677 * SigningOperationsTest.AesEcbSign
3678 *
3679 * Verifies that attempts to use AES keys to sign fail in the correct way.
3680 */
3681TEST_P(SigningOperationsTest, AesEcbSign) {
3682 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3683 .Authorization(TAG_NO_AUTH_REQUIRED)
3684 .SigningKey()
3685 .AesEncryptionKey(128)
3686 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3687
3688 AuthorizationSet out_params;
3689 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3690 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3691 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3692 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3693}
3694
3695/*
3696 * SigningOperationsTest.HmacAllDigests
3697 *
3698 * Verifies that HMAC works with all digests.
3699 */
3700TEST_P(SigningOperationsTest, HmacAllDigests) {
3701 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003702 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003703 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3704 .Authorization(TAG_NO_AUTH_REQUIRED)
3705 .HmacKey(128)
3706 .Digest(digest)
3707 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3708 << "Failed to create HMAC key with digest " << digest;
3709 string message = "12345678901234567890123456789012";
3710 string signature = MacMessage(message, digest, 160);
3711 EXPECT_EQ(160U / 8U, signature.size())
3712 << "Failed to sign with HMAC key with digest " << digest;
3713 CheckedDeleteKey();
3714 }
3715}
3716
3717/*
3718 * SigningOperationsTest.HmacSha256TooLargeMacLength
3719 *
3720 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3721 * digest size.
3722 */
3723TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3725 .Authorization(TAG_NO_AUTH_REQUIRED)
3726 .HmacKey(128)
3727 .Digest(Digest::SHA_2_256)
3728 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3729 AuthorizationSet output_params;
3730 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3731 AuthorizationSetBuilder()
3732 .Digest(Digest::SHA_2_256)
3733 .Authorization(TAG_MAC_LENGTH, 264),
3734 &output_params));
3735}
3736
3737/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003738 * SigningOperationsTest.HmacSha256InvalidMacLength
3739 *
3740 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3741 * not a multiple of 8.
3742 */
3743TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3745 .Authorization(TAG_NO_AUTH_REQUIRED)
3746 .HmacKey(128)
3747 .Digest(Digest::SHA_2_256)
3748 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3749 AuthorizationSet output_params;
3750 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3751 AuthorizationSetBuilder()
3752 .Digest(Digest::SHA_2_256)
3753 .Authorization(TAG_MAC_LENGTH, 161),
3754 &output_params));
3755}
3756
3757/*
Selene Huang31ab4042020-04-29 04:22:39 -07003758 * SigningOperationsTest.HmacSha256TooSmallMacLength
3759 *
3760 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3761 * specified minimum MAC length.
3762 */
3763TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3764 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3765 .Authorization(TAG_NO_AUTH_REQUIRED)
3766 .HmacKey(128)
3767 .Digest(Digest::SHA_2_256)
3768 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3769 AuthorizationSet output_params;
3770 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3771 AuthorizationSetBuilder()
3772 .Digest(Digest::SHA_2_256)
3773 .Authorization(TAG_MAC_LENGTH, 120),
3774 &output_params));
3775}
3776
3777/*
3778 * SigningOperationsTest.HmacRfc4231TestCase3
3779 *
3780 * Validates against the test vectors from RFC 4231 test case 3.
3781 */
3782TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3783 string key(20, 0xaa);
3784 string message(50, 0xdd);
3785 uint8_t sha_224_expected[] = {
3786 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3787 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3788 };
3789 uint8_t sha_256_expected[] = {
3790 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3791 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3792 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3793 };
3794 uint8_t sha_384_expected[] = {
3795 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3796 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3797 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3798 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3799 };
3800 uint8_t sha_512_expected[] = {
3801 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3802 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3803 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3804 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3805 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3806 };
3807
3808 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3809 if (SecLevel() != SecurityLevel::STRONGBOX) {
3810 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3811 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3812 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3813 }
3814}
3815
3816/*
3817 * SigningOperationsTest.HmacRfc4231TestCase5
3818 *
3819 * Validates against the test vectors from RFC 4231 test case 5.
3820 */
3821TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3822 string key(20, 0x0c);
3823 string message = "Test With Truncation";
3824
3825 uint8_t sha_224_expected[] = {
3826 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3827 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3828 };
3829 uint8_t sha_256_expected[] = {
3830 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3831 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3832 };
3833 uint8_t sha_384_expected[] = {
3834 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3835 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3836 };
3837 uint8_t sha_512_expected[] = {
3838 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3839 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3840 };
3841
3842 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3843 if (SecLevel() != SecurityLevel::STRONGBOX) {
3844 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3845 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3846 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3847 }
3848}
3849
3850INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3851
3852typedef KeyMintAidlTestBase VerificationOperationsTest;
3853
3854/*
Selene Huang31ab4042020-04-29 04:22:39 -07003855 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3856 *
3857 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3858 */
3859TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3860 string key_material = "HelloThisIsAKey";
3861
3862 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003863 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003864 EXPECT_EQ(ErrorCode::OK,
3865 ImportKey(AuthorizationSetBuilder()
3866 .Authorization(TAG_NO_AUTH_REQUIRED)
3867 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3868 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3869 .Digest(Digest::SHA_2_256)
3870 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3871 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003872 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003873 EXPECT_EQ(ErrorCode::OK,
3874 ImportKey(AuthorizationSetBuilder()
3875 .Authorization(TAG_NO_AUTH_REQUIRED)
3876 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3877 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3878 .Digest(Digest::SHA_2_256)
3879 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3880 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003881 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003882
3883 string message = "This is a message.";
3884 string signature = SignMessage(
3885 signing_key, message,
3886 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3887
3888 // Signing key should not work.
3889 AuthorizationSet out_params;
3890 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3891 Begin(KeyPurpose::VERIFY, signing_key,
3892 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3893
3894 // Verification key should work.
3895 VerifyMessage(verification_key, message, signature,
3896 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003897}
3898
Prashant Patildec9fdc2021-12-08 15:25:47 +00003899/*
3900 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3901 *
3902 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3903 */
3904TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3905 string key_material = "HelloThisIsAKey";
3906
3907 vector<uint8_t> signing_key, verification_key;
3908 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3909 EXPECT_EQ(ErrorCode::OK,
3910 ImportKey(AuthorizationSetBuilder()
3911 .Authorization(TAG_NO_AUTH_REQUIRED)
3912 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3913 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3914 .Digest(Digest::SHA_2_256)
3915 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3916 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003917 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003918 EXPECT_EQ(ErrorCode::OK,
3919 ImportKey(AuthorizationSetBuilder()
3920 .Authorization(TAG_NO_AUTH_REQUIRED)
3921 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3922 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3923 .Digest(Digest::SHA_2_256)
3924 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3925 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003926 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003927
3928 string message = "This is a message.";
3929 string signature = SignMessage(
3930 signing_key, message,
3931 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3932
3933 AuthorizationSet begin_out_params;
3934 ASSERT_EQ(ErrorCode::OK,
3935 Begin(KeyPurpose::VERIFY, verification_key,
3936 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3937
3938 string corruptMessage = "This is b message."; // Corrupted message
3939 string output;
3940 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3941
3942 ASSERT_EQ(ErrorCode::OK,
3943 Begin(KeyPurpose::VERIFY, verification_key,
3944 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3945
3946 signature[0] += 1; // Corrupt a signature
3947 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003948}
3949
Selene Huang31ab4042020-04-29 04:22:39 -07003950INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3951
3952typedef KeyMintAidlTestBase ExportKeyTest;
3953
3954/*
3955 * ExportKeyTest.RsaUnsupportedKeyFormat
3956 *
3957 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3958 */
3959// TODO(seleneh) add ExportKey to GenerateKey
3960// check result
3961
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003962class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003963 public:
3964 template <TagType tag_type, Tag tag, typename ValueT>
3965 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3966 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003967 for (auto& entry : key_characteristics_) {
3968 if (entry.securityLevel == SecLevel()) {
3969 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3970 << "Tag " << tag << " with value " << expected
3971 << " not found at security level" << entry.securityLevel;
3972 } else {
3973 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3974 << "Tag " << tag << " found at security level " << entry.securityLevel;
3975 }
Selene Huang31ab4042020-04-29 04:22:39 -07003976 }
3977 }
3978
3979 void CheckOrigin() {
3980 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003981 // Origin isn't a crypto param, but it always lives with them.
3982 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003983 }
3984};
3985
3986/*
3987 * ImportKeyTest.RsaSuccess
3988 *
3989 * Verifies that importing and using an RSA key pair works correctly.
3990 */
3991TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003992 uint32_t key_size;
3993 string key;
3994
3995 if (SecLevel() == SecurityLevel::STRONGBOX) {
3996 key_size = 2048;
3997 key = rsa_2048_key;
3998 } else {
3999 key_size = 1024;
4000 key = rsa_key;
4001 }
4002
Selene Huang31ab4042020-04-29 04:22:39 -07004003 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4004 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004005 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004006 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004007 .Padding(PaddingMode::RSA_PSS)
4008 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004009 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004010
4011 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004012 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004013 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4014 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4015 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4016 CheckOrigin();
4017
4018 string message(1024 / 8, 'a');
4019 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4020 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004021 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004022}
4023
4024/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004025 * ImportKeyTest.RsaSuccessWithoutParams
4026 *
4027 * Verifies that importing and using an RSA key pair without specifying parameters
4028 * works correctly.
4029 */
4030TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4031 uint32_t key_size;
4032 string key;
4033
4034 if (SecLevel() == SecurityLevel::STRONGBOX) {
4035 key_size = 2048;
4036 key = rsa_2048_key;
4037 } else {
4038 key_size = 1024;
4039 key = rsa_key;
4040 }
4041
4042 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4043 .Authorization(TAG_NO_AUTH_REQUIRED)
4044 .SigningKey()
4045 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4046 .Digest(Digest::SHA_2_256)
4047 .Padding(PaddingMode::RSA_PSS)
4048 .SetDefaultValidity(),
4049 KeyFormat::PKCS8, key));
4050
4051 // Key size and public exponent are determined from the imported key material.
4052 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4053 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4054
4055 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4056 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4057 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4058 CheckOrigin();
4059
4060 string message(1024 / 8, 'a');
4061 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4062 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004063 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004064}
4065
4066/*
Selene Huang31ab4042020-04-29 04:22:39 -07004067 * ImportKeyTest.RsaKeySizeMismatch
4068 *
4069 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4070 * correct way.
4071 */
4072TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4073 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4074 ImportKey(AuthorizationSetBuilder()
4075 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4076 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004077 .Padding(PaddingMode::NONE)
4078 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004079 KeyFormat::PKCS8, rsa_key));
4080}
4081
4082/*
4083 * ImportKeyTest.RsaPublicExponentMismatch
4084 *
4085 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4086 * fails in the correct way.
4087 */
4088TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4089 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4090 ImportKey(AuthorizationSetBuilder()
4091 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4092 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004093 .Padding(PaddingMode::NONE)
4094 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004095 KeyFormat::PKCS8, rsa_key));
4096}
4097
4098/*
David Drysdalee60248c2021-10-04 12:54:13 +01004099 * ImportKeyTest.RsaAttestMultiPurposeFail
4100 *
4101 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4102 */
4103TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004104 if (AidlVersion() < 2) {
4105 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4106 // with other key purposes. However, this was not checked at the time
4107 // so we can only be strict about checking this for implementations of KeyMint
4108 // version 2 and above.
4109 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4110 }
David Drysdalee60248c2021-10-04 12:54:13 +01004111 uint32_t key_size = 2048;
4112 string key = rsa_2048_key;
4113
4114 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4115 ImportKey(AuthorizationSetBuilder()
4116 .Authorization(TAG_NO_AUTH_REQUIRED)
4117 .RsaSigningKey(key_size, 65537)
4118 .AttestKey()
4119 .Digest(Digest::SHA_2_256)
4120 .Padding(PaddingMode::RSA_PSS)
4121 .SetDefaultValidity(),
4122 KeyFormat::PKCS8, key));
4123}
4124
4125/*
Selene Huang31ab4042020-04-29 04:22:39 -07004126 * ImportKeyTest.EcdsaSuccess
4127 *
4128 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4129 */
4130TEST_P(ImportKeyTest, EcdsaSuccess) {
4131 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4132 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004133 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004134 .Digest(Digest::SHA_2_256)
4135 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004136 KeyFormat::PKCS8, ec_256_key));
4137
4138 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004139 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4140 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4141
4142 CheckOrigin();
4143
4144 string message(32, 'a');
4145 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4146 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004147 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004148}
4149
4150/*
David Drysdale9b8d75e2023-09-05 15:16:47 +01004151 * ImportKeyTest.EcdsaSuccessCurveNotSpecified
4152 *
4153 * Verifies that importing and using an ECDSA P-256 key pair works correctly
4154 * when the EC_CURVE is not explicitly specified.
4155 */
4156TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
4157 if (AidlVersion() < 4) {
4158 /*
4159 * The KeyMint spec before V4 was not clear as to whether EC_CURVE was optional on import of
4160 * EC keys. However, this was not checked at the time so we can only be strict about
4161 * checking this for implementations of KeyMint version 4 and above.
4162 */
4163 GTEST_SKIP() << "Skipping EC_CURVE on import only strict since KeyMint v4";
4164 }
4165
4166 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4167 .Authorization(TAG_NO_AUTH_REQUIRED)
4168 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4169 .SigningKey()
4170 .Digest(Digest::SHA_2_256)
4171 .SetDefaultValidity(),
4172 KeyFormat::PKCS8, ec_256_key));
4173
4174 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4175 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4176 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4177
4178 CheckOrigin();
4179
4180 string message(32, 'a');
4181 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4182 string signature = SignMessage(message, params);
4183 LocalVerifyMessage(message, signature, params);
4184}
4185
4186/*
Selene Huang31ab4042020-04-29 04:22:39 -07004187 * ImportKeyTest.EcdsaP256RFC5915Success
4188 *
4189 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4190 * correctly.
4191 */
4192TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4193 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4194 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004195 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004196 .Digest(Digest::SHA_2_256)
4197 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004198 KeyFormat::PKCS8, ec_256_key_rfc5915));
4199
4200 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004201 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4202 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4203
4204 CheckOrigin();
4205
4206 string message(32, 'a');
4207 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4208 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004209 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004210}
4211
4212/*
4213 * ImportKeyTest.EcdsaP256SEC1Success
4214 *
4215 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4216 */
4217TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4218 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4219 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004220 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004221 .Digest(Digest::SHA_2_256)
4222 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004223 KeyFormat::PKCS8, ec_256_key_sec1));
4224
4225 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004226 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4227 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4228
4229 CheckOrigin();
4230
4231 string message(32, 'a');
4232 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4233 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004234 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004235}
4236
4237/*
4238 * ImportKeyTest.Ecdsa521Success
4239 *
4240 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4241 */
4242TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004243 if (SecLevel() == SecurityLevel::STRONGBOX) {
4244 GTEST_SKIP() << "Test not applicable to StrongBox device";
4245 }
Selene Huang31ab4042020-04-29 04:22:39 -07004246 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4247 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004248 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004249 .Digest(Digest::SHA_2_256)
4250 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004251 KeyFormat::PKCS8, ec_521_key));
4252
4253 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004254 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4255 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4256 CheckOrigin();
4257
4258 string message(32, 'a');
4259 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4260 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004261 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004262}
4263
4264/*
Selene Huang31ab4042020-04-29 04:22:39 -07004265 * ImportKeyTest.EcdsaCurveMismatch
4266 *
4267 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4268 * the correct way.
4269 */
4270TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4271 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4272 ImportKey(AuthorizationSetBuilder()
4273 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004274 .Digest(Digest::NONE)
4275 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004276 KeyFormat::PKCS8, ec_256_key));
4277}
4278
4279/*
David Drysdalee60248c2021-10-04 12:54:13 +01004280 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4281 *
4282 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4283 */
4284TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004285 if (AidlVersion() < 2) {
4286 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4287 // with other key purposes. However, this was not checked at the time
4288 // so we can only be strict about checking this for implementations of KeyMint
4289 // version 2 and above.
4290 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4291 }
David Drysdalee60248c2021-10-04 12:54:13 +01004292 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4293 ImportKey(AuthorizationSetBuilder()
4294 .Authorization(TAG_NO_AUTH_REQUIRED)
4295 .EcdsaSigningKey(EcCurve::P_256)
4296 .AttestKey()
4297 .Digest(Digest::SHA_2_256)
4298 .SetDefaultValidity(),
4299 KeyFormat::PKCS8, ec_256_key));
4300}
4301
4302/*
David Drysdale42fe1892021-10-14 14:43:46 +01004303 * ImportKeyTest.Ed25519RawSuccess
4304 *
4305 * Verifies that importing and using a raw Ed25519 private key works correctly.
4306 */
4307TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4308 if (!Curve25519Supported()) {
4309 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4310 }
4311
4312 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4313 .Authorization(TAG_NO_AUTH_REQUIRED)
4314 .EcdsaSigningKey(EcCurve::CURVE_25519)
4315 .Digest(Digest::NONE)
4316 .SetDefaultValidity(),
4317 KeyFormat::RAW, ed25519_key));
4318 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4319 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4320 CheckOrigin();
4321
4322 // The returned cert should hold the correct public key.
4323 ASSERT_GT(cert_chain_.size(), 0);
4324 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4325 ASSERT_NE(kmKeyCert, nullptr);
4326 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4327 ASSERT_NE(kmPubKey.get(), nullptr);
4328 size_t kmPubKeySize = 32;
4329 uint8_t kmPubKeyData[32];
4330 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4331 ASSERT_EQ(kmPubKeySize, 32);
4332 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4333
4334 string message(32, 'a');
4335 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4336 string signature = SignMessage(message, params);
4337 LocalVerifyMessage(message, signature, params);
4338}
4339
4340/*
4341 * ImportKeyTest.Ed25519Pkcs8Success
4342 *
4343 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4344 */
4345TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4346 if (!Curve25519Supported()) {
4347 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4348 }
4349
4350 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4351 .Authorization(TAG_NO_AUTH_REQUIRED)
4352 .EcdsaSigningKey(EcCurve::CURVE_25519)
4353 .Digest(Digest::NONE)
4354 .SetDefaultValidity(),
4355 KeyFormat::PKCS8, ed25519_pkcs8_key));
4356 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4357 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4358 CheckOrigin();
4359
4360 // The returned cert should hold the correct public key.
4361 ASSERT_GT(cert_chain_.size(), 0);
4362 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4363 ASSERT_NE(kmKeyCert, nullptr);
4364 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4365 ASSERT_NE(kmPubKey.get(), nullptr);
4366 size_t kmPubKeySize = 32;
4367 uint8_t kmPubKeyData[32];
4368 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4369 ASSERT_EQ(kmPubKeySize, 32);
4370 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4371
4372 string message(32, 'a');
4373 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4374 string signature = SignMessage(message, params);
4375 LocalVerifyMessage(message, signature, params);
4376}
4377
4378/*
4379 * ImportKeyTest.Ed25519CurveMismatch
4380 *
4381 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4382 * the correct way.
4383 */
4384TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4385 if (!Curve25519Supported()) {
4386 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4387 }
4388
4389 ASSERT_NE(ErrorCode::OK,
4390 ImportKey(AuthorizationSetBuilder()
4391 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4392 .Digest(Digest::NONE)
4393 .SetDefaultValidity(),
4394 KeyFormat::RAW, ed25519_key));
4395}
4396
4397/*
4398 * ImportKeyTest.Ed25519FormatMismatch
4399 *
4400 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4401 */
4402TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4403 if (!Curve25519Supported()) {
4404 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4405 }
4406
4407 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4408 .EcdsaSigningKey(EcCurve::CURVE_25519)
4409 .Digest(Digest::NONE)
4410 .SetDefaultValidity(),
4411 KeyFormat::PKCS8, ed25519_key));
4412 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4413 .EcdsaSigningKey(EcCurve::CURVE_25519)
4414 .Digest(Digest::NONE)
4415 .SetDefaultValidity(),
4416 KeyFormat::RAW, ed25519_pkcs8_key));
4417}
4418
4419/*
4420 * ImportKeyTest.Ed25519PurposeMismatch
4421 *
4422 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4423 */
4424TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4425 if (!Curve25519Supported()) {
4426 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4427 }
4428
4429 // Can't have both SIGN and ATTEST_KEY
4430 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4431 .EcdsaSigningKey(EcCurve::CURVE_25519)
4432 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4433 .Digest(Digest::NONE)
4434 .SetDefaultValidity(),
4435 KeyFormat::RAW, ed25519_key));
4436 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4437 // PKCS#8 format and so includes an OID).
4438 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4439 .EcdsaKey(EcCurve::CURVE_25519)
4440 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4441 .Digest(Digest::NONE)
4442 .SetDefaultValidity(),
4443 KeyFormat::PKCS8, ed25519_pkcs8_key));
4444}
4445
4446/*
4447 * ImportKeyTest.X25519RawSuccess
4448 *
4449 * Verifies that importing and using a raw X25519 private key works correctly.
4450 */
4451TEST_P(ImportKeyTest, X25519RawSuccess) {
4452 if (!Curve25519Supported()) {
4453 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4454 }
4455
4456 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4457 .Authorization(TAG_NO_AUTH_REQUIRED)
4458 .EcdsaKey(EcCurve::CURVE_25519)
4459 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4460 .SetDefaultValidity(),
4461 KeyFormat::RAW, x25519_key));
4462
4463 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4464 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4465 CheckOrigin();
4466}
4467
4468/*
4469 * ImportKeyTest.X25519Pkcs8Success
4470 *
4471 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4472 */
4473TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4474 if (!Curve25519Supported()) {
4475 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4476 }
4477
4478 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4479 .Authorization(TAG_NO_AUTH_REQUIRED)
4480 .EcdsaKey(EcCurve::CURVE_25519)
4481 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4482 .SetDefaultValidity(),
4483 KeyFormat::PKCS8, x25519_pkcs8_key));
4484
4485 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4486 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4487 CheckOrigin();
4488}
4489
4490/*
4491 * ImportKeyTest.X25519CurveMismatch
4492 *
4493 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4494 * the correct way.
4495 */
4496TEST_P(ImportKeyTest, X25519CurveMismatch) {
4497 if (!Curve25519Supported()) {
4498 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4499 }
4500
4501 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4502 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4503 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4504 .SetDefaultValidity(),
4505 KeyFormat::RAW, x25519_key));
4506}
4507
4508/*
4509 * ImportKeyTest.X25519FormatMismatch
4510 *
4511 * Verifies that importing an X25519 key with an invalid format fails.
4512 */
4513TEST_P(ImportKeyTest, X25519FormatMismatch) {
4514 if (!Curve25519Supported()) {
4515 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4516 }
4517
4518 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4519 .EcdsaKey(EcCurve::CURVE_25519)
4520 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4521 .SetDefaultValidity(),
4522 KeyFormat::PKCS8, x25519_key));
4523 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4524 .EcdsaKey(EcCurve::CURVE_25519)
4525 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4526 .SetDefaultValidity(),
4527 KeyFormat::RAW, x25519_pkcs8_key));
4528}
4529
4530/*
4531 * ImportKeyTest.X25519PurposeMismatch
4532 *
4533 * Verifies that importing an X25519 key pair with an invalid format fails.
4534 */
4535TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4536 if (!Curve25519Supported()) {
4537 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4538 }
4539
4540 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4541 .EcdsaKey(EcCurve::CURVE_25519)
4542 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4543 .SetDefaultValidity(),
4544 KeyFormat::PKCS8, x25519_pkcs8_key));
4545 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4546 .EcdsaSigningKey(EcCurve::CURVE_25519)
4547 .SetDefaultValidity(),
4548 KeyFormat::PKCS8, x25519_pkcs8_key));
4549}
4550
4551/*
Selene Huang31ab4042020-04-29 04:22:39 -07004552 * ImportKeyTest.AesSuccess
4553 *
4554 * Verifies that importing and using an AES key works.
4555 */
4556TEST_P(ImportKeyTest, AesSuccess) {
4557 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4558 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4559 .Authorization(TAG_NO_AUTH_REQUIRED)
4560 .AesEncryptionKey(key.size() * 8)
4561 .EcbMode()
4562 .Padding(PaddingMode::PKCS7),
4563 KeyFormat::RAW, key));
4564
4565 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4566 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4567 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4568 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4569 CheckOrigin();
4570
4571 string message = "Hello World!";
4572 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4573 string ciphertext = EncryptMessage(message, params);
4574 string plaintext = DecryptMessage(ciphertext, params);
4575 EXPECT_EQ(message, plaintext);
4576}
4577
4578/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004579 * ImportKeyTest.AesFailure
4580 *
4581 * Verifies that importing an invalid AES key fails.
4582 */
4583TEST_P(ImportKeyTest, AesFailure) {
4584 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4585 uint32_t bitlen = key.size() * 8;
4586 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004587 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004588 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004589 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004590 .Authorization(TAG_NO_AUTH_REQUIRED)
4591 .AesEncryptionKey(key_size)
4592 .EcbMode()
4593 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004594 KeyFormat::RAW, key);
4595 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004596 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4597 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004598 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004599
4600 // Explicit key size matches that of the provided key, but it's not a valid size.
4601 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4602 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4603 ImportKey(AuthorizationSetBuilder()
4604 .Authorization(TAG_NO_AUTH_REQUIRED)
4605 .AesEncryptionKey(long_key.size() * 8)
4606 .EcbMode()
4607 .Padding(PaddingMode::PKCS7),
4608 KeyFormat::RAW, long_key));
4609 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4610 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4611 ImportKey(AuthorizationSetBuilder()
4612 .Authorization(TAG_NO_AUTH_REQUIRED)
4613 .AesEncryptionKey(short_key.size() * 8)
4614 .EcbMode()
4615 .Padding(PaddingMode::PKCS7),
4616 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004617}
4618
4619/*
4620 * ImportKeyTest.TripleDesSuccess
4621 *
4622 * Verifies that importing and using a 3DES key works.
4623 */
4624TEST_P(ImportKeyTest, TripleDesSuccess) {
4625 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4626 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4627 .Authorization(TAG_NO_AUTH_REQUIRED)
4628 .TripleDesEncryptionKey(168)
4629 .EcbMode()
4630 .Padding(PaddingMode::PKCS7),
4631 KeyFormat::RAW, key));
4632
4633 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4634 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4635 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4636 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4637 CheckOrigin();
4638
4639 string message = "Hello World!";
4640 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4641 string ciphertext = EncryptMessage(message, params);
4642 string plaintext = DecryptMessage(ciphertext, params);
4643 EXPECT_EQ(message, plaintext);
4644}
4645
4646/*
4647 * ImportKeyTest.TripleDesFailure
4648 *
4649 * Verifies that importing an invalid 3DES key fails.
4650 */
4651TEST_P(ImportKeyTest, TripleDesFailure) {
4652 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004653 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004654 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004655 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004656 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004657 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004658 .Authorization(TAG_NO_AUTH_REQUIRED)
4659 .TripleDesEncryptionKey(key_size)
4660 .EcbMode()
4661 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004662 KeyFormat::RAW, key);
4663 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004664 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4665 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004666 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004667 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004668 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004669 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4670 ImportKey(AuthorizationSetBuilder()
4671 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004672 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004673 .EcbMode()
4674 .Padding(PaddingMode::PKCS7),
4675 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004676 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004677 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4678 ImportKey(AuthorizationSetBuilder()
4679 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004680 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004681 .EcbMode()
4682 .Padding(PaddingMode::PKCS7),
4683 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004684}
4685
4686/*
4687 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004688 *
4689 * Verifies that importing and using an HMAC key works.
4690 */
4691TEST_P(ImportKeyTest, HmacKeySuccess) {
4692 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4693 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4694 .Authorization(TAG_NO_AUTH_REQUIRED)
4695 .HmacKey(key.size() * 8)
4696 .Digest(Digest::SHA_2_256)
4697 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4698 KeyFormat::RAW, key));
4699
4700 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4701 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4702 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4703 CheckOrigin();
4704
4705 string message = "Hello World!";
4706 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4707 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4708}
4709
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004710/*
4711 * ImportKeyTest.GetKeyCharacteristics
4712 *
4713 * Verifies that imported keys have the correct characteristics.
4714 */
4715TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4716 vector<uint8_t> key_blob;
4717 vector<KeyCharacteristics> key_characteristics;
4718 auto base_builder = AuthorizationSetBuilder()
4719 .Padding(PaddingMode::NONE)
4720 .Authorization(TAG_NO_AUTH_REQUIRED)
4721 .SetDefaultValidity();
4722 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4723 Algorithm::TRIPLE_DES};
4724 ErrorCode result;
4725 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4726 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4727 for (auto alg : algorithms) {
4728 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4729 AuthorizationSetBuilder builder(base_builder);
4730 switch (alg) {
4731 case Algorithm::RSA:
4732 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4733
4734 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4735 &key_characteristics);
4736 break;
4737 case Algorithm::EC:
4738 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4739 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4740 &key_characteristics);
4741 break;
4742 case Algorithm::HMAC:
4743 builder.HmacKey(128)
4744 .Digest(Digest::SHA_2_256)
4745 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4746 result =
4747 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4748 break;
4749 case Algorithm::AES:
4750 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4751 result =
4752 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4753 break;
4754 case Algorithm::TRIPLE_DES:
4755 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4756 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4757 &key_characteristics);
4758 break;
4759 default:
4760 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4761 continue;
4762 }
4763 ASSERT_EQ(ErrorCode::OK, result);
4764 CheckCharacteristics(key_blob, key_characteristics);
4765 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4766 }
4767}
4768
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004769/*
4770 * ImportKeyTest.RsaOaepMGFDigestSuccess
4771 *
4772 * Include MGF-Digest explicitly in import key authorization list.
4773 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4774 * should have the correct characteristics.
4775 */
4776TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
4777 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4778 size_t key_size = 2048;
4779
4780 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4781 .OaepMGFDigest(mgf_digests)
4782 .Authorization(TAG_NO_AUTH_REQUIRED)
4783 .RsaEncryptionKey(key_size, 65537)
4784 .Digest(Digest::SHA_2_256)
4785 .Padding(PaddingMode::RSA_OAEP)
4786 .SetDefaultValidity(),
4787 KeyFormat::PKCS8, rsa_2048_key));
4788
4789 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4790 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4791 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4792 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4793 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4794 CheckOrigin();
4795
4796 // Make sure explicitly specified mgf-digests exist in key characteristics.
4797 assert_mgf_digests_present_in_key_characteristics(key_characteristics_, mgf_digests);
4798
4799 string message = "Hello";
4800
4801 for (auto digest : mgf_digests) {
4802 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4803 auto params = AuthorizationSetBuilder()
4804 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4805 .Digest(Digest::SHA_2_256)
4806 .Padding(PaddingMode::RSA_OAEP);
4807 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4808 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4809 EXPECT_EQ(key_size / 8, ciphertext1.size());
4810
4811 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4812 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4813 EXPECT_EQ(key_size / 8, ciphertext2.size());
4814
4815 // OAEP randomizes padding so every result should be different (with astronomically high
4816 // probability).
4817 EXPECT_NE(ciphertext1, ciphertext2);
4818
4819 string plaintext1 = DecryptMessage(ciphertext1, params);
4820 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4821 string plaintext2 = DecryptMessage(ciphertext2, params);
4822 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4823
4824 // Decrypting corrupted ciphertext should fail.
4825 size_t offset_to_corrupt = ciphertext1.size() - 1;
4826 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4827 ciphertext1[offset_to_corrupt] = corrupt_byte;
4828
4829 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4830 string result;
4831 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4832 EXPECT_EQ(0U, result.size());
4833 }
4834}
4835
4836/*
4837 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4838 *
4839 * Don't specify MGF-Digest explicitly in import key authorization list.
4840 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4841 * verify that imported key should have the correct characteristics. Default
4842 * mgf-digest shouldn't be included in key charecteristics.
4843 */
4844TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4845 size_t key_size = 2048;
4846 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4847 .Authorization(TAG_NO_AUTH_REQUIRED)
4848 .RsaEncryptionKey(key_size, 65537)
4849 .Digest(Digest::SHA_2_256)
4850 .Padding(PaddingMode::RSA_OAEP)
4851 .SetDefaultValidity(),
4852 KeyFormat::PKCS8, rsa_2048_key));
4853
4854 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4855 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4856 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4857 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4858 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4859 CheckOrigin();
4860
4861 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
4862 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
4863}
4864
Selene Huang31ab4042020-04-29 04:22:39 -07004865INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4866
4867auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004868 // IKeyMintDevice.aidl
4869 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4870 "020100" // INTEGER length 1 value 0x00 (version)
4871 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4872 "934bf94e2aa28a3f83c9f79297250262"
4873 "fbe3276b5a1c91159bbfa3ef8957aac8"
4874 "4b59b30b455a79c2973480823d8b3863"
4875 "c3deef4a8e243590268d80e18751a0e1"
4876 "30f67ce6a1ace9f79b95e097474febc9"
4877 "81195b1d13a69086c0863f66a7b7fdb4"
4878 "8792227b1ac5e2489febdf087ab54864"
4879 "83033a6f001ca5d1ec1e27f5c30f4cec"
4880 "2642074a39ae68aee552e196627a8e3d"
4881 "867e67a8c01b11e75f13cca0a97ab668"
4882 "b50cda07a8ecb7cd8e3dd7009c963653"
4883 "4f6f239cffe1fc8daa466f78b676c711"
4884 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4885 "99b801597d5220e307eaa5bee507fb94"
4886 "d1fa69f9e519b2de315bac92c36f2ea1"
4887 "fa1df4478c0ddedeae8c70e0233cd098"
4888 "040c" // OCTET STRING length 0x0c (initializationVector)
4889 "d796b02c370f1fa4cc0124f1"
4890 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4891 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4892 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4893 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4894 "3106" // SET length 0x06
4895 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4896 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4897 // } end SET
4898 // } end [1]
4899 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4900 "020120" // INTEGER length 1 value 0x20 (AES)
4901 // } end [2]
4902 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4903 "02020100" // INTEGER length 2 value 0x100
4904 // } end [3]
4905 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4906 "3103" // SET length 0x03 {
4907 "020101" // INTEGER length 1 value 0x01 (ECB)
4908 // } end SET
4909 // } end [4]
4910 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4911 "3103" // SET length 0x03 {
4912 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4913 // } end SET
4914 // } end [5]
4915 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4916 // (noAuthRequired)
4917 "0500" // NULL
4918 // } end [503]
4919 // } end SEQUENCE (AuthorizationList)
4920 // } end SEQUENCE (KeyDescription)
4921 "0420" // OCTET STRING length 0x20 (encryptedKey)
4922 "ccd540855f833a5e1480bfd2d36faf3a"
4923 "eee15df5beabe2691bc82dde2a7aa910"
4924 "0410" // OCTET STRING length 0x10 (tag)
4925 "64c9f689c60ff6223ab6e6999e0eb6e5"
4926 // } SEQUENCE (SecureKeyWrapper)
4927);
Selene Huang31ab4042020-04-29 04:22:39 -07004928
4929auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004930 // IKeyMintDevice.aidl
4931 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4932 "020100" // INTEGER length 1 value 0x00 (version)
4933 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4934 "aad93ed5924f283b4bb5526fbe7a1412"
4935 "f9d9749ec30db9062b29e574a8546f33"
4936 "c88732452f5b8e6a391ee76c39ed1712"
4937 "c61d8df6213dec1cffbc17a8c6d04c7b"
4938 "30893d8daa9b2015213e219468215532"
4939 "07f8f9931c4caba23ed3bee28b36947e"
4940 "47f10e0a5c3dc51c988a628daad3e5e1"
4941 "f4005e79c2d5a96c284b4b8d7e4948f3"
4942 "31e5b85dd5a236f85579f3ea1d1b8484"
4943 "87470bdb0ab4f81a12bee42c99fe0df4"
4944 "bee3759453e69ad1d68a809ce06b949f"
4945 "7694a990429b2fe81e066ff43e56a216"
4946 "02db70757922a4bcc23ab89f1e35da77"
4947 "586775f423e519c2ea394caf48a28d0c"
4948 "8020f1dcf6b3a68ec246f615ae96dae9"
4949 "a079b1f6eb959033c1af5c125fd94168"
4950 "040c" // OCTET STRING length 0x0c (initializationVector)
4951 "6d9721d08589581ab49204a3"
4952 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4953 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4954 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4955 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4956 "3106" // SET length 0x06
4957 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4958 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4959 // } end SET
4960 // } end [1]
4961 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4962 "020120" // INTEGER length 1 value 0x20 (AES)
4963 // } end [2]
4964 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4965 "02020100" // INTEGER length 2 value 0x100
4966 // } end [3]
4967 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4968 "3103" // SET length 0x03 {
4969 "020101" // INTEGER length 1 value 0x01 (ECB)
4970 // } end SET
4971 // } end [4]
4972 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4973 "3103" // SET length 0x03 {
4974 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4975 // } end SET
4976 // } end [5]
4977 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4978 // (noAuthRequired)
4979 "0500" // NULL
4980 // } end [503]
4981 // } end SEQUENCE (AuthorizationList)
4982 // } end SEQUENCE (KeyDescription)
4983 "0420" // OCTET STRING length 0x20 (encryptedKey)
4984 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4985 "c20d1f99a9a024a76f35c8e2cab9b68d"
4986 "0410" // OCTET STRING length 0x10 (tag)
4987 "2560c70109ae67c030f00b98b512a670"
4988 // } SEQUENCE (SecureKeyWrapper)
4989);
Selene Huang31ab4042020-04-29 04:22:39 -07004990
4991auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004992 // RFC 5208 s5
4993 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4994 "020100" // INTEGER length 1 value 0x00 (version)
4995 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4996 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4997 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4998 "0500" // NULL (parameters)
4999 // } SEQUENCE (AlgorithmIdentifier)
5000 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
5001 // RFC 8017 A.1.2
5002 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
5003 "020100" // INTEGER length 1 value 0x00 (version)
5004 "02820101" // INTEGER length 0x0101 (modulus) value...
5005 "00aec367931d8900ce56b0067f7d70e1" // 0x10
5006 "fc653f3f34d194c1fed50018fb43db93" // 0x20
5007 "7b06e673a837313d56b1c725150a3fef" // 0x30
5008 "86acbddc41bb759c2854eae32d35841e" // 0x40
5009 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
5010 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
5011 "312d7bd5921ffaea1347c157406fef71" // 0x70
5012 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
5013 "f4645c11f5c1374c3886427411c44979" // 0x90
5014 "6792e0bef75dec858a2123c36753e02a" // 0xa0
5015 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
5016 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
5017 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
5018 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
5019 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
5020 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
5021 "55" // 0x101
5022 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
5023 "02820100" // INTEGER length 0x100 (privateExponent) value...
5024 "431447b6251908112b1ee76f99f3711a" // 0x10
5025 "52b6630960046c2de70de188d833f8b8" // 0x20
5026 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
5027 "641f7fe24f14c67a88959bdb27766df9" // 0x40
5028 "e710b630a03adc683b5d2c43080e52be" // 0x50
5029 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
5030 "822bccff087d63c940ba8a45f670feb2" // 0x70
5031 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
5032 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
5033 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
5034 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
5035 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
5036 "52659d5a5ba05b663737a8696281865b" // 0xd0
5037 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
5038 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
5039 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5040 "028181" // INTEGER length 0x81 (prime1) value...
5041 "00de392e18d682c829266cc3454e1d61" // 0x10
5042 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5043 "ff841be5bac82a164c5970007047b8c5" // 0x30
5044 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5045 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5046 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5047 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5048 "9e91346130748a6e3c124f9149d71c74" // 0x80
5049 "35"
5050 "028181" // INTEGER length 0x81 (prime2) value...
5051 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5052 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5053 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5054 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5055 "9ed39a2d934c880440aed8832f984316" // 0x50
5056 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5057 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5058 "b880677c068e1be936e81288815252a8" // 0x80
5059 "a1"
5060 "028180" // INTEGER length 0x80 (exponent1) value...
5061 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5062 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5063 "5a063212a4f105a3764743e53281988a" // 0x30
5064 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5065 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5066 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5067 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5068 "4719d6e2b9439823719cd08bcd031781" // 0x80
5069 "028181" // INTEGER length 0x81 (exponent2) value...
5070 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5071 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5072 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5073 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5074 "1254186af30b22c10582a8a43e34fe94" // 0x50
5075 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5076 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5077 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5078 "61"
5079 "028181" // INTEGER length 0x81 (coefficient) value...
5080 "00c931617c77829dfb1270502be9195c" // 0x10
5081 "8f2830885f57dba869536811e6864236" // 0x20
5082 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5083 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5084 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5085 "959356210723287b0affcc9f727044d4" // 0x60
5086 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5087 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5088 "22"
5089 // } SEQUENCE
5090 // } SEQUENCE ()
5091);
Selene Huang31ab4042020-04-29 04:22:39 -07005092
5093string zero_masking_key =
5094 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5095string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5096
5097class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5098
5099TEST_P(ImportWrappedKeyTest, Success) {
5100 auto wrapping_key_desc = AuthorizationSetBuilder()
5101 .RsaEncryptionKey(2048, 65537)
5102 .Digest(Digest::SHA_2_256)
5103 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005104 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5105 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005106
5107 ASSERT_EQ(ErrorCode::OK,
5108 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5109 AuthorizationSetBuilder()
5110 .Digest(Digest::SHA_2_256)
5111 .Padding(PaddingMode::RSA_OAEP)));
5112
5113 string message = "Hello World!";
5114 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5115 string ciphertext = EncryptMessage(message, params);
5116 string plaintext = DecryptMessage(ciphertext, params);
5117 EXPECT_EQ(message, plaintext);
5118}
5119
David Drysdaled2cc8c22021-04-15 13:29:45 +01005120/*
5121 * ImportWrappedKeyTest.SuccessSidsIgnored
5122 *
5123 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5124 * include Tag:USER_SECURE_ID.
5125 */
5126TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5127 auto wrapping_key_desc = AuthorizationSetBuilder()
5128 .RsaEncryptionKey(2048, 65537)
5129 .Digest(Digest::SHA_2_256)
5130 .Padding(PaddingMode::RSA_OAEP)
5131 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5132 .SetDefaultValidity();
5133
5134 int64_t password_sid = 42;
5135 int64_t biometric_sid = 24;
5136 ASSERT_EQ(ErrorCode::OK,
5137 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5138 AuthorizationSetBuilder()
5139 .Digest(Digest::SHA_2_256)
5140 .Padding(PaddingMode::RSA_OAEP),
5141 password_sid, biometric_sid));
5142
5143 string message = "Hello World!";
5144 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5145 string ciphertext = EncryptMessage(message, params);
5146 string plaintext = DecryptMessage(ciphertext, params);
5147 EXPECT_EQ(message, plaintext);
5148}
5149
Selene Huang31ab4042020-04-29 04:22:39 -07005150TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5151 auto wrapping_key_desc = AuthorizationSetBuilder()
5152 .RsaEncryptionKey(2048, 65537)
5153 .Digest(Digest::SHA_2_256)
5154 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005155 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5156 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005157
5158 ASSERT_EQ(ErrorCode::OK,
5159 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5160 AuthorizationSetBuilder()
5161 .Digest(Digest::SHA_2_256)
5162 .Padding(PaddingMode::RSA_OAEP)));
5163}
5164
5165TEST_P(ImportWrappedKeyTest, WrongMask) {
5166 auto wrapping_key_desc = AuthorizationSetBuilder()
5167 .RsaEncryptionKey(2048, 65537)
5168 .Digest(Digest::SHA_2_256)
5169 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005170 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5171 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005172
5173 ASSERT_EQ(
5174 ErrorCode::VERIFICATION_FAILED,
5175 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5176 AuthorizationSetBuilder()
5177 .Digest(Digest::SHA_2_256)
5178 .Padding(PaddingMode::RSA_OAEP)));
5179}
5180
5181TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5182 auto wrapping_key_desc = AuthorizationSetBuilder()
5183 .RsaEncryptionKey(2048, 65537)
5184 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005185 .Padding(PaddingMode::RSA_OAEP)
5186 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005187
5188 ASSERT_EQ(
5189 ErrorCode::INCOMPATIBLE_PURPOSE,
5190 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5191 AuthorizationSetBuilder()
5192 .Digest(Digest::SHA_2_256)
5193 .Padding(PaddingMode::RSA_OAEP)));
5194}
5195
David Drysdaled2cc8c22021-04-15 13:29:45 +01005196TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5197 auto wrapping_key_desc = AuthorizationSetBuilder()
5198 .RsaEncryptionKey(2048, 65537)
5199 .Digest(Digest::SHA_2_256)
5200 .Padding(PaddingMode::RSA_PSS)
5201 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5202 .SetDefaultValidity();
5203
5204 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5205 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5206 AuthorizationSetBuilder()
5207 .Digest(Digest::SHA_2_256)
5208 .Padding(PaddingMode::RSA_OAEP)));
5209}
5210
5211TEST_P(ImportWrappedKeyTest, WrongDigest) {
5212 auto wrapping_key_desc = AuthorizationSetBuilder()
5213 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005214 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005215 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005216 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5217 .SetDefaultValidity();
5218
5219 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5220 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5221 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005222 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005223 .Padding(PaddingMode::RSA_OAEP)));
5224}
5225
Selene Huang31ab4042020-04-29 04:22:39 -07005226INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5227
5228typedef KeyMintAidlTestBase EncryptionOperationsTest;
5229
5230/*
5231 * EncryptionOperationsTest.RsaNoPaddingSuccess
5232 *
David Drysdale59cae642021-05-12 13:52:03 +01005233 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005234 */
5235TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005236 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005237 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5239 .Authorization(TAG_NO_AUTH_REQUIRED)
5240 .RsaEncryptionKey(2048, exponent)
5241 .Padding(PaddingMode::NONE)
5242 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005243
David Drysdaled2cc8c22021-04-15 13:29:45 +01005244 string message = string(2048 / 8, 'a');
5245 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005246 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005247 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005248
David Drysdale59cae642021-05-12 13:52:03 +01005249 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005250 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005251
David Drysdaled2cc8c22021-04-15 13:29:45 +01005252 // Unpadded RSA is deterministic
5253 EXPECT_EQ(ciphertext1, ciphertext2);
5254
5255 CheckedDeleteKey();
5256 }
Selene Huang31ab4042020-04-29 04:22:39 -07005257}
5258
5259/*
5260 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5261 *
David Drysdale59cae642021-05-12 13:52:03 +01005262 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005263 */
5264TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5265 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5266 .Authorization(TAG_NO_AUTH_REQUIRED)
5267 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005268 .Padding(PaddingMode::NONE)
5269 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005270
5271 string message = "1";
5272 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5273
David Drysdale59cae642021-05-12 13:52:03 +01005274 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005275 EXPECT_EQ(2048U / 8, ciphertext.size());
5276
5277 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5278 string plaintext = DecryptMessage(ciphertext, params);
5279
5280 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005281}
5282
5283/*
Selene Huang31ab4042020-04-29 04:22:39 -07005284 * EncryptionOperationsTest.RsaOaepSuccess
5285 *
David Drysdale59cae642021-05-12 13:52:03 +01005286 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005287 */
5288TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5289 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005290 auto mgf_digest = Digest::SHA1;
Selene Huang31ab4042020-04-29 04:22:39 -07005291
5292 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005293 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5294 .Authorization(TAG_NO_AUTH_REQUIRED)
5295 .RsaEncryptionKey(key_size, 65537)
5296 .Padding(PaddingMode::RSA_OAEP)
5297 .Digest(digests)
5298 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5299 .SetDefaultValidity()));
5300
5301 // Make sure explicitly specified mgf-digest exist in key characteristics.
5302 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
Selene Huang31ab4042020-04-29 04:22:39 -07005303
5304 string message = "Hello";
5305
5306 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005307 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5308
5309 auto params = AuthorizationSetBuilder()
5310 .Digest(digest)
5311 .Padding(PaddingMode::RSA_OAEP)
5312 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5313 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005314 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5315 EXPECT_EQ(key_size / 8, ciphertext1.size());
5316
David Drysdale59cae642021-05-12 13:52:03 +01005317 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005318 EXPECT_EQ(key_size / 8, ciphertext2.size());
5319
5320 // OAEP randomizes padding so every result should be different (with astronomically high
5321 // probability).
5322 EXPECT_NE(ciphertext1, ciphertext2);
5323
5324 string plaintext1 = DecryptMessage(ciphertext1, params);
5325 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5326 string plaintext2 = DecryptMessage(ciphertext2, params);
5327 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5328
5329 // Decrypting corrupted ciphertext should fail.
5330 size_t offset_to_corrupt = random() % ciphertext1.size();
5331 char corrupt_byte;
5332 do {
5333 corrupt_byte = static_cast<char>(random() % 256);
5334 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5335 ciphertext1[offset_to_corrupt] = corrupt_byte;
5336
5337 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5338 string result;
5339 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5340 EXPECT_EQ(0U, result.size());
5341 }
5342}
5343
5344/*
5345 * EncryptionOperationsTest.RsaOaepInvalidDigest
5346 *
David Drysdale59cae642021-05-12 13:52:03 +01005347 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005348 * without a digest.
5349 */
5350TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5352 .Authorization(TAG_NO_AUTH_REQUIRED)
5353 .RsaEncryptionKey(2048, 65537)
5354 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005355 .Digest(Digest::NONE)
5356 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005357
5358 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005359 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005360}
5361
5362/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005363 * EncryptionOperationsTest.RsaOaepInvalidPadding
5364 *
David Drysdale59cae642021-05-12 13:52:03 +01005365 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005366 * with a padding value that is only suitable for signing/verifying.
5367 */
5368TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5369 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5370 .Authorization(TAG_NO_AUTH_REQUIRED)
5371 .RsaEncryptionKey(2048, 65537)
5372 .Padding(PaddingMode::RSA_PSS)
5373 .Digest(Digest::NONE)
5374 .SetDefaultValidity()));
5375
5376 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005377 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005378}
5379
5380/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005381 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005382 *
David Drysdale59cae642021-05-12 13:52:03 +01005383 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005384 * with a different digest than was used to encrypt.
5385 */
5386TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005387 if (SecLevel() == SecurityLevel::STRONGBOX) {
5388 GTEST_SKIP() << "Test not applicable to StrongBox device";
5389 }
Selene Huang31ab4042020-04-29 04:22:39 -07005390
5391 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5392 .Authorization(TAG_NO_AUTH_REQUIRED)
5393 .RsaEncryptionKey(1024, 65537)
5394 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005395 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5396 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005397 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005398 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005399 message,
5400 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5401
5402 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5403 .Digest(Digest::SHA_2_256)
5404 .Padding(PaddingMode::RSA_OAEP)));
5405 string result;
5406 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5407 EXPECT_EQ(0U, result.size());
5408}
5409
5410/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005411 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5412 *
David Drysdale59cae642021-05-12 13:52:03 +01005413 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005414 * digests.
5415 */
5416TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5417 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5418
5419 size_t key_size = 2048; // Need largish key for SHA-512 test.
5420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5421 .OaepMGFDigest(digests)
5422 .Authorization(TAG_NO_AUTH_REQUIRED)
5423 .RsaEncryptionKey(key_size, 65537)
5424 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005425 .Digest(Digest::SHA_2_256)
5426 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005427
Shawn Willden20732262023-04-21 16:36:00 -06005428 std::vector<Digest> mgf1DigestsInAuths;
5429 mgf1DigestsInAuths.reserve(digests.size());
5430 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5431 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5432 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5433 KeyParameterValue value = param.value;
5434 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5435 }
5436 });
5437
5438 std::sort(digests.begin(), digests.end());
5439 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5440 EXPECT_EQ(digests, mgf1DigestsInAuths);
5441
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005442 string message = "Hello";
5443
5444 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005445 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005446 auto params = AuthorizationSetBuilder()
5447 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5448 .Digest(Digest::SHA_2_256)
5449 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005450 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005451 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5452 EXPECT_EQ(key_size / 8, ciphertext1.size());
5453
David Drysdale59cae642021-05-12 13:52:03 +01005454 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005455 EXPECT_EQ(key_size / 8, ciphertext2.size());
5456
5457 // OAEP randomizes padding so every result should be different (with astronomically high
5458 // probability).
5459 EXPECT_NE(ciphertext1, ciphertext2);
5460
5461 string plaintext1 = DecryptMessage(ciphertext1, params);
5462 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5463 string plaintext2 = DecryptMessage(ciphertext2, params);
5464 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5465
5466 // Decrypting corrupted ciphertext should fail.
5467 size_t offset_to_corrupt = random() % ciphertext1.size();
5468 char corrupt_byte;
5469 do {
5470 corrupt_byte = static_cast<char>(random() % 256);
5471 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5472 ciphertext1[offset_to_corrupt] = corrupt_byte;
5473
5474 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5475 string result;
5476 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5477 EXPECT_EQ(0U, result.size());
5478 }
5479}
5480
5481/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005482 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5483 *
5484 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5485 * specified, defaulting to SHA-1.
5486 */
5487TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5488 size_t key_size = 2048;
5489 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5490 .Authorization(TAG_NO_AUTH_REQUIRED)
5491 .RsaEncryptionKey(key_size, 65537)
5492 .Padding(PaddingMode::RSA_OAEP)
5493 .Digest(Digest::SHA_2_256)
5494 .SetDefaultValidity()));
5495
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005496 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
5497 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
5498
David Drysdaleae3727b2021-11-11 09:00:14 +00005499 // Do local RSA encryption using the default MGF digest of SHA-1.
5500 string message = "Hello";
5501 auto params =
5502 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5503 string ciphertext = LocalRsaEncryptMessage(message, params);
5504 EXPECT_EQ(key_size / 8, ciphertext.size());
5505
5506 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5507 string plaintext = DecryptMessage(ciphertext, params);
5508 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5509
5510 // Decrypting corrupted ciphertext should fail.
5511 size_t offset_to_corrupt = random() % ciphertext.size();
5512 char corrupt_byte;
5513 do {
5514 corrupt_byte = static_cast<char>(random() % 256);
5515 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5516 ciphertext[offset_to_corrupt] = corrupt_byte;
5517
5518 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5519 string result;
5520 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5521 EXPECT_EQ(0U, result.size());
5522}
5523
5524/*
5525 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5526 *
5527 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5528 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5529 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5530 */
5531TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5532 size_t key_size = 2048;
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005533 auto mgf_digest = Digest::SHA_2_256;
5534 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5535 .Authorization(TAG_NO_AUTH_REQUIRED)
5536 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5537 .RsaEncryptionKey(key_size, 65537)
5538 .Padding(PaddingMode::RSA_OAEP)
5539 .Digest(Digest::SHA_2_256)
5540 .SetDefaultValidity()));
5541
5542 // Make sure explicitly specified mgf-digest exist in key characteristics.
5543 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5544 // Make sure default mgf-digest is not included in key characteristics.
5545 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
David Drysdaleae3727b2021-11-11 09:00:14 +00005546
5547 // Do local RSA encryption using the default MGF digest of SHA-1.
5548 string message = "Hello";
5549 auto params =
5550 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5551 string ciphertext = LocalRsaEncryptMessage(message, params);
5552 EXPECT_EQ(key_size / 8, ciphertext.size());
5553
5554 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5555 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5556 // is checked against those values, and found absent.
5557 auto result = Begin(KeyPurpose::DECRYPT, params);
5558 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5559 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5560}
5561
5562/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005563 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5564 *
David Drysdale59cae642021-05-12 13:52:03 +01005565 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005566 * with incompatible MGF digest.
5567 */
5568TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005569 auto mgf_digest = Digest::SHA_2_256;
5570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5571 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5572 .Authorization(TAG_NO_AUTH_REQUIRED)
5573 .RsaEncryptionKey(2048, 65537)
5574 .Padding(PaddingMode::RSA_OAEP)
5575 .Digest(Digest::SHA_2_256)
5576 .SetDefaultValidity()));
5577 // Make sure explicitly specified mgf-digest exist in key characteristics.
5578 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5579
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005580 string message = "Hello World!";
5581
5582 auto params = AuthorizationSetBuilder()
5583 .Padding(PaddingMode::RSA_OAEP)
5584 .Digest(Digest::SHA_2_256)
5585 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005586 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005587}
5588
5589/*
5590 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5591 *
5592 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5593 * with unsupported MGF digest.
5594 */
5595TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005596 auto mgf_digest = Digest::SHA_2_256;
5597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5598 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5599 .Authorization(TAG_NO_AUTH_REQUIRED)
5600 .RsaEncryptionKey(2048, 65537)
5601 .Padding(PaddingMode::RSA_OAEP)
5602 .Digest(Digest::SHA_2_256)
5603 .SetDefaultValidity()));
5604 // Make sure explicitly specified mgf-digest exist in key characteristics.
5605 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5606
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005607 string message = "Hello World!";
5608
5609 auto params = AuthorizationSetBuilder()
5610 .Padding(PaddingMode::RSA_OAEP)
5611 .Digest(Digest::SHA_2_256)
5612 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005613 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005614}
5615
5616/*
Selene Huang31ab4042020-04-29 04:22:39 -07005617 * EncryptionOperationsTest.RsaPkcs1Success
5618 *
5619 * Verifies that RSA PKCS encryption/decrypts works.
5620 */
5621TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5623 .Authorization(TAG_NO_AUTH_REQUIRED)
5624 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005625 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5626 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005627
5628 string message = "Hello World!";
5629 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005630 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005631 EXPECT_EQ(2048U / 8, ciphertext1.size());
5632
David Drysdale59cae642021-05-12 13:52:03 +01005633 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005634 EXPECT_EQ(2048U / 8, ciphertext2.size());
5635
5636 // PKCS1 v1.5 randomizes padding so every result should be different.
5637 EXPECT_NE(ciphertext1, ciphertext2);
5638
5639 string plaintext = DecryptMessage(ciphertext1, params);
5640 EXPECT_EQ(message, plaintext);
5641
5642 // Decrypting corrupted ciphertext should fail.
5643 size_t offset_to_corrupt = random() % ciphertext1.size();
5644 char corrupt_byte;
5645 do {
5646 corrupt_byte = static_cast<char>(random() % 256);
5647 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5648 ciphertext1[offset_to_corrupt] = corrupt_byte;
5649
5650 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5651 string result;
5652 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5653 EXPECT_EQ(0U, result.size());
5654}
5655
5656/*
Selene Huang31ab4042020-04-29 04:22:39 -07005657 * EncryptionOperationsTest.EcdsaEncrypt
5658 *
5659 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5660 */
5661TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5662 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5663 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005664 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005665 .Digest(Digest::NONE)
5666 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005667 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5668 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5669 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5670}
5671
5672/*
5673 * EncryptionOperationsTest.HmacEncrypt
5674 *
5675 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5676 */
5677TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5679 .Authorization(TAG_NO_AUTH_REQUIRED)
5680 .HmacKey(128)
5681 .Digest(Digest::SHA_2_256)
5682 .Padding(PaddingMode::NONE)
5683 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5684 auto params = AuthorizationSetBuilder()
5685 .Digest(Digest::SHA_2_256)
5686 .Padding(PaddingMode::NONE)
5687 .Authorization(TAG_MAC_LENGTH, 128);
5688 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5689 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5690}
5691
5692/*
5693 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5694 *
5695 * Verifies that AES ECB mode works.
5696 */
5697TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5699 .Authorization(TAG_NO_AUTH_REQUIRED)
5700 .AesEncryptionKey(128)
5701 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5702 .Padding(PaddingMode::NONE)));
5703
5704 ASSERT_GT(key_blob_.size(), 0U);
5705 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5706
5707 // Two-block message.
5708 string message = "12345678901234567890123456789012";
5709 string ciphertext1 = EncryptMessage(message, params);
5710 EXPECT_EQ(message.size(), ciphertext1.size());
5711
5712 string ciphertext2 = EncryptMessage(string(message), params);
5713 EXPECT_EQ(message.size(), ciphertext2.size());
5714
5715 // ECB is deterministic.
5716 EXPECT_EQ(ciphertext1, ciphertext2);
5717
5718 string plaintext = DecryptMessage(ciphertext1, params);
5719 EXPECT_EQ(message, plaintext);
5720}
5721
5722/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005723 * EncryptionOperationsTest.AesEcbUnknownTag
5724 *
5725 * Verifies that AES ECB operations ignore unknown tags.
5726 */
5727TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5728 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5729 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5730 KeyParameter unknown_param;
5731 unknown_param.tag = unknown_tag;
5732
5733 vector<KeyCharacteristics> key_characteristics;
5734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5735 .Authorization(TAG_NO_AUTH_REQUIRED)
5736 .AesEncryptionKey(128)
5737 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5738 .Padding(PaddingMode::NONE)
5739 .Authorization(unknown_param),
5740 &key_blob_, &key_characteristics));
5741 ASSERT_GT(key_blob_.size(), 0U);
5742
5743 // Unknown tags should not be returned in key characteristics.
5744 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5745 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5746 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5747 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5748
5749 // Encrypt without mentioning the unknown parameter.
5750 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5751 string message = "12345678901234567890123456789012";
5752 string ciphertext = EncryptMessage(message, params);
5753 EXPECT_EQ(message.size(), ciphertext.size());
5754
5755 // Decrypt including the unknown parameter.
5756 auto decrypt_params = AuthorizationSetBuilder()
5757 .BlockMode(BlockMode::ECB)
5758 .Padding(PaddingMode::NONE)
5759 .Authorization(unknown_param);
5760 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5761 EXPECT_EQ(message, plaintext);
5762}
5763
5764/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005765 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005766 *
5767 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5768 */
5769TEST_P(EncryptionOperationsTest, AesWrongMode) {
5770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5771 .Authorization(TAG_NO_AUTH_REQUIRED)
5772 .AesEncryptionKey(128)
5773 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5774 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005775 ASSERT_GT(key_blob_.size(), 0U);
5776
Selene Huang31ab4042020-04-29 04:22:39 -07005777 EXPECT_EQ(
5778 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5779 Begin(KeyPurpose::ENCRYPT,
5780 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5781}
5782
5783/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005784 * EncryptionOperationsTest.AesWrongPadding
5785 *
5786 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5787 */
5788TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5790 .Authorization(TAG_NO_AUTH_REQUIRED)
5791 .AesEncryptionKey(128)
5792 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5793 .Padding(PaddingMode::NONE)));
5794 ASSERT_GT(key_blob_.size(), 0U);
5795
5796 EXPECT_EQ(
5797 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5798 Begin(KeyPurpose::ENCRYPT,
5799 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5800}
5801
5802/*
5803 * EncryptionOperationsTest.AesInvalidParams
5804 *
5805 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5806 */
5807TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5808 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5809 .Authorization(TAG_NO_AUTH_REQUIRED)
5810 .AesEncryptionKey(128)
5811 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5812 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5813 .Padding(PaddingMode::NONE)
5814 .Padding(PaddingMode::PKCS7)));
5815 ASSERT_GT(key_blob_.size(), 0U);
5816
5817 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5818 .BlockMode(BlockMode::CBC)
5819 .BlockMode(BlockMode::ECB)
5820 .Padding(PaddingMode::NONE));
5821 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5822 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5823
5824 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5825 .BlockMode(BlockMode::ECB)
5826 .Padding(PaddingMode::NONE)
5827 .Padding(PaddingMode::PKCS7));
5828 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5829 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5830}
5831
5832/*
Selene Huang31ab4042020-04-29 04:22:39 -07005833 * EncryptionOperationsTest.AesWrongPurpose
5834 *
5835 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5836 * specified.
5837 */
5838TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5839 auto err = GenerateKey(AuthorizationSetBuilder()
5840 .Authorization(TAG_NO_AUTH_REQUIRED)
5841 .AesKey(128)
5842 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5843 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5844 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5845 .Padding(PaddingMode::NONE));
5846 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5847 ASSERT_GT(key_blob_.size(), 0U);
5848
5849 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5850 .BlockMode(BlockMode::GCM)
5851 .Padding(PaddingMode::NONE)
5852 .Authorization(TAG_MAC_LENGTH, 128));
5853 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5854
5855 CheckedDeleteKey();
5856
5857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5858 .Authorization(TAG_NO_AUTH_REQUIRED)
5859 .AesKey(128)
5860 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5861 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5862 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5863 .Padding(PaddingMode::NONE)));
5864
5865 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5866 .BlockMode(BlockMode::GCM)
5867 .Padding(PaddingMode::NONE)
5868 .Authorization(TAG_MAC_LENGTH, 128));
5869 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5870}
5871
5872/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005873 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005874 *
5875 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5876 * multiple of the block size and no padding is specified.
5877 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005878TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5879 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005880 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005881 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5882 .Authorization(TAG_NO_AUTH_REQUIRED)
5883 .AesEncryptionKey(128)
5884 .Authorization(TAG_BLOCK_MODE, blockMode)
5885 .Padding(PaddingMode::NONE)));
5886 // Message is slightly shorter than two blocks.
5887 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005888
David Drysdaled2cc8c22021-04-15 13:29:45 +01005889 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5890 AuthorizationSet out_params;
5891 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5892 string ciphertext;
5893 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5894 EXPECT_EQ(0U, ciphertext.size());
5895
5896 CheckedDeleteKey();
5897 }
Selene Huang31ab4042020-04-29 04:22:39 -07005898}
5899
5900/*
5901 * EncryptionOperationsTest.AesEcbPkcs7Padding
5902 *
5903 * Verifies that AES PKCS7 padding works for any message length.
5904 */
5905TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5907 .Authorization(TAG_NO_AUTH_REQUIRED)
5908 .AesEncryptionKey(128)
5909 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5910 .Padding(PaddingMode::PKCS7)));
5911
5912 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5913
5914 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005915 for (size_t i = 0; i <= 48; i++) {
5916 SCOPED_TRACE(testing::Message() << "i = " << i);
5917 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5918 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005919 string ciphertext = EncryptMessage(message, params);
5920 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5921 string plaintext = DecryptMessage(ciphertext, params);
5922 EXPECT_EQ(message, plaintext);
5923 }
5924}
5925
5926/*
5927 * EncryptionOperationsTest.AesEcbWrongPadding
5928 *
5929 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5930 * specified.
5931 */
5932TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5934 .Authorization(TAG_NO_AUTH_REQUIRED)
5935 .AesEncryptionKey(128)
5936 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5937 .Padding(PaddingMode::NONE)));
5938
5939 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5940
5941 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005942 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005943 string message(i, 'a');
5944 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5945 }
5946}
5947
5948/*
5949 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5950 *
5951 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5952 */
5953TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5955 .Authorization(TAG_NO_AUTH_REQUIRED)
5956 .AesEncryptionKey(128)
5957 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5958 .Padding(PaddingMode::PKCS7)));
5959
5960 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5961
5962 string message = "a";
5963 string ciphertext = EncryptMessage(message, params);
5964 EXPECT_EQ(16U, ciphertext.size());
5965 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005966
Seth Moore7a55ae32021-06-23 14:28:11 -07005967 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5968 ++ciphertext[ciphertext.size() / 2];
5969
5970 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5971 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005972 ErrorCode error = Finish(ciphertext, &plaintext);
5973 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005974 // This is the expected error, we can exit the test now.
5975 return;
5976 } else {
5977 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005978 ASSERT_EQ(error, ErrorCode::OK)
5979 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005980 }
5981 }
5982 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005983}
5984
David Drysdaleb8093292022-04-08 12:22:35 +01005985/*
5986 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5987 *
5988 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5989 */
5990TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5991 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5992 .Authorization(TAG_NO_AUTH_REQUIRED)
5993 .AesEncryptionKey(128)
5994 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5995 .Padding(PaddingMode::PKCS7)));
5996
5997 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5998
5999 string message = "a";
6000 string ciphertext = EncryptMessage(message, params);
6001 EXPECT_EQ(16U, ciphertext.size());
6002 EXPECT_NE(ciphertext, message);
6003
6004 // Shorten the ciphertext.
6005 ciphertext.resize(ciphertext.size() - 1);
6006 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6007 string plaintext;
6008 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
6009}
6010
Selene Huang31ab4042020-04-29 04:22:39 -07006011vector<uint8_t> CopyIv(const AuthorizationSet& set) {
6012 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006013 EXPECT_TRUE(iv);
6014 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07006015}
6016
6017/*
6018 * EncryptionOperationsTest.AesCtrRoundTripSuccess
6019 *
6020 * Verifies that AES CTR mode works.
6021 */
6022TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
6023 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6024 .Authorization(TAG_NO_AUTH_REQUIRED)
6025 .AesEncryptionKey(128)
6026 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6027 .Padding(PaddingMode::NONE)));
6028
6029 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6030
6031 string message = "123";
6032 AuthorizationSet out_params;
6033 string ciphertext1 = EncryptMessage(message, params, &out_params);
6034 vector<uint8_t> iv1 = CopyIv(out_params);
6035 EXPECT_EQ(16U, iv1.size());
6036
6037 EXPECT_EQ(message.size(), ciphertext1.size());
6038
6039 out_params.Clear();
6040 string ciphertext2 = EncryptMessage(message, params, &out_params);
6041 vector<uint8_t> iv2 = CopyIv(out_params);
6042 EXPECT_EQ(16U, iv2.size());
6043
6044 // IVs should be random, so ciphertexts should differ.
6045 EXPECT_NE(ciphertext1, ciphertext2);
6046
6047 auto params_iv1 =
6048 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6049 auto params_iv2 =
6050 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6051
6052 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6053 EXPECT_EQ(message, plaintext);
6054 plaintext = DecryptMessage(ciphertext2, params_iv2);
6055 EXPECT_EQ(message, plaintext);
6056
6057 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6058 plaintext = DecryptMessage(ciphertext1, params_iv2);
6059 EXPECT_NE(message, plaintext);
6060 plaintext = DecryptMessage(ciphertext2, params_iv1);
6061 EXPECT_NE(message, plaintext);
6062}
6063
6064/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306065 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006066 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306067 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006068 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306069TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6070 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6071}
Selene Huang31ab4042020-04-29 04:22:39 -07006072
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306073/*
6074 * EncryptionOperationsTest.AesCbcIncremental
6075 *
6076 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6077 */
6078TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6079 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6080}
Selene Huang31ab4042020-04-29 04:22:39 -07006081
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306082/*
6083 * EncryptionOperationsTest.AesCtrIncremental
6084 *
6085 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6086 */
6087TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6088 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6089}
Selene Huang31ab4042020-04-29 04:22:39 -07006090
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306091/*
6092 * EncryptionOperationsTest.AesGcmIncremental
6093 *
6094 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6095 */
6096TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6097 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006098}
6099
Prashant Patildd5f7f02022-07-06 18:58:07 +00006100/*
6101 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6102 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6103 */
6104TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6105 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6106 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6107 string kat_plaintext =
6108 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6109 "809FFF37081C22EF278F896AB213A2A631");
6110 string kat_ciphertext =
6111 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6112 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6113 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6114 kat_ciphertext);
6115}
6116
6117/*
6118 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6119 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6120 */
6121TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6122 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6123 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6124 string kat_plaintext =
6125 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6126 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6127 string kat_ciphertext =
6128 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6129 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6130 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6131 kat_plaintext, kat_ciphertext);
6132}
6133
6134/*
6135 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6136 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6137 */
6138TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6139 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6140 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6141 string kat_plaintext =
6142 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6143 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6144 string kat_ciphertext =
6145 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6146 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6147 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6148 kat_ciphertext);
6149}
6150
6151/*
6152 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6153 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6154 */
6155TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6156 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6157 string kat_plaintext =
6158 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6159 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6160 string kat_ciphertext =
6161 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6162 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6163 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6164 kat_ciphertext);
6165}
6166
6167/*
6168 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6169 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6170 */
6171TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6172 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6173 string kat_plaintext =
6174 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6175 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6176 string kat_ciphertext =
6177 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6178 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6179 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6180 kat_ciphertext);
6181}
6182
6183/*
6184 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6185 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6186 */
6187TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6188 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6189 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6190 string kat_plaintext =
6191 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6192 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6193 string kat_ciphertext =
6194 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6195 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6196 "bdfcc0cba0");
6197
6198 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6199 kat_ciphertext);
6200}
6201
6202/*
6203 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6204 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6205 */
6206TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6207 if (SecLevel() == SecurityLevel::STRONGBOX) {
6208 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6209 }
6210 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6211 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6212 string kat_plaintext =
6213 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6214 "167f2497c994bd496eb80bfb2ba2c9d5af");
6215 string kat_ciphertext =
6216 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6217 "72c134552f3a138e726fbe493b3a839598");
6218 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6219 kat_ciphertext);
6220}
6221
6222/*
6223 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6224 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6225 */
6226TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6227 if (SecLevel() == SecurityLevel::STRONGBOX) {
6228 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6229 }
6230 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6231 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6232 string kat_plaintext =
6233 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6234 "b170");
6235 string kat_ciphertext =
6236 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6237 "4e3884138ff403a41fd99818708ada301c");
6238 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6239 kat_plaintext, kat_ciphertext);
6240}
6241
6242/*
6243 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6244 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6245 */
6246TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6247 if (SecLevel() == SecurityLevel::STRONGBOX) {
6248 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6249 }
6250 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6251 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6252 string kat_plaintext =
6253 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6254 "28091e09cdbbd3b42b");
6255 string kat_ciphertext =
6256 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6257 "2ae0f90f0c19f42b4a");
6258 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6259 kat_ciphertext);
6260}
6261
6262/*
6263 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6264 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6265 */
6266TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6267 if (SecLevel() == SecurityLevel::STRONGBOX) {
6268 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6269 }
6270 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6271 string kat_plaintext =
6272 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6273 "44ab");
6274 string kat_ciphertext =
6275 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6276 "2453");
6277 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6278 kat_ciphertext);
6279}
6280
6281/*
6282 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6283 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6284 */
6285TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6286 if (SecLevel() == SecurityLevel::STRONGBOX) {
6287 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6288 }
6289 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6290 string kat_plaintext =
6291 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6292 "e2c7");
6293 string kat_ciphertext =
6294 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6295 "bb7e3a889dd4a9589098b44acf1056e7aa");
6296 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6297 kat_ciphertext);
6298}
6299
6300/*
6301 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6302 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6303 */
6304TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6305 if (SecLevel() == SecurityLevel::STRONGBOX) {
6306 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6307 }
6308 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6309 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6310 string kat_plaintext =
6311 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6312 "ff52");
6313 string kat_ciphertext =
6314 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6315 "1413ad70fb0e1970669095ad77ebb5974ae8");
6316
6317 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6318 kat_ciphertext);
6319}
6320
6321/*
6322 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6323 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6324 */
6325TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6326 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6327 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6328 string kat_plaintext =
6329 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6330 "494cb53caca353e4b637ba05687be20f8d");
6331 string kat_ciphertext =
6332 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6333 "6047da1e4fd7c4e1cf2656097f75ae8685");
6334 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6335 kat_ciphertext);
6336}
6337
6338/*
6339 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6340 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6341 */
6342TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6343 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6344 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6345 string kat_plaintext =
6346 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6347 "2545a82b73c48078b9dae62261c65909");
6348 string kat_ciphertext =
6349 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6350 "9403a71987b95124073d69f2a3cb95b0ab");
6351 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6352 kat_plaintext, kat_ciphertext);
6353}
6354
6355/*
6356 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6357 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6358 */
6359TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6360 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6361 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6362 string kat_plaintext =
6363 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6364 "1f6db3c884");
6365 string kat_ciphertext =
6366 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6367 "a7be30d4c3");
6368 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6369 kat_ciphertext);
6370}
6371
6372/*
6373 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6374 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6375 */
6376TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6377 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6378 string kat_plaintext =
6379 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6380 "31a476d6806b8116089c6ec50bb543200f");
6381 string kat_ciphertext =
6382 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6383 "c83e377faf246288931136bef2a07c0be4");
6384 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6385 kat_ciphertext);
6386}
6387
6388/*
6389 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6390 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6391 */
6392TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6393 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6394 string kat_plaintext =
6395 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6396 "6f");
6397 string kat_ciphertext =
6398 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6399 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6400 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6401 kat_ciphertext);
6402}
6403
6404/*
6405 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6406 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6407 */
6408TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6409 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6410 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6411 string kat_plaintext =
6412 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6413 "f0");
6414 string kat_ciphertext =
6415 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6416 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6417
6418 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6419 kat_ciphertext);
6420}
6421
Selene Huang31ab4042020-04-29 04:22:39 -07006422struct AesCtrSp80038aTestVector {
6423 const char* key;
6424 const char* nonce;
6425 const char* plaintext;
6426 const char* ciphertext;
6427};
6428
6429// These test vectors are taken from
6430// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6431static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6432 // AES-128
6433 {
6434 "2b7e151628aed2a6abf7158809cf4f3c",
6435 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6436 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6437 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6438 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6439 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6440 },
6441 // AES-192
6442 {
6443 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6444 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6445 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6446 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6447 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6448 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6449 },
6450 // AES-256
6451 {
6452 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6453 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6454 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6455 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6456 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6457 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6458 },
6459};
6460
6461/*
6462 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6463 *
6464 * Verifies AES CTR implementation against SP800-38A test vectors.
6465 */
6466TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6467 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6468 for (size_t i = 0; i < 3; i++) {
6469 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6470 const string key = hex2str(test.key);
6471 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6472 InvalidSizes.end())
6473 continue;
6474 const string nonce = hex2str(test.nonce);
6475 const string plaintext = hex2str(test.plaintext);
6476 const string ciphertext = hex2str(test.ciphertext);
6477 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6478 }
6479}
6480
6481/*
6482 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6483 *
6484 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6485 */
6486TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6487 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6488 .Authorization(TAG_NO_AUTH_REQUIRED)
6489 .AesEncryptionKey(128)
6490 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6491 .Padding(PaddingMode::PKCS7)));
6492 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6493 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6494}
6495
6496/*
6497 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6498 *
6499 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6500 */
6501TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6502 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6503 .Authorization(TAG_NO_AUTH_REQUIRED)
6504 .AesEncryptionKey(128)
6505 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6506 .Authorization(TAG_CALLER_NONCE)
6507 .Padding(PaddingMode::NONE)));
6508
6509 auto params = AuthorizationSetBuilder()
6510 .BlockMode(BlockMode::CTR)
6511 .Padding(PaddingMode::NONE)
6512 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6513 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6514
6515 params = AuthorizationSetBuilder()
6516 .BlockMode(BlockMode::CTR)
6517 .Padding(PaddingMode::NONE)
6518 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6519 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6520
6521 params = AuthorizationSetBuilder()
6522 .BlockMode(BlockMode::CTR)
6523 .Padding(PaddingMode::NONE)
6524 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6525 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6526}
6527
6528/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006529 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006530 *
6531 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6532 */
6533TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6534 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6535 .Authorization(TAG_NO_AUTH_REQUIRED)
6536 .AesEncryptionKey(128)
6537 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6538 .Padding(PaddingMode::NONE)));
6539 // Two-block message.
6540 string message = "12345678901234567890123456789012";
6541 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6542 AuthorizationSet out_params;
6543 string ciphertext1 = EncryptMessage(message, params, &out_params);
6544 vector<uint8_t> iv1 = CopyIv(out_params);
6545 EXPECT_EQ(message.size(), ciphertext1.size());
6546
6547 out_params.Clear();
6548
6549 string ciphertext2 = EncryptMessage(message, params, &out_params);
6550 vector<uint8_t> iv2 = CopyIv(out_params);
6551 EXPECT_EQ(message.size(), ciphertext2.size());
6552
6553 // IVs should be random, so ciphertexts should differ.
6554 EXPECT_NE(ciphertext1, ciphertext2);
6555
6556 params.push_back(TAG_NONCE, iv1);
6557 string plaintext = DecryptMessage(ciphertext1, params);
6558 EXPECT_EQ(message, plaintext);
6559}
6560
6561/*
Tommy Chiuee705692021-09-23 20:09:13 +08006562 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6563 *
6564 * Verifies that keymaster generates correct output on zero-input with
6565 * NonePadding mode
6566 */
6567TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6569 .Authorization(TAG_NO_AUTH_REQUIRED)
6570 .AesEncryptionKey(128)
6571 .BlockMode(BlockMode::CBC)
6572 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6573
6574 // Zero input message
6575 string message = "";
6576 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006577 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006578 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6579 AuthorizationSet out_params;
6580 string ciphertext1 = EncryptMessage(message, params, &out_params);
6581 vector<uint8_t> iv1 = CopyIv(out_params);
6582 if (padding == PaddingMode::NONE)
6583 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6584 else
6585 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6586
6587 out_params.Clear();
6588
6589 string ciphertext2 = EncryptMessage(message, params, &out_params);
6590 vector<uint8_t> iv2 = CopyIv(out_params);
6591 if (padding == PaddingMode::NONE)
6592 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6593 else
6594 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6595
6596 // IVs should be random
6597 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6598
6599 params.push_back(TAG_NONCE, iv1);
6600 string plaintext = DecryptMessage(ciphertext1, params);
6601 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6602 }
6603}
6604
6605/*
Selene Huang31ab4042020-04-29 04:22:39 -07006606 * EncryptionOperationsTest.AesCallerNonce
6607 *
6608 * Verifies that AES caller-provided nonces work correctly.
6609 */
6610TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6612 .Authorization(TAG_NO_AUTH_REQUIRED)
6613 .AesEncryptionKey(128)
6614 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6615 .Authorization(TAG_CALLER_NONCE)
6616 .Padding(PaddingMode::NONE)));
6617
6618 string message = "12345678901234567890123456789012";
6619
6620 // Don't specify nonce, should get a random one.
6621 AuthorizationSetBuilder params =
6622 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6623 AuthorizationSet out_params;
6624 string ciphertext = EncryptMessage(message, params, &out_params);
6625 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006626 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006627
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006628 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006629 string plaintext = DecryptMessage(ciphertext, params);
6630 EXPECT_EQ(message, plaintext);
6631
6632 // Now specify a nonce, should also work.
6633 params = AuthorizationSetBuilder()
6634 .BlockMode(BlockMode::CBC)
6635 .Padding(PaddingMode::NONE)
6636 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6637 out_params.Clear();
6638 ciphertext = EncryptMessage(message, params, &out_params);
6639
6640 // Decrypt with correct nonce.
6641 plaintext = DecryptMessage(ciphertext, params);
6642 EXPECT_EQ(message, plaintext);
6643
6644 // Try with wrong nonce.
6645 params = AuthorizationSetBuilder()
6646 .BlockMode(BlockMode::CBC)
6647 .Padding(PaddingMode::NONE)
6648 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6649 plaintext = DecryptMessage(ciphertext, params);
6650 EXPECT_NE(message, plaintext);
6651}
6652
6653/*
6654 * EncryptionOperationsTest.AesCallerNonceProhibited
6655 *
6656 * Verifies that caller-provided nonces are not permitted when not specified in the key
6657 * authorizations.
6658 */
6659TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6660 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6661 .Authorization(TAG_NO_AUTH_REQUIRED)
6662 .AesEncryptionKey(128)
6663 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6664 .Padding(PaddingMode::NONE)));
6665
6666 string message = "12345678901234567890123456789012";
6667
6668 // Don't specify nonce, should get a random one.
6669 AuthorizationSetBuilder params =
6670 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6671 AuthorizationSet out_params;
6672 string ciphertext = EncryptMessage(message, params, &out_params);
6673 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006674 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006675
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006676 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006677 string plaintext = DecryptMessage(ciphertext, params);
6678 EXPECT_EQ(message, plaintext);
6679
6680 // Now specify a nonce, should fail
6681 params = AuthorizationSetBuilder()
6682 .BlockMode(BlockMode::CBC)
6683 .Padding(PaddingMode::NONE)
6684 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6685 out_params.Clear();
6686 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6687}
6688
6689/*
6690 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6691 *
6692 * Verifies that AES GCM mode works.
6693 */
6694TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6695 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6696 .Authorization(TAG_NO_AUTH_REQUIRED)
6697 .AesEncryptionKey(128)
6698 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6699 .Padding(PaddingMode::NONE)
6700 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6701
6702 string aad = "foobar";
6703 string message = "123456789012345678901234567890123456";
6704
6705 auto begin_params = AuthorizationSetBuilder()
6706 .BlockMode(BlockMode::GCM)
6707 .Padding(PaddingMode::NONE)
6708 .Authorization(TAG_MAC_LENGTH, 128);
6709
Selene Huang31ab4042020-04-29 04:22:39 -07006710 // Encrypt
6711 AuthorizationSet begin_out_params;
6712 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6713 << "Begin encrypt";
6714 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006715 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6716 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006717 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6718
6719 // Grab nonce
6720 begin_params.push_back(begin_out_params);
6721
6722 // Decrypt.
6723 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006724 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006725 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006726 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006727 EXPECT_EQ(message.length(), plaintext.length());
6728 EXPECT_EQ(message, plaintext);
6729}
6730
6731/*
6732 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6733 *
6734 * Verifies that AES GCM mode works, even when there's a long delay
6735 * between operations.
6736 */
6737TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6739 .Authorization(TAG_NO_AUTH_REQUIRED)
6740 .AesEncryptionKey(128)
6741 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6742 .Padding(PaddingMode::NONE)
6743 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6744
6745 string aad = "foobar";
6746 string message = "123456789012345678901234567890123456";
6747
6748 auto begin_params = AuthorizationSetBuilder()
6749 .BlockMode(BlockMode::GCM)
6750 .Padding(PaddingMode::NONE)
6751 .Authorization(TAG_MAC_LENGTH, 128);
6752
Selene Huang31ab4042020-04-29 04:22:39 -07006753 // Encrypt
6754 AuthorizationSet begin_out_params;
6755 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6756 << "Begin encrypt";
6757 string ciphertext;
6758 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006759 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006760 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006761 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006762
6763 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6764
6765 // Grab nonce
6766 begin_params.push_back(begin_out_params);
6767
6768 // Decrypt.
6769 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6770 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006771 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006772 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006773 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006774 sleep(5);
6775 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6776 EXPECT_EQ(message.length(), plaintext.length());
6777 EXPECT_EQ(message, plaintext);
6778}
6779
6780/*
6781 * EncryptionOperationsTest.AesGcmDifferentNonces
6782 *
6783 * Verifies that encrypting the same data with different nonces produces different outputs.
6784 */
6785TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6787 .Authorization(TAG_NO_AUTH_REQUIRED)
6788 .AesEncryptionKey(128)
6789 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6790 .Padding(PaddingMode::NONE)
6791 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6792 .Authorization(TAG_CALLER_NONCE)));
6793
6794 string aad = "foobar";
6795 string message = "123456789012345678901234567890123456";
6796 string nonce1 = "000000000000";
6797 string nonce2 = "111111111111";
6798 string nonce3 = "222222222222";
6799
6800 string ciphertext1 =
6801 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6802 string ciphertext2 =
6803 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6804 string ciphertext3 =
6805 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6806
6807 ASSERT_NE(ciphertext1, ciphertext2);
6808 ASSERT_NE(ciphertext1, ciphertext3);
6809 ASSERT_NE(ciphertext2, ciphertext3);
6810}
6811
6812/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006813 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6814 *
6815 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6816 */
6817TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6819 .Authorization(TAG_NO_AUTH_REQUIRED)
6820 .AesEncryptionKey(128)
6821 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6822 .Padding(PaddingMode::NONE)
6823 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6824
6825 string aad = "foobar";
6826 string message = "123456789012345678901234567890123456";
6827
6828 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6829 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6830 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6831
6832 ASSERT_NE(ciphertext1, ciphertext2);
6833 ASSERT_NE(ciphertext1, ciphertext3);
6834 ASSERT_NE(ciphertext2, ciphertext3);
6835}
6836
6837/*
Selene Huang31ab4042020-04-29 04:22:39 -07006838 * EncryptionOperationsTest.AesGcmTooShortTag
6839 *
6840 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6841 */
6842TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6844 .Authorization(TAG_NO_AUTH_REQUIRED)
6845 .AesEncryptionKey(128)
6846 .BlockMode(BlockMode::GCM)
6847 .Padding(PaddingMode::NONE)
6848 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6849 string message = "123456789012345678901234567890123456";
6850 auto params = AuthorizationSetBuilder()
6851 .BlockMode(BlockMode::GCM)
6852 .Padding(PaddingMode::NONE)
6853 .Authorization(TAG_MAC_LENGTH, 96);
6854
6855 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6856}
6857
6858/*
6859 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6860 *
6861 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6862 */
6863TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6865 .Authorization(TAG_NO_AUTH_REQUIRED)
6866 .AesEncryptionKey(128)
6867 .BlockMode(BlockMode::GCM)
6868 .Padding(PaddingMode::NONE)
6869 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6870 string aad = "foobar";
6871 string message = "123456789012345678901234567890123456";
6872 auto params = AuthorizationSetBuilder()
6873 .BlockMode(BlockMode::GCM)
6874 .Padding(PaddingMode::NONE)
6875 .Authorization(TAG_MAC_LENGTH, 128);
6876
Selene Huang31ab4042020-04-29 04:22:39 -07006877 // Encrypt
6878 AuthorizationSet begin_out_params;
6879 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6880 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006881 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006882
6883 AuthorizationSet finish_out_params;
6884 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006885 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6886 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006887
6888 params = AuthorizationSetBuilder()
6889 .Authorizations(begin_out_params)
6890 .BlockMode(BlockMode::GCM)
6891 .Padding(PaddingMode::NONE)
6892 .Authorization(TAG_MAC_LENGTH, 96);
6893
6894 // Decrypt.
6895 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6896}
6897
6898/*
6899 * EncryptionOperationsTest.AesGcmCorruptKey
6900 *
6901 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6902 */
6903TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6904 const uint8_t nonce_bytes[] = {
6905 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6906 };
6907 string nonce = make_string(nonce_bytes);
6908 const uint8_t ciphertext_bytes[] = {
6909 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6910 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6911 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6912 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6913 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6914 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6915 };
6916 string ciphertext = make_string(ciphertext_bytes);
6917
6918 auto params = AuthorizationSetBuilder()
6919 .BlockMode(BlockMode::GCM)
6920 .Padding(PaddingMode::NONE)
6921 .Authorization(TAG_MAC_LENGTH, 128)
6922 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6923
6924 auto import_params = AuthorizationSetBuilder()
6925 .Authorization(TAG_NO_AUTH_REQUIRED)
6926 .AesEncryptionKey(128)
6927 .BlockMode(BlockMode::GCM)
6928 .Padding(PaddingMode::NONE)
6929 .Authorization(TAG_CALLER_NONCE)
6930 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6931
6932 // Import correct key and decrypt
6933 const uint8_t key_bytes[] = {
6934 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6935 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6936 };
6937 string key = make_string(key_bytes);
6938 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6939 string plaintext = DecryptMessage(ciphertext, params);
6940 CheckedDeleteKey();
6941
6942 // Corrupt key and attempt to decrypt
6943 key[0] = 0;
6944 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6945 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6946 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6947 CheckedDeleteKey();
6948}
6949
6950/*
6951 * EncryptionOperationsTest.AesGcmAadNoData
6952 *
6953 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6954 * encrypt.
6955 */
6956TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6957 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6958 .Authorization(TAG_NO_AUTH_REQUIRED)
6959 .AesEncryptionKey(128)
6960 .BlockMode(BlockMode::GCM)
6961 .Padding(PaddingMode::NONE)
6962 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6963
6964 string aad = "1234567890123456";
6965 auto params = AuthorizationSetBuilder()
6966 .BlockMode(BlockMode::GCM)
6967 .Padding(PaddingMode::NONE)
6968 .Authorization(TAG_MAC_LENGTH, 128);
6969
Selene Huang31ab4042020-04-29 04:22:39 -07006970 // Encrypt
6971 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006972 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006973 string ciphertext;
6974 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006975 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6976 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006977 EXPECT_TRUE(finish_out_params.empty());
6978
6979 // Grab nonce
6980 params.push_back(begin_out_params);
6981
6982 // Decrypt.
6983 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006984 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006985 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006986 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006987
6988 EXPECT_TRUE(finish_out_params.empty());
6989
6990 EXPECT_EQ("", plaintext);
6991}
6992
6993/*
6994 * EncryptionOperationsTest.AesGcmMultiPartAad
6995 *
6996 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6997 * chunks.
6998 */
6999TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
7000 const size_t tag_bits = 128;
7001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7002 .Authorization(TAG_NO_AUTH_REQUIRED)
7003 .AesEncryptionKey(128)
7004 .BlockMode(BlockMode::GCM)
7005 .Padding(PaddingMode::NONE)
7006 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7007
7008 string message = "123456789012345678901234567890123456";
7009 auto begin_params = AuthorizationSetBuilder()
7010 .BlockMode(BlockMode::GCM)
7011 .Padding(PaddingMode::NONE)
7012 .Authorization(TAG_MAC_LENGTH, tag_bits);
7013 AuthorizationSet begin_out_params;
7014
David Drysdale7fc26b92022-05-13 09:54:24 +01007015 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007016
7017 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07007018 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
7019 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007020 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007021 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7022 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007023
Selene Huang31ab4042020-04-29 04:22:39 -07007024 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07007025 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07007026
7027 // Grab nonce.
7028 begin_params.push_back(begin_out_params);
7029
7030 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01007031 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007032 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007033 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007034 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007035 EXPECT_EQ(message, plaintext);
7036}
7037
7038/*
7039 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7040 *
7041 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7042 */
7043TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7044 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7045 .Authorization(TAG_NO_AUTH_REQUIRED)
7046 .AesEncryptionKey(128)
7047 .BlockMode(BlockMode::GCM)
7048 .Padding(PaddingMode::NONE)
7049 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7050
7051 string message = "123456789012345678901234567890123456";
7052 auto begin_params = AuthorizationSetBuilder()
7053 .BlockMode(BlockMode::GCM)
7054 .Padding(PaddingMode::NONE)
7055 .Authorization(TAG_MAC_LENGTH, 128);
7056 AuthorizationSet begin_out_params;
7057
David Drysdale7fc26b92022-05-13 09:54:24 +01007058 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007059
Shawn Willden92d79c02021-02-19 07:31:55 -07007060 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007061 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007062 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7063 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007064
David Drysdaled2cc8c22021-04-15 13:29:45 +01007065 // The failure should have already cancelled the operation.
7066 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7067
Shawn Willden92d79c02021-02-19 07:31:55 -07007068 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007069}
7070
7071/*
7072 * EncryptionOperationsTest.AesGcmBadAad
7073 *
7074 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7075 */
7076TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7078 .Authorization(TAG_NO_AUTH_REQUIRED)
7079 .AesEncryptionKey(128)
7080 .BlockMode(BlockMode::GCM)
7081 .Padding(PaddingMode::NONE)
7082 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7083
7084 string message = "12345678901234567890123456789012";
7085 auto begin_params = AuthorizationSetBuilder()
7086 .BlockMode(BlockMode::GCM)
7087 .Padding(PaddingMode::NONE)
7088 .Authorization(TAG_MAC_LENGTH, 128);
7089
Selene Huang31ab4042020-04-29 04:22:39 -07007090 // Encrypt
7091 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007092 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007093 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007094 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007095 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007096
7097 // Grab nonce
7098 begin_params.push_back(begin_out_params);
7099
Selene Huang31ab4042020-04-29 04:22:39 -07007100 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007101 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007102 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007103 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007104 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007105}
7106
7107/*
7108 * EncryptionOperationsTest.AesGcmWrongNonce
7109 *
7110 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7111 */
7112TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7114 .Authorization(TAG_NO_AUTH_REQUIRED)
7115 .AesEncryptionKey(128)
7116 .BlockMode(BlockMode::GCM)
7117 .Padding(PaddingMode::NONE)
7118 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7119
7120 string message = "12345678901234567890123456789012";
7121 auto begin_params = AuthorizationSetBuilder()
7122 .BlockMode(BlockMode::GCM)
7123 .Padding(PaddingMode::NONE)
7124 .Authorization(TAG_MAC_LENGTH, 128);
7125
Selene Huang31ab4042020-04-29 04:22:39 -07007126 // Encrypt
7127 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007128 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007129 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007130 string ciphertext;
7131 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007132 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007133
7134 // Wrong nonce
7135 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7136
7137 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007138 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007139 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007140 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007141 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007142
7143 // With wrong nonce, should have gotten garbage plaintext (or none).
7144 EXPECT_NE(message, plaintext);
7145}
7146
7147/*
7148 * EncryptionOperationsTest.AesGcmCorruptTag
7149 *
7150 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7151 */
7152TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7154 .Authorization(TAG_NO_AUTH_REQUIRED)
7155 .AesEncryptionKey(128)
7156 .BlockMode(BlockMode::GCM)
7157 .Padding(PaddingMode::NONE)
7158 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7159
7160 string aad = "1234567890123456";
7161 string message = "123456789012345678901234567890123456";
7162
7163 auto params = AuthorizationSetBuilder()
7164 .BlockMode(BlockMode::GCM)
7165 .Padding(PaddingMode::NONE)
7166 .Authorization(TAG_MAC_LENGTH, 128);
7167
Selene Huang31ab4042020-04-29 04:22:39 -07007168 // Encrypt
7169 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007170 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007171 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007172 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007173 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007174
7175 // Corrupt tag
7176 ++(*ciphertext.rbegin());
7177
7178 // Grab nonce
7179 params.push_back(begin_out_params);
7180
7181 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007182 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007183 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007184 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007185 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007186}
7187
7188/*
7189 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7190 *
7191 * Verifies that 3DES is basically functional.
7192 */
7193TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7194 auto auths = AuthorizationSetBuilder()
7195 .TripleDesEncryptionKey(168)
7196 .BlockMode(BlockMode::ECB)
7197 .Authorization(TAG_NO_AUTH_REQUIRED)
7198 .Padding(PaddingMode::NONE);
7199
7200 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7201 // Two-block message.
7202 string message = "1234567890123456";
7203 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7204 string ciphertext1 = EncryptMessage(message, inParams);
7205 EXPECT_EQ(message.size(), ciphertext1.size());
7206
7207 string ciphertext2 = EncryptMessage(string(message), inParams);
7208 EXPECT_EQ(message.size(), ciphertext2.size());
7209
7210 // ECB is deterministic.
7211 EXPECT_EQ(ciphertext1, ciphertext2);
7212
7213 string plaintext = DecryptMessage(ciphertext1, inParams);
7214 EXPECT_EQ(message, plaintext);
7215}
7216
7217/*
7218 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7219 *
7220 * Verifies that CBC keys reject ECB usage.
7221 */
7222TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7224 .TripleDesEncryptionKey(168)
7225 .BlockMode(BlockMode::CBC)
7226 .Authorization(TAG_NO_AUTH_REQUIRED)
7227 .Padding(PaddingMode::NONE)));
7228
7229 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7230 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7231}
7232
7233/*
7234 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7235 *
7236 * Tests ECB mode with PKCS#7 padding, various message sizes.
7237 */
7238TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7239 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7240 .TripleDesEncryptionKey(168)
7241 .BlockMode(BlockMode::ECB)
7242 .Authorization(TAG_NO_AUTH_REQUIRED)
7243 .Padding(PaddingMode::PKCS7)));
7244
7245 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007246 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007247 string message(i, 'a');
7248 auto inParams =
7249 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7250 string ciphertext = EncryptMessage(message, inParams);
7251 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7252 string plaintext = DecryptMessage(ciphertext, inParams);
7253 EXPECT_EQ(message, plaintext);
7254 }
7255}
7256
7257/*
7258 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7259 *
7260 * Verifies that keys configured for no padding reject PKCS7 padding
7261 */
7262TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7263 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7264 .TripleDesEncryptionKey(168)
7265 .BlockMode(BlockMode::ECB)
7266 .Authorization(TAG_NO_AUTH_REQUIRED)
7267 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007268 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7269 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007270}
7271
7272/*
7273 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7274 *
7275 * Verifies that corrupted padding is detected.
7276 */
7277TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7278 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7279 .TripleDesEncryptionKey(168)
7280 .BlockMode(BlockMode::ECB)
7281 .Authorization(TAG_NO_AUTH_REQUIRED)
7282 .Padding(PaddingMode::PKCS7)));
7283
7284 string message = "a";
7285 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7286 EXPECT_EQ(8U, ciphertext.size());
7287 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007288
7289 AuthorizationSetBuilder begin_params;
7290 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7291 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007292
7293 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7294 ++ciphertext[ciphertext.size() / 2];
7295
David Drysdale7fc26b92022-05-13 09:54:24 +01007296 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007297 string plaintext;
7298 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7299 ErrorCode error = Finish(&plaintext);
7300 if (error == ErrorCode::INVALID_ARGUMENT) {
7301 // This is the expected error, we can exit the test now.
7302 return;
7303 } else {
7304 // Very small chance we got valid decryption, so try again.
7305 ASSERT_EQ(error, ErrorCode::OK);
7306 }
7307 }
7308 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007309}
7310
7311struct TripleDesTestVector {
7312 const char* name;
7313 const KeyPurpose purpose;
7314 const BlockMode block_mode;
7315 const PaddingMode padding_mode;
7316 const char* key;
7317 const char* iv;
7318 const char* input;
7319 const char* output;
7320};
7321
7322// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7323// of the NIST vectors are multiples of the block size.
7324static const TripleDesTestVector kTripleDesTestVectors[] = {
7325 {
7326 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7327 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7328 "", // IV
7329 "329d86bdf1bc5af4", // input
7330 "d946c2756d78633f", // output
7331 },
7332 {
7333 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7334 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7335 "", // IV
7336 "6b1540781b01ce1997adae102dbf3c5b", // input
7337 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7338 },
7339 {
7340 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7341 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7342 "", // IV
7343 "6daad94ce08acfe7", // input
7344 "660e7d32dcc90e79", // output
7345 },
7346 {
7347 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7348 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7349 "", // IV
7350 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7351 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7352 },
7353 {
7354 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7355 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7356 "43f791134c5647ba", // IV
7357 "dcc153cef81d6f24", // input
7358 "92538bd8af18d3ba", // output
7359 },
7360 {
7361 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7362 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7363 "c2e999cb6249023c", // IV
7364 "c689aee38a301bb316da75db36f110b5", // input
7365 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7366 },
7367 {
7368 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7369 PaddingMode::PKCS7,
7370 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7371 "c2e999cb6249023c", // IV
7372 "c689aee38a301bb316da75db36f110b500", // input
7373 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7374 },
7375 {
7376 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7377 PaddingMode::PKCS7,
7378 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7379 "c2e999cb6249023c", // IV
7380 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7381 "c689aee38a301bb316da75db36f110b500", // output
7382 },
7383 {
7384 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7385 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7386 "41746c7e442d3681", // IV
7387 "c53a7b0ec40600fe", // input
7388 "d4f00eb455de1034", // output
7389 },
7390 {
7391 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7392 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7393 "3982bc02c3727d45", // IV
7394 "6006f10adef52991fcc777a1238bbb65", // input
7395 "edae09288e9e3bc05746d872b48e3b29", // output
7396 },
7397};
7398
7399/*
7400 * EncryptionOperationsTest.TripleDesTestVector
7401 *
7402 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7403 */
7404TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7405 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7406 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7407 SCOPED_TRACE(test->name);
7408 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7409 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7410 hex2str(test->output));
7411 }
7412}
7413
7414/*
7415 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7416 *
7417 * Validates CBC mode functionality.
7418 */
7419TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7421 .TripleDesEncryptionKey(168)
7422 .BlockMode(BlockMode::CBC)
7423 .Authorization(TAG_NO_AUTH_REQUIRED)
7424 .Padding(PaddingMode::NONE)));
7425
7426 ASSERT_GT(key_blob_.size(), 0U);
7427
Brian J Murray734c8412022-01-13 14:55:30 -08007428 // Four-block message.
7429 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007430 vector<uint8_t> iv1;
7431 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7432 EXPECT_EQ(message.size(), ciphertext1.size());
7433
7434 vector<uint8_t> iv2;
7435 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7436 EXPECT_EQ(message.size(), ciphertext2.size());
7437
7438 // IVs should be random, so ciphertexts should differ.
7439 EXPECT_NE(iv1, iv2);
7440 EXPECT_NE(ciphertext1, ciphertext2);
7441
7442 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7443 EXPECT_EQ(message, plaintext);
7444}
7445
7446/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007447 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7448 *
7449 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7450 */
7451TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7452 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7453 .TripleDesEncryptionKey(168)
7454 .BlockMode(BlockMode::CBC)
7455 .Authorization(TAG_NO_AUTH_REQUIRED)
7456 .Authorization(TAG_CALLER_NONCE)
7457 .Padding(PaddingMode::NONE)));
7458 auto params = AuthorizationSetBuilder()
7459 .BlockMode(BlockMode::CBC)
7460 .Padding(PaddingMode::NONE)
7461 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7462 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7463}
7464
7465/*
Selene Huang31ab4042020-04-29 04:22:39 -07007466 * EncryptionOperationsTest.TripleDesCallerIv
7467 *
7468 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7469 */
7470TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7471 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7472 .TripleDesEncryptionKey(168)
7473 .BlockMode(BlockMode::CBC)
7474 .Authorization(TAG_NO_AUTH_REQUIRED)
7475 .Authorization(TAG_CALLER_NONCE)
7476 .Padding(PaddingMode::NONE)));
7477 string message = "1234567890123456";
7478 vector<uint8_t> iv;
7479 // Don't specify IV, should get a random one.
7480 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7481 EXPECT_EQ(message.size(), ciphertext1.size());
7482 EXPECT_EQ(8U, iv.size());
7483
7484 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7485 EXPECT_EQ(message, plaintext);
7486
7487 // Now specify an IV, should also work.
7488 iv = AidlBuf("abcdefgh");
7489 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7490
7491 // Decrypt with correct IV.
7492 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7493 EXPECT_EQ(message, plaintext);
7494
7495 // Now try with wrong IV.
7496 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7497 EXPECT_NE(message, plaintext);
7498}
7499
7500/*
7501 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7502 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007503 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007504 */
7505TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7507 .TripleDesEncryptionKey(168)
7508 .BlockMode(BlockMode::CBC)
7509 .Authorization(TAG_NO_AUTH_REQUIRED)
7510 .Padding(PaddingMode::NONE)));
7511
7512 string message = "12345678901234567890123456789012";
7513 vector<uint8_t> iv;
7514 // Don't specify nonce, should get a random one.
7515 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7516 EXPECT_EQ(message.size(), ciphertext1.size());
7517 EXPECT_EQ(8U, iv.size());
7518
7519 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7520 EXPECT_EQ(message, plaintext);
7521
7522 // Now specify a nonce, should fail.
7523 auto input_params = AuthorizationSetBuilder()
7524 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7525 .BlockMode(BlockMode::CBC)
7526 .Padding(PaddingMode::NONE);
7527 AuthorizationSet output_params;
7528 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7529 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7530}
7531
7532/*
7533 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7534 *
7535 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7536 */
7537TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7539 .TripleDesEncryptionKey(168)
7540 .BlockMode(BlockMode::ECB)
7541 .Authorization(TAG_NO_AUTH_REQUIRED)
7542 .Padding(PaddingMode::NONE)));
7543 // Two-block message.
7544 string message = "1234567890123456";
7545 auto begin_params =
7546 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7547 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7548}
7549
7550/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007551 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007552 *
7553 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7554 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007555TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7556 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007557 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007558 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7559 .TripleDesEncryptionKey(168)
7560 .BlockMode(blockMode)
7561 .Authorization(TAG_NO_AUTH_REQUIRED)
7562 .Padding(PaddingMode::NONE)));
7563 // Message is slightly shorter than two blocks.
7564 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007565
David Drysdaled2cc8c22021-04-15 13:29:45 +01007566 auto begin_params =
7567 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7568 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007569 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007570 string ciphertext;
7571 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7572
7573 CheckedDeleteKey();
7574 }
Selene Huang31ab4042020-04-29 04:22:39 -07007575}
7576
7577/*
7578 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7579 *
7580 * Verifies that PKCS7 padding works correctly in CBC mode.
7581 */
7582TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7583 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7584 .TripleDesEncryptionKey(168)
7585 .BlockMode(BlockMode::CBC)
7586 .Authorization(TAG_NO_AUTH_REQUIRED)
7587 .Padding(PaddingMode::PKCS7)));
7588
7589 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007590 for (size_t i = 0; i <= 32; i++) {
7591 SCOPED_TRACE(testing::Message() << "i = " << i);
7592 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7593 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007594 vector<uint8_t> iv;
7595 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7596 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7597 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7598 EXPECT_EQ(message, plaintext);
7599 }
7600}
7601
7602/*
7603 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7604 *
7605 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7606 */
7607TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7609 .TripleDesEncryptionKey(168)
7610 .BlockMode(BlockMode::CBC)
7611 .Authorization(TAG_NO_AUTH_REQUIRED)
7612 .Padding(PaddingMode::NONE)));
7613
7614 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007615 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007616 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007617 auto begin_params =
7618 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7619 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7620 }
7621}
7622
7623/*
7624 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7625 *
7626 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7627 */
7628TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7630 .TripleDesEncryptionKey(168)
7631 .BlockMode(BlockMode::CBC)
7632 .Authorization(TAG_NO_AUTH_REQUIRED)
7633 .Padding(PaddingMode::PKCS7)));
7634
7635 string message = "a";
7636 vector<uint8_t> iv;
7637 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7638 EXPECT_EQ(8U, ciphertext.size());
7639 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007640
7641 auto begin_params = AuthorizationSetBuilder()
7642 .BlockMode(BlockMode::CBC)
7643 .Padding(PaddingMode::PKCS7)
7644 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007645
7646 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007647 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007648 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007649 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007650 string plaintext;
7651 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7652 ErrorCode error = Finish(&plaintext);
7653 if (error == ErrorCode::INVALID_ARGUMENT) {
7654 // This is the expected error, we can exit the test now.
7655 return;
7656 } else {
7657 // Very small chance we got valid decryption, so try again.
7658 ASSERT_EQ(error, ErrorCode::OK);
7659 }
7660 }
7661 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007662}
7663
7664/*
7665 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7666 *
7667 * Verifies that 3DES CBC works with many different input sizes.
7668 */
7669TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7671 .TripleDesEncryptionKey(168)
7672 .BlockMode(BlockMode::CBC)
7673 .Authorization(TAG_NO_AUTH_REQUIRED)
7674 .Padding(PaddingMode::NONE)));
7675
7676 int increment = 7;
7677 string message(240, 'a');
7678 AuthorizationSet input_params =
7679 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7680 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007681 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007682
7683 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007684 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007685 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007686 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7687 EXPECT_EQ(message.size(), ciphertext.size());
7688
7689 // Move TAG_NONCE into input_params
7690 input_params = output_params;
7691 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7692 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7693 output_params.Clear();
7694
David Drysdale7fc26b92022-05-13 09:54:24 +01007695 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007696 string plaintext;
7697 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007698 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007699 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7700 EXPECT_EQ(ciphertext.size(), plaintext.size());
7701 EXPECT_EQ(message, plaintext);
7702}
7703
7704INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7705
7706typedef KeyMintAidlTestBase MaxOperationsTest;
7707
7708/*
7709 * MaxOperationsTest.TestLimitAes
7710 *
7711 * Verifies that the max uses per boot tag works correctly with AES keys.
7712 */
7713TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007714 if (SecLevel() == SecurityLevel::STRONGBOX) {
7715 GTEST_SKIP() << "Test not applicable to StrongBox device";
7716 }
Selene Huang31ab4042020-04-29 04:22:39 -07007717
7718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7719 .Authorization(TAG_NO_AUTH_REQUIRED)
7720 .AesEncryptionKey(128)
7721 .EcbMode()
7722 .Padding(PaddingMode::NONE)
7723 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7724
7725 string message = "1234567890123456";
7726
7727 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7728
7729 EncryptMessage(message, params);
7730 EncryptMessage(message, params);
7731 EncryptMessage(message, params);
7732
7733 // Fourth time should fail.
7734 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7735}
7736
7737/*
Qi Wud22ec842020-11-26 13:27:53 +08007738 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007739 *
7740 * Verifies that the max uses per boot tag works correctly with RSA keys.
7741 */
7742TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007743 if (SecLevel() == SecurityLevel::STRONGBOX) {
7744 GTEST_SKIP() << "Test not applicable to StrongBox device";
7745 }
Selene Huang31ab4042020-04-29 04:22:39 -07007746
7747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7748 .Authorization(TAG_NO_AUTH_REQUIRED)
7749 .RsaSigningKey(1024, 65537)
7750 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007751 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7752 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007753
7754 string message = "1234567890123456";
7755
7756 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7757
7758 SignMessage(message, params);
7759 SignMessage(message, params);
7760 SignMessage(message, params);
7761
7762 // Fourth time should fail.
7763 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7764}
7765
7766INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7767
Qi Wud22ec842020-11-26 13:27:53 +08007768typedef KeyMintAidlTestBase UsageCountLimitTest;
7769
7770/*
Qi Wubeefae42021-01-28 23:16:37 +08007771 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007772 *
Qi Wubeefae42021-01-28 23:16:37 +08007773 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007774 */
Qi Wubeefae42021-01-28 23:16:37 +08007775TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007776 if (SecLevel() == SecurityLevel::STRONGBOX) {
7777 GTEST_SKIP() << "Test not applicable to StrongBox device";
7778 }
Qi Wud22ec842020-11-26 13:27:53 +08007779
7780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7781 .Authorization(TAG_NO_AUTH_REQUIRED)
7782 .AesEncryptionKey(128)
7783 .EcbMode()
7784 .Padding(PaddingMode::NONE)
7785 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7786
7787 // Check the usage count limit tag appears in the authorizations.
7788 AuthorizationSet auths;
7789 for (auto& entry : key_characteristics_) {
7790 auths.push_back(AuthorizationSet(entry.authorizations));
7791 }
7792 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7793 << "key usage count limit " << 1U << " missing";
7794
7795 string message = "1234567890123456";
7796 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7797
Qi Wubeefae42021-01-28 23:16:37 +08007798 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7799 AuthorizationSet keystore_auths =
7800 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7801
Qi Wud22ec842020-11-26 13:27:53 +08007802 // First usage of AES key should work.
7803 EncryptMessage(message, params);
7804
Qi Wud22ec842020-11-26 13:27:53 +08007805 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7806 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7807 // must be invalidated from secure storage (such as RPMB partition).
7808 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7809 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007810 // Usage count limit tag is enforced by keystore, keymint does nothing.
7811 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007812 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007813 }
7814}
7815
7816/*
Qi Wubeefae42021-01-28 23:16:37 +08007817 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007818 *
Qi Wubeefae42021-01-28 23:16:37 +08007819 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007820 */
Qi Wubeefae42021-01-28 23:16:37 +08007821TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007822 if (SecLevel() == SecurityLevel::STRONGBOX) {
7823 GTEST_SKIP() << "Test not applicable to StrongBox device";
7824 }
Qi Wubeefae42021-01-28 23:16:37 +08007825
7826 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7827 .Authorization(TAG_NO_AUTH_REQUIRED)
7828 .AesEncryptionKey(128)
7829 .EcbMode()
7830 .Padding(PaddingMode::NONE)
7831 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7832
7833 // Check the usage count limit tag appears in the authorizations.
7834 AuthorizationSet auths;
7835 for (auto& entry : key_characteristics_) {
7836 auths.push_back(AuthorizationSet(entry.authorizations));
7837 }
7838 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7839 << "key usage count limit " << 3U << " missing";
7840
7841 string message = "1234567890123456";
7842 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7843
7844 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7845 AuthorizationSet keystore_auths =
7846 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7847
7848 EncryptMessage(message, params);
7849 EncryptMessage(message, params);
7850 EncryptMessage(message, params);
7851
7852 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7853 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7854 // must be invalidated from secure storage (such as RPMB partition).
7855 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7856 } else {
7857 // Usage count limit tag is enforced by keystore, keymint does nothing.
7858 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007859 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007860 }
7861}
7862
7863/*
7864 * UsageCountLimitTest.TestSingleUseRsa
7865 *
7866 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7867 */
7868TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007869 if (SecLevel() == SecurityLevel::STRONGBOX) {
7870 GTEST_SKIP() << "Test not applicable to StrongBox device";
7871 }
Qi Wud22ec842020-11-26 13:27:53 +08007872
7873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7874 .Authorization(TAG_NO_AUTH_REQUIRED)
7875 .RsaSigningKey(1024, 65537)
7876 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007877 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7878 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007879
7880 // Check the usage count limit tag appears in the authorizations.
7881 AuthorizationSet auths;
7882 for (auto& entry : key_characteristics_) {
7883 auths.push_back(AuthorizationSet(entry.authorizations));
7884 }
7885 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7886 << "key usage count limit " << 1U << " missing";
7887
7888 string message = "1234567890123456";
7889 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7890
Qi Wubeefae42021-01-28 23:16:37 +08007891 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7892 AuthorizationSet keystore_auths =
7893 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7894
Qi Wud22ec842020-11-26 13:27:53 +08007895 // First usage of RSA key should work.
7896 SignMessage(message, params);
7897
Qi Wud22ec842020-11-26 13:27:53 +08007898 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7899 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7900 // must be invalidated from secure storage (such as RPMB partition).
7901 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7902 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007903 // Usage count limit tag is enforced by keystore, keymint does nothing.
7904 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007905 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007906 }
7907}
7908
7909/*
7910 * UsageCountLimitTest.TestLimitUseRsa
7911 *
7912 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7913 */
7914TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007915 if (SecLevel() == SecurityLevel::STRONGBOX) {
7916 GTEST_SKIP() << "Test not applicable to StrongBox device";
7917 }
Qi Wubeefae42021-01-28 23:16:37 +08007918
7919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7920 .Authorization(TAG_NO_AUTH_REQUIRED)
7921 .RsaSigningKey(1024, 65537)
7922 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007923 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7924 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007925
7926 // Check the usage count limit tag appears in the authorizations.
7927 AuthorizationSet auths;
7928 for (auto& entry : key_characteristics_) {
7929 auths.push_back(AuthorizationSet(entry.authorizations));
7930 }
7931 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7932 << "key usage count limit " << 3U << " missing";
7933
7934 string message = "1234567890123456";
7935 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7936
7937 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7938 AuthorizationSet keystore_auths =
7939 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7940
7941 SignMessage(message, params);
7942 SignMessage(message, params);
7943 SignMessage(message, params);
7944
7945 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7946 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7947 // must be invalidated from secure storage (such as RPMB partition).
7948 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7949 } else {
7950 // Usage count limit tag is enforced by keystore, keymint does nothing.
7951 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007952 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007953 }
7954}
7955
Qi Wu8e727f72021-02-11 02:49:33 +08007956/*
7957 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7958 *
7959 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7960 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7961 * in hardware.
7962 */
7963TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007964 auto error = GenerateKey(AuthorizationSetBuilder()
7965 .RsaSigningKey(2048, 65537)
7966 .Digest(Digest::NONE)
7967 .Padding(PaddingMode::NONE)
7968 .Authorization(TAG_NO_AUTH_REQUIRED)
7969 .Authorization(TAG_ROLLBACK_RESISTANCE)
7970 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007971 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7972 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007973 }
David Drysdale513bf122021-10-06 11:53:13 +01007974
7975 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7976 ASSERT_EQ(ErrorCode::OK, error);
7977 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7978 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7979 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7980
7981 // The KeyMint should also enforce single use key in hardware when it supports rollback
7982 // resistance.
7983 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7984 .Authorization(TAG_NO_AUTH_REQUIRED)
7985 .RsaSigningKey(1024, 65537)
7986 .NoDigestOrPadding()
7987 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7988 .SetDefaultValidity()));
7989
7990 // Check the usage count limit tag appears in the hardware authorizations.
7991 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7992 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7993 << "key usage count limit " << 1U << " missing";
7994
7995 string message = "1234567890123456";
7996 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7997
7998 // First usage of RSA key should work.
7999 SignMessage(message, params);
8000
8001 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8002 // must be invalidated from secure storage (such as RPMB partition).
8003 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08008004}
8005
Qi Wud22ec842020-11-26 13:27:53 +08008006INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
8007
David Drysdale7de9feb2021-03-05 14:56:19 +00008008typedef KeyMintAidlTestBase GetHardwareInfoTest;
8009
8010TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
8011 // Retrieving hardware info should give the same result each time.
8012 KeyMintHardwareInfo info;
8013 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
8014 KeyMintHardwareInfo info2;
8015 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
8016 EXPECT_EQ(info, info2);
8017}
8018
8019INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
8020
Selene Huang31ab4042020-04-29 04:22:39 -07008021typedef KeyMintAidlTestBase AddEntropyTest;
8022
8023/*
8024 * AddEntropyTest.AddEntropy
8025 *
8026 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
8027 * is actually added.
8028 */
8029TEST_P(AddEntropyTest, AddEntropy) {
8030 string data = "foo";
8031 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
8032}
8033
8034/*
8035 * AddEntropyTest.AddEmptyEntropy
8036 *
8037 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
8038 */
8039TEST_P(AddEntropyTest, AddEmptyEntropy) {
8040 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8041}
8042
8043/*
8044 * AddEntropyTest.AddLargeEntropy
8045 *
8046 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8047 */
8048TEST_P(AddEntropyTest, AddLargeEntropy) {
8049 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8050}
8051
David Drysdalebb3d85e2021-04-13 11:15:51 +01008052/*
8053 * AddEntropyTest.AddTooLargeEntropy
8054 *
8055 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8056 */
8057TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8058 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8059 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8060}
8061
Selene Huang31ab4042020-04-29 04:22:39 -07008062INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8063
Selene Huang31ab4042020-04-29 04:22:39 -07008064typedef KeyMintAidlTestBase KeyDeletionTest;
8065
8066/**
8067 * KeyDeletionTest.DeleteKey
8068 *
8069 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8070 * valid key blob.
8071 */
8072TEST_P(KeyDeletionTest, DeleteKey) {
8073 auto error = GenerateKey(AuthorizationSetBuilder()
8074 .RsaSigningKey(2048, 65537)
8075 .Digest(Digest::NONE)
8076 .Padding(PaddingMode::NONE)
8077 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008078 .Authorization(TAG_ROLLBACK_RESISTANCE)
8079 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008080 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8081 GTEST_SKIP() << "Rollback resistance not supported";
8082 }
Selene Huang31ab4042020-04-29 04:22:39 -07008083
8084 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008085 ASSERT_EQ(ErrorCode::OK, error);
8086 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8087 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008088
David Drysdale513bf122021-10-06 11:53:13 +01008089 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008090
David Drysdale513bf122021-10-06 11:53:13 +01008091 string message = "12345678901234567890123456789012";
8092 AuthorizationSet begin_out_params;
8093 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8094 Begin(KeyPurpose::SIGN, key_blob_,
8095 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8096 &begin_out_params));
8097 AbortIfNeeded();
8098 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008099}
8100
8101/**
8102 * KeyDeletionTest.DeleteInvalidKey
8103 *
8104 * This test checks that the HAL excepts invalid key blobs..
8105 */
8106TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8107 // Generate key just to check if rollback protection is implemented
8108 auto error = GenerateKey(AuthorizationSetBuilder()
8109 .RsaSigningKey(2048, 65537)
8110 .Digest(Digest::NONE)
8111 .Padding(PaddingMode::NONE)
8112 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008113 .Authorization(TAG_ROLLBACK_RESISTANCE)
8114 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008115 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8116 GTEST_SKIP() << "Rollback resistance not supported";
8117 }
Selene Huang31ab4042020-04-29 04:22:39 -07008118
8119 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008120 ASSERT_EQ(ErrorCode::OK, error);
8121 AuthorizationSet enforced(SecLevelAuthorizations());
8122 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008123
David Drysdale513bf122021-10-06 11:53:13 +01008124 // Delete the key we don't care about the result at this point.
8125 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008126
David Drysdale513bf122021-10-06 11:53:13 +01008127 // Now create an invalid key blob and delete it.
8128 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008129
David Drysdale513bf122021-10-06 11:53:13 +01008130 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008131}
8132
8133/**
8134 * KeyDeletionTest.DeleteAllKeys
8135 *
8136 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8137 *
8138 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8139 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8140 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8141 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8142 * credentials stored in Keystore/Keymint.
8143 */
8144TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008145 if (!arm_deleteAllKeys) {
8146 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8147 return;
8148 }
Selene Huang31ab4042020-04-29 04:22:39 -07008149 auto error = GenerateKey(AuthorizationSetBuilder()
8150 .RsaSigningKey(2048, 65537)
8151 .Digest(Digest::NONE)
8152 .Padding(PaddingMode::NONE)
8153 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008154 .Authorization(TAG_ROLLBACK_RESISTANCE)
8155 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008156 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8157 GTEST_SKIP() << "Rollback resistance not supported";
8158 }
Selene Huang31ab4042020-04-29 04:22:39 -07008159
8160 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008161 ASSERT_EQ(ErrorCode::OK, error);
8162 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8163 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008164
David Drysdale513bf122021-10-06 11:53:13 +01008165 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008166
David Drysdale513bf122021-10-06 11:53:13 +01008167 string message = "12345678901234567890123456789012";
8168 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008169
David Drysdale513bf122021-10-06 11:53:13 +01008170 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8171 Begin(KeyPurpose::SIGN, key_blob_,
8172 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8173 &begin_out_params));
8174 AbortIfNeeded();
8175 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008176}
8177
8178INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8179
David Drysdaled2cc8c22021-04-15 13:29:45 +01008180typedef KeyMintAidlTestBase KeyUpgradeTest;
8181
8182/**
8183 * KeyUpgradeTest.UpgradeInvalidKey
8184 *
8185 * This test checks that the HAL excepts invalid key blobs..
8186 */
8187TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8188 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8189
8190 std::vector<uint8_t> new_blob;
8191 Status result = keymint_->upgradeKey(key_blob,
8192 AuthorizationSetBuilder()
8193 .Authorization(TAG_APPLICATION_ID, "clientid")
8194 .Authorization(TAG_APPLICATION_DATA, "appdata")
8195 .vector_data(),
8196 &new_blob);
8197 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8198}
8199
8200INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8201
Selene Huang31ab4042020-04-29 04:22:39 -07008202using UpgradeKeyTest = KeyMintAidlTestBase;
8203
8204/*
8205 * UpgradeKeyTest.UpgradeKey
8206 *
8207 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8208 */
8209TEST_P(UpgradeKeyTest, UpgradeKey) {
8210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8211 .AesEncryptionKey(128)
8212 .Padding(PaddingMode::NONE)
8213 .Authorization(TAG_NO_AUTH_REQUIRED)));
8214
8215 auto result = UpgradeKey(key_blob_);
8216
8217 // Key doesn't need upgrading. Should get okay, but no new key blob.
8218 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8219}
8220
8221INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8222
8223using ClearOperationsTest = KeyMintAidlTestBase;
8224
8225/*
8226 * ClearSlotsTest.TooManyOperations
8227 *
8228 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8229 * operations are started without being finished or aborted. Also verifies
8230 * that aborting the operations clears the operations.
8231 *
8232 */
8233TEST_P(ClearOperationsTest, TooManyOperations) {
8234 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8235 .Authorization(TAG_NO_AUTH_REQUIRED)
8236 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008237 .Padding(PaddingMode::NONE)
8238 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008239
8240 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8241 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008242 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008243 AuthorizationSet out_params;
8244 ErrorCode result;
8245 size_t i;
8246
8247 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008248 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008249 if (ErrorCode::OK != result) {
8250 break;
8251 }
8252 }
8253 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8254 // Try again just in case there's a weird overflow bug
8255 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008256 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008257 for (size_t j = 0; j < i; j++) {
8258 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8259 << "Aboort failed for i = " << j << std::endl;
8260 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008261 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008262 AbortIfNeeded();
8263}
8264
8265INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8266
8267typedef KeyMintAidlTestBase TransportLimitTest;
8268
8269/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008270 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008271 *
8272 * Verifies that passing input data to finish succeeds as expected.
8273 */
8274TEST_P(TransportLimitTest, LargeFinishInput) {
8275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8276 .Authorization(TAG_NO_AUTH_REQUIRED)
8277 .AesEncryptionKey(128)
8278 .BlockMode(BlockMode::ECB)
8279 .Padding(PaddingMode::NONE)));
8280
8281 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008282 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008283 auto cipher_params =
8284 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8285
8286 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008287 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008288
8289 string plain_message = std::string(1 << msg_size, 'x');
8290 string encrypted_message;
8291 auto rc = Finish(plain_message, &encrypted_message);
8292
8293 EXPECT_EQ(ErrorCode::OK, rc);
8294 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8295 << "Encrypt finish returned OK, but did not consume all of the given input";
8296 cipher_params.push_back(out_params);
8297
David Drysdale7fc26b92022-05-13 09:54:24 +01008298 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008299
8300 string decrypted_message;
8301 rc = Finish(encrypted_message, &decrypted_message);
8302 EXPECT_EQ(ErrorCode::OK, rc);
8303 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8304 << "Decrypt finish returned OK, did not consume all of the given input";
8305 }
8306}
8307
8308INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8309
Seth Moored79a0ec2021-12-13 20:03:33 +00008310static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008311 switch (curve) {
8312 case EcCurve::P_224:
8313 return NID_secp224r1;
8314 case EcCurve::P_256:
8315 return NID_X9_62_prime256v1;
8316 case EcCurve::P_384:
8317 return NID_secp384r1;
8318 case EcCurve::P_521:
8319 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008320 case EcCurve::CURVE_25519:
8321 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008322 }
8323}
8324
David Drysdale42fe1892021-10-14 14:43:46 +01008325class KeyAgreementTest : public KeyMintAidlTestBase {
8326 protected:
8327 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8328 std::vector<uint8_t>* localPublicKey) {
8329 // Generate EC key locally (with access to private key material)
8330 if (localCurve == EcCurve::CURVE_25519) {
8331 uint8_t privKeyData[32];
8332 uint8_t pubKeyData[32];
8333 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008334 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8335 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8336 } else {
8337 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8338 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8339 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8340 ASSERT_NE(group, nullptr);
8341 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8342 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8343 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8344 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008345 }
David Drysdalea410b772022-05-09 16:44:13 +01008346
8347 // Get encoded form of the public part of the locally generated key...
8348 unsigned char* p = nullptr;
8349 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8350 ASSERT_GT(localPublicKeySize, 0);
8351 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8352 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8353 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008354 }
8355
8356 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8357 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008358 auto builder = AuthorizationSetBuilder()
8359 .Authorization(TAG_NO_AUTH_REQUIRED)
8360 .Authorization(TAG_EC_CURVE, curve)
8361 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8362 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8363 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8364 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8365 .SetDefaultValidity();
8366 ErrorCode result = GenerateKey(builder);
8367
8368 if (SecLevel() == SecurityLevel::STRONGBOX) {
8369 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8370 result = GenerateKeyWithSelfSignedAttestKey(
8371 AuthorizationSetBuilder()
8372 .EcdsaKey(EcCurve::P_256)
8373 .AttestKey()
8374 .SetDefaultValidity(), /* attest key params */
8375 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8376 }
8377 }
David Drysdale42fe1892021-10-14 14:43:46 +01008378 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8379 ASSERT_GT(cert_chain_.size(), 0);
8380 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8381 ASSERT_NE(kmKeyCert, nullptr);
8382 // Check that keyAgreement (bit 4) is set in KeyUsage
8383 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8384 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8385 ASSERT_NE(*kmPubKey, nullptr);
8386 if (dump_Attestations) {
8387 for (size_t n = 0; n < cert_chain_.size(); n++) {
8388 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8389 }
8390 }
8391 }
8392
8393 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8394 const std::vector<uint8_t>& localPublicKey) {
8395 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8396 string ZabFromKeyMintStr;
8397 ASSERT_EQ(ErrorCode::OK,
8398 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8399 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8400 vector<uint8_t> ZabFromTest;
8401
8402 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8403 size_t kmPubKeySize = 32;
8404 uint8_t kmPubKeyData[32];
8405 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8406 ASSERT_EQ(kmPubKeySize, 32);
8407
8408 uint8_t localPrivKeyData[32];
8409 size_t localPrivKeySize = 32;
8410 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8411 &localPrivKeySize));
8412 ASSERT_EQ(localPrivKeySize, 32);
8413
8414 uint8_t sharedKey[32];
8415 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8416 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8417 } else {
8418 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8419 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8420 ASSERT_NE(ctx, nullptr);
8421 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8422 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8423 size_t ZabFromTestLen = 0;
8424 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8425 ZabFromTest.resize(ZabFromTestLen);
8426 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8427 }
8428 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8429 }
8430};
8431
David Zeuthene0c40892021-01-08 12:54:11 -05008432/*
8433 * KeyAgreementTest.Ecdh
8434 *
David Drysdale42fe1892021-10-14 14:43:46 +01008435 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008436 */
8437TEST_P(KeyAgreementTest, Ecdh) {
8438 // Because it's possible to use this API with keys on different curves, we
8439 // check all N^2 combinations where N is the number of supported
8440 // curves.
8441 //
8442 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8443 // lot more curves we can be smart about things and just pick |otherCurve| so
8444 // it's not |curve| and that way we end up with only 2*N runs
8445 //
8446 for (auto curve : ValidCurves()) {
8447 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008448 SCOPED_TRACE(testing::Message()
8449 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8450
David Zeuthene0c40892021-01-08 12:54:11 -05008451 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008452 EVP_PKEY_Ptr localPrivKey;
8453 vector<uint8_t> localPublicKey;
8454 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008455
8456 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008457 EVP_PKEY_Ptr kmPubKey;
8458 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008459
8460 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8461 if (curve != localCurve) {
8462 // If the keys are using different curves KeyMint should fail with
8463 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008464 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008465 string ZabFromKeyMintStr;
8466 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008467 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008468 &ZabFromKeyMintStr));
8469
8470 } else {
8471 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008472 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008473 }
8474
8475 CheckedDeleteKey();
8476 }
8477 }
8478}
8479
David Drysdale42fe1892021-10-14 14:43:46 +01008480/*
8481 * KeyAgreementTest.EcdhCurve25519
8482 *
8483 * Verifies that ECDH works for curve25519. This is also covered by the general
8484 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8485 * KeyMint 1.0.
8486 */
8487TEST_P(KeyAgreementTest, EcdhCurve25519) {
8488 if (!Curve25519Supported()) {
8489 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8490 }
8491
8492 // Generate EC key in KeyMint (only access to public key material)
8493 EcCurve curve = EcCurve::CURVE_25519;
8494 EVP_PKEY_Ptr kmPubKey = nullptr;
8495 GenerateKeyMintEcKey(curve, &kmPubKey);
8496
8497 // Generate EC key on same curve locally (with access to private key material).
8498 EVP_PKEY_Ptr privKey;
8499 vector<uint8_t> encodedPublicKey;
8500 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8501
8502 // Agree on a key between local and KeyMint and check it.
8503 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8504
8505 CheckedDeleteKey();
8506}
8507
8508/*
8509 * KeyAgreementTest.EcdhCurve25519Imported
8510 *
8511 * Verifies that ECDH works for an imported curve25519 key.
8512 */
8513TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8514 if (!Curve25519Supported()) {
8515 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8516 }
8517
8518 // Import x25519 key into KeyMint.
8519 EcCurve curve = EcCurve::CURVE_25519;
8520 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8521 .Authorization(TAG_NO_AUTH_REQUIRED)
8522 .EcdsaKey(EcCurve::CURVE_25519)
8523 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8524 .SetDefaultValidity(),
8525 KeyFormat::PKCS8, x25519_pkcs8_key));
8526 ASSERT_GT(cert_chain_.size(), 0);
8527 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8528 ASSERT_NE(kmKeyCert, nullptr);
8529 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8530 ASSERT_NE(kmPubKey.get(), nullptr);
8531
8532 // Expect the import to emit corresponding public key data.
8533 size_t kmPubKeySize = 32;
8534 uint8_t kmPubKeyData[32];
8535 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8536 ASSERT_EQ(kmPubKeySize, 32);
8537 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8538 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8539
8540 // Generate EC key on same curve locally (with access to private key material).
8541 EVP_PKEY_Ptr privKey;
8542 vector<uint8_t> encodedPublicKey;
8543 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8544
8545 // Agree on a key between local and KeyMint and check it.
8546 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8547
8548 CheckedDeleteKey();
8549}
8550
8551/*
8552 * KeyAgreementTest.EcdhCurve25519InvalidSize
8553 *
8554 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8555 */
8556TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8557 if (!Curve25519Supported()) {
8558 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8559 }
8560
8561 // Generate EC key in KeyMint (only access to public key material)
8562 EcCurve curve = EcCurve::CURVE_25519;
8563 EVP_PKEY_Ptr kmPubKey = nullptr;
8564 GenerateKeyMintEcKey(curve, &kmPubKey);
8565
8566 // Generate EC key on same curve locally (with access to private key material).
8567 EVP_PKEY_Ptr privKey;
8568 vector<uint8_t> encodedPublicKey;
8569 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8570
8571 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8572 string ZabFromKeyMintStr;
8573 // Send in an incomplete public key.
8574 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8575 &ZabFromKeyMintStr));
8576
8577 CheckedDeleteKey();
8578}
8579
8580/*
8581 * KeyAgreementTest.EcdhCurve25519Mismatch
8582 *
8583 * Verifies that ECDH fails between curve25519 and other curves.
8584 */
8585TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8586 if (!Curve25519Supported()) {
8587 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8588 }
8589
8590 // Generate EC key in KeyMint (only access to public key material)
8591 EcCurve curve = EcCurve::CURVE_25519;
8592 EVP_PKEY_Ptr kmPubKey = nullptr;
8593 GenerateKeyMintEcKey(curve, &kmPubKey);
8594
8595 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008596 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008597 if (localCurve == curve) {
8598 continue;
8599 }
8600 // Generate EC key on a different curve locally (with access to private key material).
8601 EVP_PKEY_Ptr privKey;
8602 vector<uint8_t> encodedPublicKey;
8603 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8604
David Drysdale7fc26b92022-05-13 09:54:24 +01008605 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008606 string ZabFromKeyMintStr;
8607 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8608 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8609 &ZabFromKeyMintStr));
8610 }
8611
8612 CheckedDeleteKey();
8613}
8614
David Zeuthene0c40892021-01-08 12:54:11 -05008615INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8616
David Drysdaled2cc8c22021-04-15 13:29:45 +01008617using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8618
8619// This is a problematic test, as it can render the device under test permanently unusable.
8620// Re-enable and run at your own risk.
8621TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8622 auto result = DestroyAttestationIds();
8623 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8624}
8625
8626INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8627
Shawn Willdend659c7c2021-02-19 14:51:51 -07008628using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008629
David Drysdaledb0dcf52021-05-18 11:43:31 +01008630/*
8631 * EarlyBootKeyTest.CreateEarlyBootKeys
8632 *
8633 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8634 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008635TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008636 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008637 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8638 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008639 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8640 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8641 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8642 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008643
David Drysdaleadfe6112021-05-27 12:00:53 +01008644 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8645 ASSERT_GT(keyData.blob.size(), 0U);
8646 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8647 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8648 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008649}
8650
David Drysdaledb0dcf52021-05-18 11:43:31 +01008651/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008652 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8653 *
8654 * Verifies that creating an early boot key with attestation succeeds.
8655 */
8656TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8657 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8658 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8659 builder->AttestationChallenge("challenge");
8660 builder->AttestationApplicationId("app_id");
8661 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008662 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8663 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8664 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8665 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008666
8667 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008668 // Strongbox may not support factory attestation. Key creation might fail with
8669 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8670 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8671 continue;
8672 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008673 ASSERT_GT(keyData.blob.size(), 0U);
8674 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8675 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8676 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008677}
8678
8679/*
8680 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008681 *
8682 * Verifies that using early boot keys at a later stage fails.
8683 */
8684TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8686 .Authorization(TAG_NO_AUTH_REQUIRED)
8687 .Authorization(TAG_EARLY_BOOT_ONLY)
8688 .HmacKey(128)
8689 .Digest(Digest::SHA_2_256)
8690 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8691 AuthorizationSet output_params;
8692 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8693 AuthorizationSetBuilder()
8694 .Digest(Digest::SHA_2_256)
8695 .Authorization(TAG_MAC_LENGTH, 256),
8696 &output_params));
8697}
8698
8699/*
8700 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8701 *
8702 * Verifies that importing early boot keys fails.
8703 */
8704TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8705 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8706 .Authorization(TAG_NO_AUTH_REQUIRED)
8707 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008708 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008709 .Digest(Digest::SHA_2_256)
8710 .SetDefaultValidity(),
8711 KeyFormat::PKCS8, ec_256_key));
8712}
8713
David Drysdaled2cc8c22021-04-15 13:29:45 +01008714// This is a more comprehensive test, but it can only be run on a machine which is still in early
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008715// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8716// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8717// early boot, so you'll have to reboot between runs.
8718TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8719 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8720 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008721 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8722 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8723 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8724 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8725
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008726 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8727 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8728 EXPECT_TRUE(
8729 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8730 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8731 EXPECT_TRUE(
8732 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8733
8734 // Should be able to use keys, since early boot has not ended
8735 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8736 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8737 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8738 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8739
8740 // End early boot
8741 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8742 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8743
8744 // Should not be able to use already-created keys.
8745 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8746 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8747 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8748 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8749
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008750 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008751 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008752 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008753 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8754 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8755 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8756 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008757}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008758
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008759INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8760
Shawn Willdend659c7c2021-02-19 14:51:51 -07008761using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008762
8763// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8764// between runs... and on most test devices there are no enrolled credentials so it can't be
8765// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8766// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8767// a manual test process, which includes unlocking between runs, which is why it's included here.
8768// Well, that and the fact that it's the only test we can do without also making calls into the
8769// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8770// implications might be, so that may or may not be a solution.
8771TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8772 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8773 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008774 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8775 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8776 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8777 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008778
8779 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8780 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8781 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8782 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8783
8784 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008785 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008786 ASSERT_EQ(ErrorCode::OK, rc);
8787 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8788 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8789 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8790 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008791}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008792
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008793INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8794
Shawn Willden22fb9c12022-06-02 14:04:33 -06008795using VsrRequirementTest = KeyMintAidlTestBase;
8796
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008797// @VsrTest = VSR-3.10-008
Shawn Willden22fb9c12022-06-02 14:04:33 -06008798TEST_P(VsrRequirementTest, Vsr13Test) {
8799 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008800 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008801 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8802 }
8803 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8804}
8805
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008806// @VsrTest = VSR-3.10-013.001
Eran Messerib9346f52022-12-15 14:58:34 +00008807TEST_P(VsrRequirementTest, Vsr14Test) {
8808 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008809 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008810 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8811 }
8812 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8813}
8814
Shawn Willden22fb9c12022-06-02 14:04:33 -06008815INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8816
Janis Danisevskis24c04702020-12-16 18:28:39 -08008817} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008818
8819int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008820 std::cout << "Testing ";
8821 auto halInstances =
8822 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8823 std::cout << "HAL instances:\n";
8824 for (auto& entry : halInstances) {
8825 std::cout << " " << entry << '\n';
8826 }
8827
Selene Huang31ab4042020-04-29 04:22:39 -07008828 ::testing::InitGoogleTest(&argc, argv);
8829 for (int i = 1; i < argc; ++i) {
8830 if (argv[i][0] == '-') {
8831 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008832 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8833 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008834 }
8835 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008836 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8837 dump_Attestations = true;
8838 } else {
8839 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008840 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008841 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8842 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8843 // be run in emulated environments that don't have the normal bootloader
8844 // interactions.
8845 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8846 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008847 if (std::string(argv[i]) == "--keyblob_dir") {
8848 if (i + 1 >= argc) {
8849 std::cerr << "Missing argument for --keyblob_dir\n";
8850 return 1;
8851 }
8852 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8853 std::string(argv[i + 1]);
8854 ++i;
8855 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008856 if (std::string(argv[i]) == "--expect_upgrade") {
8857 if (i + 1 >= argc) {
8858 std::cerr << "Missing argument for --expect_upgrade\n";
8859 return 1;
8860 }
8861 std::string arg = argv[i + 1];
8862 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8863 expect_upgrade =
8864 arg == "yes"
8865 ? true
8866 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
8867 ++i;
8868 }
Selene Huang31ab4042020-04-29 04:22:39 -07008869 }
8870 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008871 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008872}