blob: 1e61a1817be372cf7fdacf561a2ea3f5da43c50e [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
Selene Huang31ab4042020-04-29 04:22:39 -07002568 * UNSUPPORTED_KEY_SIZE.
2569 */
2570TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2571 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2572 GenerateKey(AuthorizationSetBuilder()
2573 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2574 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002575 .Digest(Digest::NONE)
2576 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002577}
2578
2579/*
David Drysdale42fe1892021-10-14 14:43:46 +01002580 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002581 *
David Drysdale42fe1892021-10-14 14:43:46 +01002582 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002583 * UNSUPPORTED_KEY_SIZE.
2584 */
David Drysdale42fe1892021-10-14 14:43:46 +01002585TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002586 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002587 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002588 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002589 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002590 auto result = GenerateKey(AuthorizationSetBuilder()
2591 .EcdsaSigningKey(curve)
2592 .Digest(Digest::NONE)
2593 .SetDefaultValidity(),
2594 &key_blob, &key_characteristics);
2595 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2596 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002597 }
2598
David Drysdaledf09e542021-06-08 15:46:11 +01002599 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2600 GenerateKey(AuthorizationSetBuilder()
2601 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2602 .Authorization(TAG_KEY_SIZE, 190)
2603 .SigningKey()
2604 .Digest(Digest::NONE)
2605 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002606}
2607
2608/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002609 * NewKeyGenerationTest.EcdsaMissingCurve
2610 *
2611 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2612 */
2613TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2614 if (AidlVersion() < 2) {
2615 /*
2616 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2617 * However, this was not checked at the time so we can only be strict about checking this
2618 * for implementations of KeyMint version 2 and above.
2619 */
2620 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2621 }
2622 /* If EC_CURVE not provided, generateKey
2623 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2624 */
2625 auto result = GenerateKey(
2626 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2627 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2628 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2629}
2630
2631/*
Selene Huang31ab4042020-04-29 04:22:39 -07002632 * NewKeyGenerationTest.EcdsaMismatchKeySize
2633 *
2634 * Verifies that specifying mismatched key size and curve for EC key generation returns
2635 * INVALID_ARGUMENT.
2636 */
2637TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002638 if (SecLevel() == SecurityLevel::STRONGBOX) {
2639 GTEST_SKIP() << "Test not applicable to StrongBox device";
2640 }
Selene Huang31ab4042020-04-29 04:22:39 -07002641
David Drysdaledf09e542021-06-08 15:46:11 +01002642 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002643 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002644 .Authorization(TAG_KEY_SIZE, 224)
2645 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002646 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002647 .Digest(Digest::NONE)
2648 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002649 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002650}
2651
2652/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002653 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002654 *
2655 * Verifies that keymint does not support any curve designated as unsupported.
2656 */
2657TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2658 Digest digest;
2659 if (SecLevel() == SecurityLevel::STRONGBOX) {
2660 digest = Digest::SHA_2_256;
2661 } else {
2662 digest = Digest::SHA_2_512;
2663 }
2664 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002665 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002666 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2667 .EcdsaSigningKey(curve)
2668 .Digest(digest)
2669 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002670 << "Failed to generate key on curve: " << curve;
2671 CheckedDeleteKey();
2672 }
2673}
2674
2675/*
2676 * NewKeyGenerationTest.Hmac
2677 *
2678 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2679 * characteristics.
2680 */
2681TEST_P(NewKeyGenerationTest, Hmac) {
2682 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002683 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002684 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002685 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002686 constexpr size_t key_size = 128;
2687 ASSERT_EQ(ErrorCode::OK,
2688 GenerateKey(
2689 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2690 TAG_MIN_MAC_LENGTH, 128),
2691 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002692 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002693
2694 ASSERT_GT(key_blob.size(), 0U);
2695 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002696 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002697
Shawn Willden7f424372021-01-10 18:06:50 -07002698 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2699 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2700 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2701 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002702 }
2703}
2704
2705/*
Selene Huang4f64c222021-04-13 19:54:36 -07002706 * NewKeyGenerationTest.HmacNoAttestation
2707 *
2708 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2709 * and app id are provided.
2710 */
2711TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2712 auto challenge = "hello";
2713 auto app_id = "foo";
2714
2715 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002716 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002717 vector<uint8_t> key_blob;
2718 vector<KeyCharacteristics> key_characteristics;
2719 constexpr size_t key_size = 128;
2720 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2721 .HmacKey(key_size)
2722 .Digest(digest)
2723 .AttestationChallenge(challenge)
2724 .AttestationApplicationId(app_id)
2725 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2726 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002727 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002728
2729 ASSERT_GT(key_blob.size(), 0U);
2730 ASSERT_EQ(cert_chain_.size(), 0);
2731 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002732 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002733
2734 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2736 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2737 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002738 }
2739}
2740
2741/*
Qi Wud22ec842020-11-26 13:27:53 +08002742 * NewKeyGenerationTest.LimitedUsageHmac
2743 *
2744 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2745 * resulting keys have correct characteristics.
2746 */
2747TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2748 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002749 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002750 vector<uint8_t> key_blob;
2751 vector<KeyCharacteristics> key_characteristics;
2752 constexpr size_t key_size = 128;
2753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2754 .HmacKey(key_size)
2755 .Digest(digest)
2756 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2757 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2758 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002759 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002760
2761 ASSERT_GT(key_blob.size(), 0U);
2762 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002763 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002764
2765 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2766 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2767 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2768 << "Key size " << key_size << "missing";
2769
2770 // Check the usage count limit tag appears in the authorizations.
2771 AuthorizationSet auths;
2772 for (auto& entry : key_characteristics) {
2773 auths.push_back(AuthorizationSet(entry.authorizations));
2774 }
2775 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2776 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002777 }
2778}
2779
2780/*
Selene Huang31ab4042020-04-29 04:22:39 -07002781 * NewKeyGenerationTest.HmacCheckKeySizes
2782 *
2783 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2784 */
2785TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2786 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002787 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002788 if (key_size < 64 || key_size % 8 != 0) {
2789 // To keep this test from being very slow, we only test a random fraction of
2790 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2791 // them, we expect to run ~40 of them in each run.
2792 if (key_size % 8 == 0 || random() % 10 == 0) {
2793 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2794 GenerateKey(AuthorizationSetBuilder()
2795 .HmacKey(key_size)
2796 .Digest(Digest::SHA_2_256)
2797 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2798 << "HMAC key size " << key_size << " invalid";
2799 }
2800 } else {
2801 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2802 .HmacKey(key_size)
2803 .Digest(Digest::SHA_2_256)
2804 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2805 << "Failed to generate HMAC key of size " << key_size;
2806 CheckedDeleteKey();
2807 }
2808 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002809 if (SecLevel() == SecurityLevel::STRONGBOX) {
2810 // STRONGBOX devices must not support keys larger than 512 bits.
2811 size_t key_size = 520;
2812 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2813 GenerateKey(AuthorizationSetBuilder()
2814 .HmacKey(key_size)
2815 .Digest(Digest::SHA_2_256)
2816 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2817 << "HMAC key size " << key_size << " unexpectedly valid";
2818 }
Selene Huang31ab4042020-04-29 04:22:39 -07002819}
2820
2821/*
2822 * NewKeyGenerationTest.HmacCheckMinMacLengths
2823 *
2824 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2825 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2826 * specific MAC length that failed, so reproducing a failed run will be easy.
2827 */
2828TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2829 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002830 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002831 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2832 // To keep this test from being very long, we only test a random fraction of
2833 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2834 // we expect to run ~17 of them in each run.
2835 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2836 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2837 GenerateKey(AuthorizationSetBuilder()
2838 .HmacKey(128)
2839 .Digest(Digest::SHA_2_256)
2840 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2841 << "HMAC min mac length " << min_mac_length << " invalid.";
2842 }
2843 } else {
2844 EXPECT_EQ(ErrorCode::OK,
2845 GenerateKey(AuthorizationSetBuilder()
2846 .HmacKey(128)
2847 .Digest(Digest::SHA_2_256)
2848 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2849 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2850 CheckedDeleteKey();
2851 }
2852 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002853
2854 // Minimum MAC length must be no more than 512 bits.
2855 size_t min_mac_length = 520;
2856 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2857 GenerateKey(AuthorizationSetBuilder()
2858 .HmacKey(128)
2859 .Digest(Digest::SHA_2_256)
2860 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2861 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002862}
2863
2864/*
2865 * NewKeyGenerationTest.HmacMultipleDigests
2866 *
2867 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2868 */
2869TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002870 if (SecLevel() == SecurityLevel::STRONGBOX) {
2871 GTEST_SKIP() << "Test not applicable to StrongBox device";
2872 }
Selene Huang31ab4042020-04-29 04:22:39 -07002873
2874 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2875 GenerateKey(AuthorizationSetBuilder()
2876 .HmacKey(128)
2877 .Digest(Digest::SHA1)
2878 .Digest(Digest::SHA_2_256)
2879 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2880}
2881
2882/*
2883 * NewKeyGenerationTest.HmacDigestNone
2884 *
2885 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2886 */
2887TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2888 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2889 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2890 128)));
2891
2892 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2893 GenerateKey(AuthorizationSetBuilder()
2894 .HmacKey(128)
2895 .Digest(Digest::NONE)
2896 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2897}
2898
Selene Huang4f64c222021-04-13 19:54:36 -07002899/*
2900 * NewKeyGenerationTest.AesNoAttestation
2901 *
2902 * Verifies that attestation parameters to AES keys are ignored and generateKey
2903 * will succeed.
2904 */
2905TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2906 auto challenge = "hello";
2907 auto app_id = "foo";
2908
2909 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2910 .Authorization(TAG_NO_AUTH_REQUIRED)
2911 .AesEncryptionKey(128)
2912 .EcbMode()
2913 .Padding(PaddingMode::PKCS7)
2914 .AttestationChallenge(challenge)
2915 .AttestationApplicationId(app_id)));
2916
2917 ASSERT_EQ(cert_chain_.size(), 0);
2918}
2919
2920/*
2921 * NewKeyGenerationTest.TripleDesNoAttestation
2922 *
2923 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2924 * will be successful. No attestation should be generated.
2925 */
2926TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2927 auto challenge = "hello";
2928 auto app_id = "foo";
2929
2930 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2931 .TripleDesEncryptionKey(168)
2932 .BlockMode(BlockMode::ECB)
2933 .Authorization(TAG_NO_AUTH_REQUIRED)
2934 .Padding(PaddingMode::NONE)
2935 .AttestationChallenge(challenge)
2936 .AttestationApplicationId(app_id)));
2937 ASSERT_EQ(cert_chain_.size(), 0);
2938}
2939
Selene Huang31ab4042020-04-29 04:22:39 -07002940INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2941
2942typedef KeyMintAidlTestBase SigningOperationsTest;
2943
2944/*
2945 * SigningOperationsTest.RsaSuccess
2946 *
2947 * Verifies that raw RSA signature operations succeed.
2948 */
2949TEST_P(SigningOperationsTest, RsaSuccess) {
2950 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2951 .RsaSigningKey(2048, 65537)
2952 .Digest(Digest::NONE)
2953 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002954 .Authorization(TAG_NO_AUTH_REQUIRED)
2955 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002956 string message = "12345678901234567890123456789012";
2957 string signature = SignMessage(
2958 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002959 LocalVerifyMessage(message, signature,
2960 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2961}
2962
2963/*
2964 * SigningOperationsTest.RsaAllPaddingsAndDigests
2965 *
2966 * Verifies RSA signature/verification for all padding modes and digests.
2967 */
2968TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2969 auto authorizations = AuthorizationSetBuilder()
2970 .Authorization(TAG_NO_AUTH_REQUIRED)
2971 .RsaSigningKey(2048, 65537)
2972 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2973 .Padding(PaddingMode::NONE)
2974 .Padding(PaddingMode::RSA_PSS)
2975 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2976 .SetDefaultValidity();
2977
2978 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2979
2980 string message(128, 'a');
2981 string corrupt_message(message);
2982 ++corrupt_message[corrupt_message.size() / 2];
2983
2984 for (auto padding :
2985 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2986 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002987 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002988 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2989 // Digesting only makes sense with padding.
2990 continue;
2991 }
2992
2993 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2994 // PSS requires digesting.
2995 continue;
2996 }
2997
2998 string signature =
2999 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
3000 LocalVerifyMessage(message, signature,
3001 AuthorizationSetBuilder().Digest(digest).Padding(padding));
3002 }
3003 }
Selene Huang31ab4042020-04-29 04:22:39 -07003004}
3005
3006/*
3007 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3008 *
Shawn Willden7f424372021-01-10 18:06:50 -07003009 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003010 */
3011TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3012 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3013 .Authorization(TAG_NO_AUTH_REQUIRED)
3014 .RsaSigningKey(2048, 65537)
3015 .Digest(Digest::NONE)
3016 .Padding(PaddingMode::NONE)
3017 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003018 .Authorization(TAG_APPLICATION_DATA, "appdata")
3019 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003020
3021 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3022
Selene Huang31ab4042020-04-29 04:22:39 -07003023 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3024 Begin(KeyPurpose::SIGN,
3025 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3026 AbortIfNeeded();
3027 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3028 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3029 .Digest(Digest::NONE)
3030 .Padding(PaddingMode::NONE)
3031 .Authorization(TAG_APPLICATION_ID, "clientid")));
3032 AbortIfNeeded();
3033 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3034 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3035 .Digest(Digest::NONE)
3036 .Padding(PaddingMode::NONE)
3037 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3038 AbortIfNeeded();
3039 EXPECT_EQ(ErrorCode::OK,
3040 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3041 .Digest(Digest::NONE)
3042 .Padding(PaddingMode::NONE)
3043 .Authorization(TAG_APPLICATION_DATA, "appdata")
3044 .Authorization(TAG_APPLICATION_ID, "clientid")));
3045 AbortIfNeeded();
3046}
3047
3048/*
3049 * SigningOperationsTest.RsaPssSha256Success
3050 *
3051 * Verifies that RSA-PSS signature operations succeed.
3052 */
3053TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3054 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3055 .RsaSigningKey(2048, 65537)
3056 .Digest(Digest::SHA_2_256)
3057 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003058 .Authorization(TAG_NO_AUTH_REQUIRED)
3059 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003060 // Use large message, which won't work without digesting.
3061 string message(1024, 'a');
3062 string signature = SignMessage(
3063 message,
3064 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3065}
3066
3067/*
3068 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3069 *
3070 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3071 * supports only unpadded operations.
3072 */
3073TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3075 .RsaSigningKey(2048, 65537)
3076 .Digest(Digest::NONE)
3077 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003078 .Padding(PaddingMode::NONE)
3079 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003080 string message = "12345678901234567890123456789012";
3081 string signature;
3082
3083 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3084 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3085 .Digest(Digest::NONE)
3086 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3087}
3088
3089/*
3090 * SigningOperationsTest.NoUserConfirmation
3091 *
3092 * Verifies that keymint rejects signing operations for keys with
3093 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3094 * presented.
3095 */
3096TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003098 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003099 .Digest(Digest::NONE)
3100 .Padding(PaddingMode::NONE)
3101 .Authorization(TAG_NO_AUTH_REQUIRED)
3102 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3103 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003104
3105 const string message = "12345678901234567890123456789012";
3106 EXPECT_EQ(ErrorCode::OK,
3107 Begin(KeyPurpose::SIGN,
3108 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3109 string signature;
3110 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3111}
3112
3113/*
3114 * SigningOperationsTest.RsaPkcs1Sha256Success
3115 *
3116 * Verifies that digested RSA-PKCS1 signature operations succeed.
3117 */
3118TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3120 .RsaSigningKey(2048, 65537)
3121 .Digest(Digest::SHA_2_256)
3122 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003123 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3124 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003125 string message(1024, 'a');
3126 string signature = SignMessage(message, AuthorizationSetBuilder()
3127 .Digest(Digest::SHA_2_256)
3128 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3129}
3130
3131/*
3132 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3133 *
3134 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3135 */
3136TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3137 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3138 .RsaSigningKey(2048, 65537)
3139 .Digest(Digest::NONE)
3140 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003141 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3142 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003143 string message(53, 'a');
3144 string signature = SignMessage(message, AuthorizationSetBuilder()
3145 .Digest(Digest::NONE)
3146 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3147}
3148
3149/*
3150 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3151 *
3152 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3153 * given a too-long message.
3154 */
3155TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3156 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3157 .RsaSigningKey(2048, 65537)
3158 .Digest(Digest::NONE)
3159 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003160 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3161 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003162 string message(257, 'a');
3163
3164 EXPECT_EQ(ErrorCode::OK,
3165 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3166 .Digest(Digest::NONE)
3167 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3168 string signature;
3169 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3170}
3171
3172/*
3173 * SigningOperationsTest.RsaPssSha512TooSmallKey
3174 *
3175 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3176 * used with a key that is too small for the message.
3177 *
3178 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3179 * keymint specification requires that salt_size == digest_size, so the message will be
3180 * digest_size * 2 +
3181 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3182 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3183 * for a 1024-bit key.
3184 */
3185TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003186 if (SecLevel() == SecurityLevel::STRONGBOX) {
3187 GTEST_SKIP() << "Test not applicable to StrongBox device";
3188 }
Selene Huang31ab4042020-04-29 04:22:39 -07003189 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3190 .RsaSigningKey(1024, 65537)
3191 .Digest(Digest::SHA_2_512)
3192 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003193 .Padding(PaddingMode::RSA_PSS)
3194 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003195 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3196 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3197 .Digest(Digest::SHA_2_512)
3198 .Padding(PaddingMode::RSA_PSS)));
3199}
3200
3201/*
3202 * SigningOperationsTest.RsaNoPaddingTooLong
3203 *
3204 * Verifies that raw RSA signature operations fail with the correct error code when
3205 * given a too-long message.
3206 */
3207TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3208 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3209 .RsaSigningKey(2048, 65537)
3210 .Digest(Digest::NONE)
3211 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003212 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3213 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003214 // One byte too long
3215 string message(2048 / 8 + 1, 'a');
3216 ASSERT_EQ(ErrorCode::OK,
3217 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3218 .Digest(Digest::NONE)
3219 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3220 string result;
3221 ErrorCode finish_error_code = Finish(message, &result);
3222 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3223 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3224
3225 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3226 message = string(128 * 1024, 'a');
3227 ASSERT_EQ(ErrorCode::OK,
3228 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3229 .Digest(Digest::NONE)
3230 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3231 finish_error_code = Finish(message, &result);
3232 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3233 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3234}
3235
3236/*
3237 * SigningOperationsTest.RsaAbort
3238 *
3239 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3240 * test, but the behavior should be algorithm and purpose-independent.
3241 */
3242TEST_P(SigningOperationsTest, RsaAbort) {
3243 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3244 .RsaSigningKey(2048, 65537)
3245 .Digest(Digest::NONE)
3246 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003247 .Padding(PaddingMode::NONE)
3248 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003249
3250 ASSERT_EQ(ErrorCode::OK,
3251 Begin(KeyPurpose::SIGN,
3252 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3253 EXPECT_EQ(ErrorCode::OK, Abort());
3254
3255 // Another abort should fail
3256 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3257
3258 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003259 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003260}
3261
3262/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003263 * SigningOperationsTest.RsaNonUniqueParams
3264 *
3265 * Verifies that an operation with multiple padding modes is rejected.
3266 */
3267TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3269 .RsaSigningKey(2048, 65537)
3270 .Digest(Digest::NONE)
3271 .Digest(Digest::SHA1)
3272 .Authorization(TAG_NO_AUTH_REQUIRED)
3273 .Padding(PaddingMode::NONE)
3274 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3275 .SetDefaultValidity()));
3276
3277 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3278 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3279 .Digest(Digest::NONE)
3280 .Padding(PaddingMode::NONE)
3281 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3282
Tommy Chiuc93c4392021-05-11 18:36:50 +08003283 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3284 .Digest(Digest::NONE)
3285 .Digest(Digest::SHA1)
3286 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3287 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003288
3289 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3290 Begin(KeyPurpose::SIGN,
3291 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3292}
3293
3294/*
Selene Huang31ab4042020-04-29 04:22:39 -07003295 * SigningOperationsTest.RsaUnsupportedPadding
3296 *
3297 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3298 * with a padding mode inappropriate for RSA.
3299 */
3300TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3302 .RsaSigningKey(2048, 65537)
3303 .Authorization(TAG_NO_AUTH_REQUIRED)
3304 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003305 .Padding(PaddingMode::PKCS7)
3306 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003307 ASSERT_EQ(
3308 ErrorCode::UNSUPPORTED_PADDING_MODE,
3309 Begin(KeyPurpose::SIGN,
3310 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003311 CheckedDeleteKey();
3312
3313 ASSERT_EQ(ErrorCode::OK,
3314 GenerateKey(
3315 AuthorizationSetBuilder()
3316 .RsaSigningKey(2048, 65537)
3317 .Authorization(TAG_NO_AUTH_REQUIRED)
3318 .Digest(Digest::SHA_2_256 /* supported digest */)
3319 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3320 .SetDefaultValidity()));
3321 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3322 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3323 .Digest(Digest::SHA_2_256)
3324 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003325}
3326
3327/*
3328 * SigningOperationsTest.RsaPssNoDigest
3329 *
3330 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3331 */
3332TEST_P(SigningOperationsTest, RsaNoDigest) {
3333 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3334 .RsaSigningKey(2048, 65537)
3335 .Authorization(TAG_NO_AUTH_REQUIRED)
3336 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003337 .Padding(PaddingMode::RSA_PSS)
3338 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003339 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3340 Begin(KeyPurpose::SIGN,
3341 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3342
3343 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3344 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3345}
3346
3347/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003348 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003349 *
3350 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3351 * supported in some cases (as validated in other tests), but a mode must be specified.
3352 */
3353TEST_P(SigningOperationsTest, RsaNoPadding) {
3354 // Padding must be specified
3355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3356 .RsaKey(2048, 65537)
3357 .Authorization(TAG_NO_AUTH_REQUIRED)
3358 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003359 .Digest(Digest::NONE)
3360 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003361 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3362 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3363}
3364
3365/*
3366 * SigningOperationsTest.RsaShortMessage
3367 *
3368 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3369 */
3370TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3371 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3372 .Authorization(TAG_NO_AUTH_REQUIRED)
3373 .RsaSigningKey(2048, 65537)
3374 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003375 .Padding(PaddingMode::NONE)
3376 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003377
3378 // Barely shorter
3379 string message(2048 / 8 - 1, 'a');
3380 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3381
3382 // Much shorter
3383 message = "a";
3384 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3385}
3386
3387/*
3388 * SigningOperationsTest.RsaSignWithEncryptionKey
3389 *
3390 * Verifies that RSA encryption keys cannot be used to sign.
3391 */
3392TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3393 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3394 .Authorization(TAG_NO_AUTH_REQUIRED)
3395 .RsaEncryptionKey(2048, 65537)
3396 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003397 .Padding(PaddingMode::NONE)
3398 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003399 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3400 Begin(KeyPurpose::SIGN,
3401 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3402}
3403
3404/*
3405 * SigningOperationsTest.RsaSignTooLargeMessage
3406 *
3407 * Verifies that attempting a raw signature of a message which is the same length as the key,
3408 * but numerically larger than the public modulus, fails with the correct error.
3409 */
3410TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3411 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3412 .Authorization(TAG_NO_AUTH_REQUIRED)
3413 .RsaSigningKey(2048, 65537)
3414 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003415 .Padding(PaddingMode::NONE)
3416 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003417
3418 // Largest possible message will always be larger than the public modulus.
3419 string message(2048 / 8, static_cast<char>(0xff));
3420 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3421 .Authorization(TAG_NO_AUTH_REQUIRED)
3422 .Digest(Digest::NONE)
3423 .Padding(PaddingMode::NONE)));
3424 string signature;
3425 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3426}
3427
3428/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003429 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3430 *
David Drysdale42fe1892021-10-14 14:43:46 +01003431 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003432 */
3433TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003434 string message = "1234567890";
3435 string corrupt_message = "2234567890";
3436 for (auto curve : ValidCurves()) {
3437 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003438 // Ed25519 only allows Digest::NONE.
3439 auto digests = (curve == EcCurve::CURVE_25519)
3440 ? std::vector<Digest>(1, Digest::NONE)
3441 : ValidDigests(true /* withNone */, false /* withMD5 */);
3442
David Drysdaledf8f52e2021-05-06 08:10:58 +01003443 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3444 .Authorization(TAG_NO_AUTH_REQUIRED)
3445 .EcdsaSigningKey(curve)
3446 .Digest(digests)
3447 .SetDefaultValidity());
3448 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3449 if (error != ErrorCode::OK) {
3450 continue;
3451 }
3452
3453 for (auto digest : digests) {
3454 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3455 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3456 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3457 }
3458
3459 auto rc = DeleteKey();
3460 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3461 }
3462}
3463
3464/*
Selene Huang31ab4042020-04-29 04:22:39 -07003465 * SigningOperationsTest.EcdsaAllCurves
3466 *
David Drysdale42fe1892021-10-14 14:43:46 +01003467 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003468 */
3469TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3470 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003471 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3472 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003473 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3474 .Authorization(TAG_NO_AUTH_REQUIRED)
3475 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003476 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003477 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003478 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3479 if (error != ErrorCode::OK) continue;
3480
3481 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003482 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003483 CheckedDeleteKey();
3484 }
3485}
3486
3487/*
David Drysdale42fe1892021-10-14 14:43:46 +01003488 * SigningOperationsTest.EcdsaCurve25519
3489 *
3490 * Verifies that ECDSA operations succeed with curve25519.
3491 */
3492TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3493 if (!Curve25519Supported()) {
3494 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3495 }
3496
3497 EcCurve curve = EcCurve::CURVE_25519;
3498 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3499 .Authorization(TAG_NO_AUTH_REQUIRED)
3500 .EcdsaSigningKey(curve)
3501 .Digest(Digest::NONE)
3502 .SetDefaultValidity());
3503 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3504
3505 string message(1024, 'a');
3506 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3507 CheckedDeleteKey();
3508}
3509
3510/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003511 * SigningOperationsTest.EcdsaCurve25519MaxSize
3512 *
3513 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3514 */
3515TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3516 if (!Curve25519Supported()) {
3517 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3518 }
3519
3520 EcCurve curve = EcCurve::CURVE_25519;
3521 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3522 .Authorization(TAG_NO_AUTH_REQUIRED)
3523 .EcdsaSigningKey(curve)
3524 .Digest(Digest::NONE)
3525 .SetDefaultValidity());
3526 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3527
3528 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3529
3530 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3531 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3532 string message(msg_size, 'a');
3533
3534 // Attempt to sign via Begin+Finish.
3535 AuthorizationSet out_params;
3536 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3537 EXPECT_TRUE(out_params.empty());
3538 string signature;
3539 auto result = Finish(message, &signature);
3540 EXPECT_EQ(result, ErrorCode::OK);
3541 LocalVerifyMessage(message, signature, params);
3542
3543 // Attempt to sign via Begin+Update+Finish
3544 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3545 EXPECT_TRUE(out_params.empty());
3546 string output;
3547 result = Update(message, &output);
3548 EXPECT_EQ(result, ErrorCode::OK);
3549 EXPECT_EQ(output.size(), 0);
3550 string signature2;
3551 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3552 LocalVerifyMessage(message, signature2, params);
3553 }
3554
3555 CheckedDeleteKey();
3556}
3557
3558/*
3559 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3560 *
3561 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3562 */
3563TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3564 if (!Curve25519Supported()) {
3565 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3566 }
3567
3568 EcCurve curve = EcCurve::CURVE_25519;
3569 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3570 .Authorization(TAG_NO_AUTH_REQUIRED)
3571 .EcdsaSigningKey(curve)
3572 .Digest(Digest::NONE)
3573 .SetDefaultValidity());
3574 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3575
3576 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3577
3578 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3579 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3580 string message(msg_size, 'a');
3581
3582 // Attempt to sign via Begin+Finish.
3583 AuthorizationSet out_params;
3584 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3585 EXPECT_TRUE(out_params.empty());
3586 string signature;
3587 auto result = Finish(message, &signature);
3588 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3589
3590 // Attempt to sign via Begin+Update (but never get to Finish)
3591 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3592 EXPECT_TRUE(out_params.empty());
3593 string output;
3594 result = Update(message, &output);
3595 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3596 }
3597
3598 CheckedDeleteKey();
3599}
3600
3601/*
Selene Huang31ab4042020-04-29 04:22:39 -07003602 * SigningOperationsTest.EcdsaNoDigestHugeData
3603 *
3604 * Verifies that ECDSA operations support very large messages, even without digesting. This
3605 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3606 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3607 * the framework.
3608 */
3609TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3611 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003612 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003613 .Digest(Digest::NONE)
3614 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003615 string message(1 * 1024, 'a');
3616 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3617}
3618
3619/*
3620 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3621 *
3622 * Verifies that using an EC key requires the correct app ID/data.
3623 */
3624TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3626 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003627 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003628 .Digest(Digest::NONE)
3629 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003630 .Authorization(TAG_APPLICATION_DATA, "appdata")
3631 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003632
3633 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3634
Selene Huang31ab4042020-04-29 04:22:39 -07003635 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3636 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3637 AbortIfNeeded();
3638 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3639 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3640 .Digest(Digest::NONE)
3641 .Authorization(TAG_APPLICATION_ID, "clientid")));
3642 AbortIfNeeded();
3643 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3644 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3645 .Digest(Digest::NONE)
3646 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3647 AbortIfNeeded();
3648 EXPECT_EQ(ErrorCode::OK,
3649 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3650 .Digest(Digest::NONE)
3651 .Authorization(TAG_APPLICATION_DATA, "appdata")
3652 .Authorization(TAG_APPLICATION_ID, "clientid")));
3653 AbortIfNeeded();
3654}
3655
3656/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003657 * SigningOperationsTest.EcdsaIncompatibleDigest
3658 *
3659 * Verifies that using an EC key requires compatible digest.
3660 */
3661TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3662 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3663 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003664 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003665 .Digest(Digest::NONE)
3666 .Digest(Digest::SHA1)
3667 .SetDefaultValidity()));
3668 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3669 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3670 AbortIfNeeded();
3671}
3672
3673/*
Selene Huang31ab4042020-04-29 04:22:39 -07003674 * SigningOperationsTest.AesEcbSign
3675 *
3676 * Verifies that attempts to use AES keys to sign fail in the correct way.
3677 */
3678TEST_P(SigningOperationsTest, AesEcbSign) {
3679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3680 .Authorization(TAG_NO_AUTH_REQUIRED)
3681 .SigningKey()
3682 .AesEncryptionKey(128)
3683 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3684
3685 AuthorizationSet out_params;
3686 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3687 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3688 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3689 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3690}
3691
3692/*
3693 * SigningOperationsTest.HmacAllDigests
3694 *
3695 * Verifies that HMAC works with all digests.
3696 */
3697TEST_P(SigningOperationsTest, HmacAllDigests) {
3698 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003699 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3701 .Authorization(TAG_NO_AUTH_REQUIRED)
3702 .HmacKey(128)
3703 .Digest(digest)
3704 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3705 << "Failed to create HMAC key with digest " << digest;
3706 string message = "12345678901234567890123456789012";
3707 string signature = MacMessage(message, digest, 160);
3708 EXPECT_EQ(160U / 8U, signature.size())
3709 << "Failed to sign with HMAC key with digest " << digest;
3710 CheckedDeleteKey();
3711 }
3712}
3713
3714/*
3715 * SigningOperationsTest.HmacSha256TooLargeMacLength
3716 *
3717 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3718 * digest size.
3719 */
3720TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3722 .Authorization(TAG_NO_AUTH_REQUIRED)
3723 .HmacKey(128)
3724 .Digest(Digest::SHA_2_256)
3725 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3726 AuthorizationSet output_params;
3727 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3728 AuthorizationSetBuilder()
3729 .Digest(Digest::SHA_2_256)
3730 .Authorization(TAG_MAC_LENGTH, 264),
3731 &output_params));
3732}
3733
3734/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003735 * SigningOperationsTest.HmacSha256InvalidMacLength
3736 *
3737 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3738 * not a multiple of 8.
3739 */
3740TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3741 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3742 .Authorization(TAG_NO_AUTH_REQUIRED)
3743 .HmacKey(128)
3744 .Digest(Digest::SHA_2_256)
3745 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3746 AuthorizationSet output_params;
3747 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3748 AuthorizationSetBuilder()
3749 .Digest(Digest::SHA_2_256)
3750 .Authorization(TAG_MAC_LENGTH, 161),
3751 &output_params));
3752}
3753
3754/*
Selene Huang31ab4042020-04-29 04:22:39 -07003755 * SigningOperationsTest.HmacSha256TooSmallMacLength
3756 *
3757 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3758 * specified minimum MAC length.
3759 */
3760TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3761 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3762 .Authorization(TAG_NO_AUTH_REQUIRED)
3763 .HmacKey(128)
3764 .Digest(Digest::SHA_2_256)
3765 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3766 AuthorizationSet output_params;
3767 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3768 AuthorizationSetBuilder()
3769 .Digest(Digest::SHA_2_256)
3770 .Authorization(TAG_MAC_LENGTH, 120),
3771 &output_params));
3772}
3773
3774/*
3775 * SigningOperationsTest.HmacRfc4231TestCase3
3776 *
3777 * Validates against the test vectors from RFC 4231 test case 3.
3778 */
3779TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3780 string key(20, 0xaa);
3781 string message(50, 0xdd);
3782 uint8_t sha_224_expected[] = {
3783 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3784 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3785 };
3786 uint8_t sha_256_expected[] = {
3787 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3788 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3789 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3790 };
3791 uint8_t sha_384_expected[] = {
3792 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3793 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3794 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3795 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3796 };
3797 uint8_t sha_512_expected[] = {
3798 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3799 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3800 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3801 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3802 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3803 };
3804
3805 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3806 if (SecLevel() != SecurityLevel::STRONGBOX) {
3807 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3808 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3809 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3810 }
3811}
3812
3813/*
3814 * SigningOperationsTest.HmacRfc4231TestCase5
3815 *
3816 * Validates against the test vectors from RFC 4231 test case 5.
3817 */
3818TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3819 string key(20, 0x0c);
3820 string message = "Test With Truncation";
3821
3822 uint8_t sha_224_expected[] = {
3823 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3824 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3825 };
3826 uint8_t sha_256_expected[] = {
3827 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3828 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3829 };
3830 uint8_t sha_384_expected[] = {
3831 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3832 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3833 };
3834 uint8_t sha_512_expected[] = {
3835 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3836 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3837 };
3838
3839 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3840 if (SecLevel() != SecurityLevel::STRONGBOX) {
3841 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3842 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3843 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3844 }
3845}
3846
3847INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3848
3849typedef KeyMintAidlTestBase VerificationOperationsTest;
3850
3851/*
Selene Huang31ab4042020-04-29 04:22:39 -07003852 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3853 *
3854 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3855 */
3856TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3857 string key_material = "HelloThisIsAKey";
3858
3859 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003860 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003861 EXPECT_EQ(ErrorCode::OK,
3862 ImportKey(AuthorizationSetBuilder()
3863 .Authorization(TAG_NO_AUTH_REQUIRED)
3864 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3865 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3866 .Digest(Digest::SHA_2_256)
3867 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3868 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003869 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003870 EXPECT_EQ(ErrorCode::OK,
3871 ImportKey(AuthorizationSetBuilder()
3872 .Authorization(TAG_NO_AUTH_REQUIRED)
3873 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3874 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3875 .Digest(Digest::SHA_2_256)
3876 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3877 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003878 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003879
3880 string message = "This is a message.";
3881 string signature = SignMessage(
3882 signing_key, message,
3883 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3884
3885 // Signing key should not work.
3886 AuthorizationSet out_params;
3887 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3888 Begin(KeyPurpose::VERIFY, signing_key,
3889 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3890
3891 // Verification key should work.
3892 VerifyMessage(verification_key, message, signature,
3893 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003894}
3895
Prashant Patildec9fdc2021-12-08 15:25:47 +00003896/*
3897 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3898 *
3899 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3900 */
3901TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3902 string key_material = "HelloThisIsAKey";
3903
3904 vector<uint8_t> signing_key, verification_key;
3905 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3906 EXPECT_EQ(ErrorCode::OK,
3907 ImportKey(AuthorizationSetBuilder()
3908 .Authorization(TAG_NO_AUTH_REQUIRED)
3909 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3910 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3911 .Digest(Digest::SHA_2_256)
3912 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3913 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003914 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003915 EXPECT_EQ(ErrorCode::OK,
3916 ImportKey(AuthorizationSetBuilder()
3917 .Authorization(TAG_NO_AUTH_REQUIRED)
3918 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3919 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3920 .Digest(Digest::SHA_2_256)
3921 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3922 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003923 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003924
3925 string message = "This is a message.";
3926 string signature = SignMessage(
3927 signing_key, message,
3928 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3929
3930 AuthorizationSet begin_out_params;
3931 ASSERT_EQ(ErrorCode::OK,
3932 Begin(KeyPurpose::VERIFY, verification_key,
3933 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3934
3935 string corruptMessage = "This is b message."; // Corrupted message
3936 string output;
3937 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3938
3939 ASSERT_EQ(ErrorCode::OK,
3940 Begin(KeyPurpose::VERIFY, verification_key,
3941 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3942
3943 signature[0] += 1; // Corrupt a signature
3944 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003945}
3946
Selene Huang31ab4042020-04-29 04:22:39 -07003947INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3948
3949typedef KeyMintAidlTestBase ExportKeyTest;
3950
3951/*
3952 * ExportKeyTest.RsaUnsupportedKeyFormat
3953 *
3954 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3955 */
3956// TODO(seleneh) add ExportKey to GenerateKey
3957// check result
3958
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003959class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003960 public:
3961 template <TagType tag_type, Tag tag, typename ValueT>
3962 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3963 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003964 for (auto& entry : key_characteristics_) {
3965 if (entry.securityLevel == SecLevel()) {
3966 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3967 << "Tag " << tag << " with value " << expected
3968 << " not found at security level" << entry.securityLevel;
3969 } else {
3970 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3971 << "Tag " << tag << " found at security level " << entry.securityLevel;
3972 }
Selene Huang31ab4042020-04-29 04:22:39 -07003973 }
3974 }
3975
3976 void CheckOrigin() {
3977 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003978 // Origin isn't a crypto param, but it always lives with them.
3979 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003980 }
3981};
3982
3983/*
3984 * ImportKeyTest.RsaSuccess
3985 *
3986 * Verifies that importing and using an RSA key pair works correctly.
3987 */
3988TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003989 uint32_t key_size;
3990 string key;
3991
3992 if (SecLevel() == SecurityLevel::STRONGBOX) {
3993 key_size = 2048;
3994 key = rsa_2048_key;
3995 } else {
3996 key_size = 1024;
3997 key = rsa_key;
3998 }
3999
Selene Huang31ab4042020-04-29 04:22:39 -07004000 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4001 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004002 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004003 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004004 .Padding(PaddingMode::RSA_PSS)
4005 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004006 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004007
4008 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004009 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004010 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4011 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4012 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4013 CheckOrigin();
4014
4015 string message(1024 / 8, 'a');
4016 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4017 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004018 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004019}
4020
4021/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004022 * ImportKeyTest.RsaSuccessWithoutParams
4023 *
4024 * Verifies that importing and using an RSA key pair without specifying parameters
4025 * works correctly.
4026 */
4027TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4028 uint32_t key_size;
4029 string key;
4030
4031 if (SecLevel() == SecurityLevel::STRONGBOX) {
4032 key_size = 2048;
4033 key = rsa_2048_key;
4034 } else {
4035 key_size = 1024;
4036 key = rsa_key;
4037 }
4038
4039 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4040 .Authorization(TAG_NO_AUTH_REQUIRED)
4041 .SigningKey()
4042 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4043 .Digest(Digest::SHA_2_256)
4044 .Padding(PaddingMode::RSA_PSS)
4045 .SetDefaultValidity(),
4046 KeyFormat::PKCS8, key));
4047
4048 // Key size and public exponent are determined from the imported key material.
4049 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4050 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4051
4052 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4053 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4054 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4055 CheckOrigin();
4056
4057 string message(1024 / 8, 'a');
4058 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4059 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004060 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004061}
4062
4063/*
Selene Huang31ab4042020-04-29 04:22:39 -07004064 * ImportKeyTest.RsaKeySizeMismatch
4065 *
4066 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4067 * correct way.
4068 */
4069TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4070 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4071 ImportKey(AuthorizationSetBuilder()
4072 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4073 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004074 .Padding(PaddingMode::NONE)
4075 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004076 KeyFormat::PKCS8, rsa_key));
4077}
4078
4079/*
4080 * ImportKeyTest.RsaPublicExponentMismatch
4081 *
4082 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4083 * fails in the correct way.
4084 */
4085TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4086 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4087 ImportKey(AuthorizationSetBuilder()
4088 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4089 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004090 .Padding(PaddingMode::NONE)
4091 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004092 KeyFormat::PKCS8, rsa_key));
4093}
4094
4095/*
David Drysdalee60248c2021-10-04 12:54:13 +01004096 * ImportKeyTest.RsaAttestMultiPurposeFail
4097 *
4098 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4099 */
4100TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004101 if (AidlVersion() < 2) {
4102 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4103 // with other key purposes. However, this was not checked at the time
4104 // so we can only be strict about checking this for implementations of KeyMint
4105 // version 2 and above.
4106 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4107 }
David Drysdalee60248c2021-10-04 12:54:13 +01004108 uint32_t key_size = 2048;
4109 string key = rsa_2048_key;
4110
4111 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4112 ImportKey(AuthorizationSetBuilder()
4113 .Authorization(TAG_NO_AUTH_REQUIRED)
4114 .RsaSigningKey(key_size, 65537)
4115 .AttestKey()
4116 .Digest(Digest::SHA_2_256)
4117 .Padding(PaddingMode::RSA_PSS)
4118 .SetDefaultValidity(),
4119 KeyFormat::PKCS8, key));
4120}
4121
4122/*
Selene Huang31ab4042020-04-29 04:22:39 -07004123 * ImportKeyTest.EcdsaSuccess
4124 *
4125 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4126 */
4127TEST_P(ImportKeyTest, EcdsaSuccess) {
4128 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4129 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004130 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004131 .Digest(Digest::SHA_2_256)
4132 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004133 KeyFormat::PKCS8, ec_256_key));
4134
4135 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004136 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4137 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4138
4139 CheckOrigin();
4140
4141 string message(32, 'a');
4142 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4143 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004144 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004145}
4146
4147/*
4148 * ImportKeyTest.EcdsaP256RFC5915Success
4149 *
4150 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4151 * correctly.
4152 */
4153TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4154 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4155 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004156 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004157 .Digest(Digest::SHA_2_256)
4158 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004159 KeyFormat::PKCS8, ec_256_key_rfc5915));
4160
4161 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004162 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4163 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4164
4165 CheckOrigin();
4166
4167 string message(32, 'a');
4168 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4169 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004170 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004171}
4172
4173/*
4174 * ImportKeyTest.EcdsaP256SEC1Success
4175 *
4176 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4177 */
4178TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4179 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4180 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004181 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004182 .Digest(Digest::SHA_2_256)
4183 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004184 KeyFormat::PKCS8, ec_256_key_sec1));
4185
4186 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004187 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4188 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4189
4190 CheckOrigin();
4191
4192 string message(32, 'a');
4193 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4194 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004195 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004196}
4197
4198/*
4199 * ImportKeyTest.Ecdsa521Success
4200 *
4201 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4202 */
4203TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004204 if (SecLevel() == SecurityLevel::STRONGBOX) {
4205 GTEST_SKIP() << "Test not applicable to StrongBox device";
4206 }
Selene Huang31ab4042020-04-29 04:22:39 -07004207 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4208 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004209 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004210 .Digest(Digest::SHA_2_256)
4211 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004212 KeyFormat::PKCS8, ec_521_key));
4213
4214 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004215 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4216 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4217 CheckOrigin();
4218
4219 string message(32, 'a');
4220 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4221 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004222 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004223}
4224
4225/*
Selene Huang31ab4042020-04-29 04:22:39 -07004226 * ImportKeyTest.EcdsaCurveMismatch
4227 *
4228 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4229 * the correct way.
4230 */
4231TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4232 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4233 ImportKey(AuthorizationSetBuilder()
4234 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004235 .Digest(Digest::NONE)
4236 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004237 KeyFormat::PKCS8, ec_256_key));
4238}
4239
4240/*
David Drysdalee60248c2021-10-04 12:54:13 +01004241 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4242 *
4243 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4244 */
4245TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004246 if (AidlVersion() < 2) {
4247 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4248 // with other key purposes. However, this was not checked at the time
4249 // so we can only be strict about checking this for implementations of KeyMint
4250 // version 2 and above.
4251 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4252 }
David Drysdalee60248c2021-10-04 12:54:13 +01004253 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4254 ImportKey(AuthorizationSetBuilder()
4255 .Authorization(TAG_NO_AUTH_REQUIRED)
4256 .EcdsaSigningKey(EcCurve::P_256)
4257 .AttestKey()
4258 .Digest(Digest::SHA_2_256)
4259 .SetDefaultValidity(),
4260 KeyFormat::PKCS8, ec_256_key));
4261}
4262
4263/*
David Drysdale42fe1892021-10-14 14:43:46 +01004264 * ImportKeyTest.Ed25519RawSuccess
4265 *
4266 * Verifies that importing and using a raw Ed25519 private key works correctly.
4267 */
4268TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4269 if (!Curve25519Supported()) {
4270 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4271 }
4272
4273 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4274 .Authorization(TAG_NO_AUTH_REQUIRED)
4275 .EcdsaSigningKey(EcCurve::CURVE_25519)
4276 .Digest(Digest::NONE)
4277 .SetDefaultValidity(),
4278 KeyFormat::RAW, ed25519_key));
4279 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4280 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4281 CheckOrigin();
4282
4283 // The returned cert should hold the correct public key.
4284 ASSERT_GT(cert_chain_.size(), 0);
4285 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4286 ASSERT_NE(kmKeyCert, nullptr);
4287 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4288 ASSERT_NE(kmPubKey.get(), nullptr);
4289 size_t kmPubKeySize = 32;
4290 uint8_t kmPubKeyData[32];
4291 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4292 ASSERT_EQ(kmPubKeySize, 32);
4293 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4294
4295 string message(32, 'a');
4296 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4297 string signature = SignMessage(message, params);
4298 LocalVerifyMessage(message, signature, params);
4299}
4300
4301/*
4302 * ImportKeyTest.Ed25519Pkcs8Success
4303 *
4304 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4305 */
4306TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4307 if (!Curve25519Supported()) {
4308 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4309 }
4310
4311 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4312 .Authorization(TAG_NO_AUTH_REQUIRED)
4313 .EcdsaSigningKey(EcCurve::CURVE_25519)
4314 .Digest(Digest::NONE)
4315 .SetDefaultValidity(),
4316 KeyFormat::PKCS8, ed25519_pkcs8_key));
4317 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4318 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4319 CheckOrigin();
4320
4321 // The returned cert should hold the correct public key.
4322 ASSERT_GT(cert_chain_.size(), 0);
4323 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4324 ASSERT_NE(kmKeyCert, nullptr);
4325 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4326 ASSERT_NE(kmPubKey.get(), nullptr);
4327 size_t kmPubKeySize = 32;
4328 uint8_t kmPubKeyData[32];
4329 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4330 ASSERT_EQ(kmPubKeySize, 32);
4331 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4332
4333 string message(32, 'a');
4334 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4335 string signature = SignMessage(message, params);
4336 LocalVerifyMessage(message, signature, params);
4337}
4338
4339/*
4340 * ImportKeyTest.Ed25519CurveMismatch
4341 *
4342 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4343 * the correct way.
4344 */
4345TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4346 if (!Curve25519Supported()) {
4347 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4348 }
4349
4350 ASSERT_NE(ErrorCode::OK,
4351 ImportKey(AuthorizationSetBuilder()
4352 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4353 .Digest(Digest::NONE)
4354 .SetDefaultValidity(),
4355 KeyFormat::RAW, ed25519_key));
4356}
4357
4358/*
4359 * ImportKeyTest.Ed25519FormatMismatch
4360 *
4361 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4362 */
4363TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4364 if (!Curve25519Supported()) {
4365 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4366 }
4367
4368 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4369 .EcdsaSigningKey(EcCurve::CURVE_25519)
4370 .Digest(Digest::NONE)
4371 .SetDefaultValidity(),
4372 KeyFormat::PKCS8, ed25519_key));
4373 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4374 .EcdsaSigningKey(EcCurve::CURVE_25519)
4375 .Digest(Digest::NONE)
4376 .SetDefaultValidity(),
4377 KeyFormat::RAW, ed25519_pkcs8_key));
4378}
4379
4380/*
4381 * ImportKeyTest.Ed25519PurposeMismatch
4382 *
4383 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4384 */
4385TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4386 if (!Curve25519Supported()) {
4387 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4388 }
4389
4390 // Can't have both SIGN and ATTEST_KEY
4391 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4392 .EcdsaSigningKey(EcCurve::CURVE_25519)
4393 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4394 .Digest(Digest::NONE)
4395 .SetDefaultValidity(),
4396 KeyFormat::RAW, ed25519_key));
4397 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4398 // PKCS#8 format and so includes an OID).
4399 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4400 .EcdsaKey(EcCurve::CURVE_25519)
4401 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4402 .Digest(Digest::NONE)
4403 .SetDefaultValidity(),
4404 KeyFormat::PKCS8, ed25519_pkcs8_key));
4405}
4406
4407/*
4408 * ImportKeyTest.X25519RawSuccess
4409 *
4410 * Verifies that importing and using a raw X25519 private key works correctly.
4411 */
4412TEST_P(ImportKeyTest, X25519RawSuccess) {
4413 if (!Curve25519Supported()) {
4414 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4415 }
4416
4417 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4418 .Authorization(TAG_NO_AUTH_REQUIRED)
4419 .EcdsaKey(EcCurve::CURVE_25519)
4420 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4421 .SetDefaultValidity(),
4422 KeyFormat::RAW, x25519_key));
4423
4424 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4425 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4426 CheckOrigin();
4427}
4428
4429/*
4430 * ImportKeyTest.X25519Pkcs8Success
4431 *
4432 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4433 */
4434TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4435 if (!Curve25519Supported()) {
4436 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4437 }
4438
4439 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4440 .Authorization(TAG_NO_AUTH_REQUIRED)
4441 .EcdsaKey(EcCurve::CURVE_25519)
4442 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4443 .SetDefaultValidity(),
4444 KeyFormat::PKCS8, x25519_pkcs8_key));
4445
4446 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4447 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4448 CheckOrigin();
4449}
4450
4451/*
4452 * ImportKeyTest.X25519CurveMismatch
4453 *
4454 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4455 * the correct way.
4456 */
4457TEST_P(ImportKeyTest, X25519CurveMismatch) {
4458 if (!Curve25519Supported()) {
4459 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4460 }
4461
4462 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4463 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4464 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4465 .SetDefaultValidity(),
4466 KeyFormat::RAW, x25519_key));
4467}
4468
4469/*
4470 * ImportKeyTest.X25519FormatMismatch
4471 *
4472 * Verifies that importing an X25519 key with an invalid format fails.
4473 */
4474TEST_P(ImportKeyTest, X25519FormatMismatch) {
4475 if (!Curve25519Supported()) {
4476 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4477 }
4478
4479 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4480 .EcdsaKey(EcCurve::CURVE_25519)
4481 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4482 .SetDefaultValidity(),
4483 KeyFormat::PKCS8, x25519_key));
4484 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4485 .EcdsaKey(EcCurve::CURVE_25519)
4486 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4487 .SetDefaultValidity(),
4488 KeyFormat::RAW, x25519_pkcs8_key));
4489}
4490
4491/*
4492 * ImportKeyTest.X25519PurposeMismatch
4493 *
4494 * Verifies that importing an X25519 key pair with an invalid format fails.
4495 */
4496TEST_P(ImportKeyTest, X25519PurposeMismatch) {
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::CURVE_25519)
4503 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4504 .SetDefaultValidity(),
4505 KeyFormat::PKCS8, x25519_pkcs8_key));
4506 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4507 .EcdsaSigningKey(EcCurve::CURVE_25519)
4508 .SetDefaultValidity(),
4509 KeyFormat::PKCS8, x25519_pkcs8_key));
4510}
4511
4512/*
Selene Huang31ab4042020-04-29 04:22:39 -07004513 * ImportKeyTest.AesSuccess
4514 *
4515 * Verifies that importing and using an AES key works.
4516 */
4517TEST_P(ImportKeyTest, AesSuccess) {
4518 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4519 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4520 .Authorization(TAG_NO_AUTH_REQUIRED)
4521 .AesEncryptionKey(key.size() * 8)
4522 .EcbMode()
4523 .Padding(PaddingMode::PKCS7),
4524 KeyFormat::RAW, key));
4525
4526 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4527 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4528 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4529 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4530 CheckOrigin();
4531
4532 string message = "Hello World!";
4533 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4534 string ciphertext = EncryptMessage(message, params);
4535 string plaintext = DecryptMessage(ciphertext, params);
4536 EXPECT_EQ(message, plaintext);
4537}
4538
4539/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004540 * ImportKeyTest.AesFailure
4541 *
4542 * Verifies that importing an invalid AES key fails.
4543 */
4544TEST_P(ImportKeyTest, AesFailure) {
4545 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4546 uint32_t bitlen = key.size() * 8;
4547 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004548 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004549 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004550 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004551 .Authorization(TAG_NO_AUTH_REQUIRED)
4552 .AesEncryptionKey(key_size)
4553 .EcbMode()
4554 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004555 KeyFormat::RAW, key);
4556 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004557 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4558 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004559 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004560
4561 // Explicit key size matches that of the provided key, but it's not a valid size.
4562 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4563 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4564 ImportKey(AuthorizationSetBuilder()
4565 .Authorization(TAG_NO_AUTH_REQUIRED)
4566 .AesEncryptionKey(long_key.size() * 8)
4567 .EcbMode()
4568 .Padding(PaddingMode::PKCS7),
4569 KeyFormat::RAW, long_key));
4570 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4571 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4572 ImportKey(AuthorizationSetBuilder()
4573 .Authorization(TAG_NO_AUTH_REQUIRED)
4574 .AesEncryptionKey(short_key.size() * 8)
4575 .EcbMode()
4576 .Padding(PaddingMode::PKCS7),
4577 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004578}
4579
4580/*
4581 * ImportKeyTest.TripleDesSuccess
4582 *
4583 * Verifies that importing and using a 3DES key works.
4584 */
4585TEST_P(ImportKeyTest, TripleDesSuccess) {
4586 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4587 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4588 .Authorization(TAG_NO_AUTH_REQUIRED)
4589 .TripleDesEncryptionKey(168)
4590 .EcbMode()
4591 .Padding(PaddingMode::PKCS7),
4592 KeyFormat::RAW, key));
4593
4594 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4595 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4596 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4597 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4598 CheckOrigin();
4599
4600 string message = "Hello World!";
4601 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4602 string ciphertext = EncryptMessage(message, params);
4603 string plaintext = DecryptMessage(ciphertext, params);
4604 EXPECT_EQ(message, plaintext);
4605}
4606
4607/*
4608 * ImportKeyTest.TripleDesFailure
4609 *
4610 * Verifies that importing an invalid 3DES key fails.
4611 */
4612TEST_P(ImportKeyTest, TripleDesFailure) {
4613 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004614 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004615 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004616 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004617 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004618 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004619 .Authorization(TAG_NO_AUTH_REQUIRED)
4620 .TripleDesEncryptionKey(key_size)
4621 .EcbMode()
4622 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004623 KeyFormat::RAW, key);
4624 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004625 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4626 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004627 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004628 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004629 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004630 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4631 ImportKey(AuthorizationSetBuilder()
4632 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004633 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004634 .EcbMode()
4635 .Padding(PaddingMode::PKCS7),
4636 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004637 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004638 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4639 ImportKey(AuthorizationSetBuilder()
4640 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004641 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004642 .EcbMode()
4643 .Padding(PaddingMode::PKCS7),
4644 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004645}
4646
4647/*
4648 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004649 *
4650 * Verifies that importing and using an HMAC key works.
4651 */
4652TEST_P(ImportKeyTest, HmacKeySuccess) {
4653 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4654 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4655 .Authorization(TAG_NO_AUTH_REQUIRED)
4656 .HmacKey(key.size() * 8)
4657 .Digest(Digest::SHA_2_256)
4658 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4659 KeyFormat::RAW, key));
4660
4661 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4662 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4663 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4664 CheckOrigin();
4665
4666 string message = "Hello World!";
4667 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4668 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4669}
4670
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004671/*
4672 * ImportKeyTest.GetKeyCharacteristics
4673 *
4674 * Verifies that imported keys have the correct characteristics.
4675 */
4676TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4677 vector<uint8_t> key_blob;
4678 vector<KeyCharacteristics> key_characteristics;
4679 auto base_builder = AuthorizationSetBuilder()
4680 .Padding(PaddingMode::NONE)
4681 .Authorization(TAG_NO_AUTH_REQUIRED)
4682 .SetDefaultValidity();
4683 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4684 Algorithm::TRIPLE_DES};
4685 ErrorCode result;
4686 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4687 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4688 for (auto alg : algorithms) {
4689 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4690 AuthorizationSetBuilder builder(base_builder);
4691 switch (alg) {
4692 case Algorithm::RSA:
4693 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4694
4695 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4696 &key_characteristics);
4697 break;
4698 case Algorithm::EC:
4699 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4700 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4701 &key_characteristics);
4702 break;
4703 case Algorithm::HMAC:
4704 builder.HmacKey(128)
4705 .Digest(Digest::SHA_2_256)
4706 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4707 result =
4708 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4709 break;
4710 case Algorithm::AES:
4711 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4712 result =
4713 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4714 break;
4715 case Algorithm::TRIPLE_DES:
4716 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4717 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4718 &key_characteristics);
4719 break;
4720 default:
4721 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4722 continue;
4723 }
4724 ASSERT_EQ(ErrorCode::OK, result);
4725 CheckCharacteristics(key_blob, key_characteristics);
4726 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4727 }
4728}
4729
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004730/*
4731 * ImportKeyTest.RsaOaepMGFDigestSuccess
4732 *
4733 * Include MGF-Digest explicitly in import key authorization list.
4734 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4735 * should have the correct characteristics.
4736 */
4737TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
4738 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4739 size_t key_size = 2048;
4740
4741 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4742 .OaepMGFDigest(mgf_digests)
4743 .Authorization(TAG_NO_AUTH_REQUIRED)
4744 .RsaEncryptionKey(key_size, 65537)
4745 .Digest(Digest::SHA_2_256)
4746 .Padding(PaddingMode::RSA_OAEP)
4747 .SetDefaultValidity(),
4748 KeyFormat::PKCS8, rsa_2048_key));
4749
4750 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4751 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4752 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4753 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4754 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4755 CheckOrigin();
4756
4757 // Make sure explicitly specified mgf-digests exist in key characteristics.
4758 assert_mgf_digests_present_in_key_characteristics(key_characteristics_, mgf_digests);
4759
4760 string message = "Hello";
4761
4762 for (auto digest : mgf_digests) {
4763 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4764 auto params = AuthorizationSetBuilder()
4765 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4766 .Digest(Digest::SHA_2_256)
4767 .Padding(PaddingMode::RSA_OAEP);
4768 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4769 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4770 EXPECT_EQ(key_size / 8, ciphertext1.size());
4771
4772 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4773 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4774 EXPECT_EQ(key_size / 8, ciphertext2.size());
4775
4776 // OAEP randomizes padding so every result should be different (with astronomically high
4777 // probability).
4778 EXPECT_NE(ciphertext1, ciphertext2);
4779
4780 string plaintext1 = DecryptMessage(ciphertext1, params);
4781 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4782 string plaintext2 = DecryptMessage(ciphertext2, params);
4783 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4784
4785 // Decrypting corrupted ciphertext should fail.
4786 size_t offset_to_corrupt = ciphertext1.size() - 1;
4787 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4788 ciphertext1[offset_to_corrupt] = corrupt_byte;
4789
4790 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4791 string result;
4792 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4793 EXPECT_EQ(0U, result.size());
4794 }
4795}
4796
4797/*
4798 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4799 *
4800 * Don't specify MGF-Digest explicitly in import key authorization list.
4801 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4802 * verify that imported key should have the correct characteristics. Default
4803 * mgf-digest shouldn't be included in key charecteristics.
4804 */
4805TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4806 size_t key_size = 2048;
4807 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4808 .Authorization(TAG_NO_AUTH_REQUIRED)
4809 .RsaEncryptionKey(key_size, 65537)
4810 .Digest(Digest::SHA_2_256)
4811 .Padding(PaddingMode::RSA_OAEP)
4812 .SetDefaultValidity(),
4813 KeyFormat::PKCS8, rsa_2048_key));
4814
4815 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4816 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4817 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4818 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4819 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4820 CheckOrigin();
4821
4822 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
4823 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
4824}
4825
Selene Huang31ab4042020-04-29 04:22:39 -07004826INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4827
4828auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004829 // IKeyMintDevice.aidl
4830 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4831 "020100" // INTEGER length 1 value 0x00 (version)
4832 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4833 "934bf94e2aa28a3f83c9f79297250262"
4834 "fbe3276b5a1c91159bbfa3ef8957aac8"
4835 "4b59b30b455a79c2973480823d8b3863"
4836 "c3deef4a8e243590268d80e18751a0e1"
4837 "30f67ce6a1ace9f79b95e097474febc9"
4838 "81195b1d13a69086c0863f66a7b7fdb4"
4839 "8792227b1ac5e2489febdf087ab54864"
4840 "83033a6f001ca5d1ec1e27f5c30f4cec"
4841 "2642074a39ae68aee552e196627a8e3d"
4842 "867e67a8c01b11e75f13cca0a97ab668"
4843 "b50cda07a8ecb7cd8e3dd7009c963653"
4844 "4f6f239cffe1fc8daa466f78b676c711"
4845 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4846 "99b801597d5220e307eaa5bee507fb94"
4847 "d1fa69f9e519b2de315bac92c36f2ea1"
4848 "fa1df4478c0ddedeae8c70e0233cd098"
4849 "040c" // OCTET STRING length 0x0c (initializationVector)
4850 "d796b02c370f1fa4cc0124f1"
4851 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4852 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4853 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4854 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4855 "3106" // SET length 0x06
4856 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4857 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4858 // } end SET
4859 // } end [1]
4860 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4861 "020120" // INTEGER length 1 value 0x20 (AES)
4862 // } end [2]
4863 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4864 "02020100" // INTEGER length 2 value 0x100
4865 // } end [3]
4866 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4867 "3103" // SET length 0x03 {
4868 "020101" // INTEGER length 1 value 0x01 (ECB)
4869 // } end SET
4870 // } end [4]
4871 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4872 "3103" // SET length 0x03 {
4873 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4874 // } end SET
4875 // } end [5]
4876 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4877 // (noAuthRequired)
4878 "0500" // NULL
4879 // } end [503]
4880 // } end SEQUENCE (AuthorizationList)
4881 // } end SEQUENCE (KeyDescription)
4882 "0420" // OCTET STRING length 0x20 (encryptedKey)
4883 "ccd540855f833a5e1480bfd2d36faf3a"
4884 "eee15df5beabe2691bc82dde2a7aa910"
4885 "0410" // OCTET STRING length 0x10 (tag)
4886 "64c9f689c60ff6223ab6e6999e0eb6e5"
4887 // } SEQUENCE (SecureKeyWrapper)
4888);
Selene Huang31ab4042020-04-29 04:22:39 -07004889
4890auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004891 // IKeyMintDevice.aidl
4892 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4893 "020100" // INTEGER length 1 value 0x00 (version)
4894 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4895 "aad93ed5924f283b4bb5526fbe7a1412"
4896 "f9d9749ec30db9062b29e574a8546f33"
4897 "c88732452f5b8e6a391ee76c39ed1712"
4898 "c61d8df6213dec1cffbc17a8c6d04c7b"
4899 "30893d8daa9b2015213e219468215532"
4900 "07f8f9931c4caba23ed3bee28b36947e"
4901 "47f10e0a5c3dc51c988a628daad3e5e1"
4902 "f4005e79c2d5a96c284b4b8d7e4948f3"
4903 "31e5b85dd5a236f85579f3ea1d1b8484"
4904 "87470bdb0ab4f81a12bee42c99fe0df4"
4905 "bee3759453e69ad1d68a809ce06b949f"
4906 "7694a990429b2fe81e066ff43e56a216"
4907 "02db70757922a4bcc23ab89f1e35da77"
4908 "586775f423e519c2ea394caf48a28d0c"
4909 "8020f1dcf6b3a68ec246f615ae96dae9"
4910 "a079b1f6eb959033c1af5c125fd94168"
4911 "040c" // OCTET STRING length 0x0c (initializationVector)
4912 "6d9721d08589581ab49204a3"
4913 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4914 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4915 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4916 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4917 "3106" // SET length 0x06
4918 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4919 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4920 // } end SET
4921 // } end [1]
4922 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4923 "020120" // INTEGER length 1 value 0x20 (AES)
4924 // } end [2]
4925 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4926 "02020100" // INTEGER length 2 value 0x100
4927 // } end [3]
4928 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4929 "3103" // SET length 0x03 {
4930 "020101" // INTEGER length 1 value 0x01 (ECB)
4931 // } end SET
4932 // } end [4]
4933 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4934 "3103" // SET length 0x03 {
4935 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4936 // } end SET
4937 // } end [5]
4938 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4939 // (noAuthRequired)
4940 "0500" // NULL
4941 // } end [503]
4942 // } end SEQUENCE (AuthorizationList)
4943 // } end SEQUENCE (KeyDescription)
4944 "0420" // OCTET STRING length 0x20 (encryptedKey)
4945 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4946 "c20d1f99a9a024a76f35c8e2cab9b68d"
4947 "0410" // OCTET STRING length 0x10 (tag)
4948 "2560c70109ae67c030f00b98b512a670"
4949 // } SEQUENCE (SecureKeyWrapper)
4950);
Selene Huang31ab4042020-04-29 04:22:39 -07004951
4952auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004953 // RFC 5208 s5
4954 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4955 "020100" // INTEGER length 1 value 0x00 (version)
4956 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4957 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4958 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4959 "0500" // NULL (parameters)
4960 // } SEQUENCE (AlgorithmIdentifier)
4961 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4962 // RFC 8017 A.1.2
4963 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4964 "020100" // INTEGER length 1 value 0x00 (version)
4965 "02820101" // INTEGER length 0x0101 (modulus) value...
4966 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4967 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4968 "7b06e673a837313d56b1c725150a3fef" // 0x30
4969 "86acbddc41bb759c2854eae32d35841e" // 0x40
4970 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4971 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4972 "312d7bd5921ffaea1347c157406fef71" // 0x70
4973 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4974 "f4645c11f5c1374c3886427411c44979" // 0x90
4975 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4976 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4977 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4978 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4979 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4980 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4981 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4982 "55" // 0x101
4983 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4984 "02820100" // INTEGER length 0x100 (privateExponent) value...
4985 "431447b6251908112b1ee76f99f3711a" // 0x10
4986 "52b6630960046c2de70de188d833f8b8" // 0x20
4987 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4988 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4989 "e710b630a03adc683b5d2c43080e52be" // 0x50
4990 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4991 "822bccff087d63c940ba8a45f670feb2" // 0x70
4992 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4993 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4994 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4995 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4996 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4997 "52659d5a5ba05b663737a8696281865b" // 0xd0
4998 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4999 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
5000 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5001 "028181" // INTEGER length 0x81 (prime1) value...
5002 "00de392e18d682c829266cc3454e1d61" // 0x10
5003 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5004 "ff841be5bac82a164c5970007047b8c5" // 0x30
5005 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5006 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5007 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5008 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5009 "9e91346130748a6e3c124f9149d71c74" // 0x80
5010 "35"
5011 "028181" // INTEGER length 0x81 (prime2) value...
5012 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5013 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5014 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5015 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5016 "9ed39a2d934c880440aed8832f984316" // 0x50
5017 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5018 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5019 "b880677c068e1be936e81288815252a8" // 0x80
5020 "a1"
5021 "028180" // INTEGER length 0x80 (exponent1) value...
5022 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5023 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5024 "5a063212a4f105a3764743e53281988a" // 0x30
5025 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5026 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5027 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5028 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5029 "4719d6e2b9439823719cd08bcd031781" // 0x80
5030 "028181" // INTEGER length 0x81 (exponent2) value...
5031 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5032 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5033 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5034 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5035 "1254186af30b22c10582a8a43e34fe94" // 0x50
5036 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5037 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5038 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5039 "61"
5040 "028181" // INTEGER length 0x81 (coefficient) value...
5041 "00c931617c77829dfb1270502be9195c" // 0x10
5042 "8f2830885f57dba869536811e6864236" // 0x20
5043 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5044 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5045 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5046 "959356210723287b0affcc9f727044d4" // 0x60
5047 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5048 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5049 "22"
5050 // } SEQUENCE
5051 // } SEQUENCE ()
5052);
Selene Huang31ab4042020-04-29 04:22:39 -07005053
5054string zero_masking_key =
5055 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5056string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5057
5058class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5059
5060TEST_P(ImportWrappedKeyTest, Success) {
5061 auto wrapping_key_desc = AuthorizationSetBuilder()
5062 .RsaEncryptionKey(2048, 65537)
5063 .Digest(Digest::SHA_2_256)
5064 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005065 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5066 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005067
5068 ASSERT_EQ(ErrorCode::OK,
5069 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5070 AuthorizationSetBuilder()
5071 .Digest(Digest::SHA_2_256)
5072 .Padding(PaddingMode::RSA_OAEP)));
5073
5074 string message = "Hello World!";
5075 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5076 string ciphertext = EncryptMessage(message, params);
5077 string plaintext = DecryptMessage(ciphertext, params);
5078 EXPECT_EQ(message, plaintext);
5079}
5080
David Drysdaled2cc8c22021-04-15 13:29:45 +01005081/*
5082 * ImportWrappedKeyTest.SuccessSidsIgnored
5083 *
5084 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5085 * include Tag:USER_SECURE_ID.
5086 */
5087TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5088 auto wrapping_key_desc = AuthorizationSetBuilder()
5089 .RsaEncryptionKey(2048, 65537)
5090 .Digest(Digest::SHA_2_256)
5091 .Padding(PaddingMode::RSA_OAEP)
5092 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5093 .SetDefaultValidity();
5094
5095 int64_t password_sid = 42;
5096 int64_t biometric_sid = 24;
5097 ASSERT_EQ(ErrorCode::OK,
5098 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5099 AuthorizationSetBuilder()
5100 .Digest(Digest::SHA_2_256)
5101 .Padding(PaddingMode::RSA_OAEP),
5102 password_sid, biometric_sid));
5103
5104 string message = "Hello World!";
5105 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5106 string ciphertext = EncryptMessage(message, params);
5107 string plaintext = DecryptMessage(ciphertext, params);
5108 EXPECT_EQ(message, plaintext);
5109}
5110
Selene Huang31ab4042020-04-29 04:22:39 -07005111TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5112 auto wrapping_key_desc = AuthorizationSetBuilder()
5113 .RsaEncryptionKey(2048, 65537)
5114 .Digest(Digest::SHA_2_256)
5115 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005116 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5117 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005118
5119 ASSERT_EQ(ErrorCode::OK,
5120 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5121 AuthorizationSetBuilder()
5122 .Digest(Digest::SHA_2_256)
5123 .Padding(PaddingMode::RSA_OAEP)));
5124}
5125
5126TEST_P(ImportWrappedKeyTest, WrongMask) {
5127 auto wrapping_key_desc = AuthorizationSetBuilder()
5128 .RsaEncryptionKey(2048, 65537)
5129 .Digest(Digest::SHA_2_256)
5130 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005131 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5132 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005133
5134 ASSERT_EQ(
5135 ErrorCode::VERIFICATION_FAILED,
5136 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5137 AuthorizationSetBuilder()
5138 .Digest(Digest::SHA_2_256)
5139 .Padding(PaddingMode::RSA_OAEP)));
5140}
5141
5142TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5143 auto wrapping_key_desc = AuthorizationSetBuilder()
5144 .RsaEncryptionKey(2048, 65537)
5145 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005146 .Padding(PaddingMode::RSA_OAEP)
5147 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005148
5149 ASSERT_EQ(
5150 ErrorCode::INCOMPATIBLE_PURPOSE,
5151 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5152 AuthorizationSetBuilder()
5153 .Digest(Digest::SHA_2_256)
5154 .Padding(PaddingMode::RSA_OAEP)));
5155}
5156
David Drysdaled2cc8c22021-04-15 13:29:45 +01005157TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5158 auto wrapping_key_desc = AuthorizationSetBuilder()
5159 .RsaEncryptionKey(2048, 65537)
5160 .Digest(Digest::SHA_2_256)
5161 .Padding(PaddingMode::RSA_PSS)
5162 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5163 .SetDefaultValidity();
5164
5165 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5166 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5167 AuthorizationSetBuilder()
5168 .Digest(Digest::SHA_2_256)
5169 .Padding(PaddingMode::RSA_OAEP)));
5170}
5171
5172TEST_P(ImportWrappedKeyTest, WrongDigest) {
5173 auto wrapping_key_desc = AuthorizationSetBuilder()
5174 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005175 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005176 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005177 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5178 .SetDefaultValidity();
5179
5180 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5181 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5182 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005183 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005184 .Padding(PaddingMode::RSA_OAEP)));
5185}
5186
Selene Huang31ab4042020-04-29 04:22:39 -07005187INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5188
5189typedef KeyMintAidlTestBase EncryptionOperationsTest;
5190
5191/*
5192 * EncryptionOperationsTest.RsaNoPaddingSuccess
5193 *
David Drysdale59cae642021-05-12 13:52:03 +01005194 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005195 */
5196TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005197 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005198 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005199 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5200 .Authorization(TAG_NO_AUTH_REQUIRED)
5201 .RsaEncryptionKey(2048, exponent)
5202 .Padding(PaddingMode::NONE)
5203 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005204
David Drysdaled2cc8c22021-04-15 13:29:45 +01005205 string message = string(2048 / 8, 'a');
5206 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005207 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005208 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005209
David Drysdale59cae642021-05-12 13:52:03 +01005210 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005211 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005212
David Drysdaled2cc8c22021-04-15 13:29:45 +01005213 // Unpadded RSA is deterministic
5214 EXPECT_EQ(ciphertext1, ciphertext2);
5215
5216 CheckedDeleteKey();
5217 }
Selene Huang31ab4042020-04-29 04:22:39 -07005218}
5219
5220/*
5221 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5222 *
David Drysdale59cae642021-05-12 13:52:03 +01005223 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005224 */
5225TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5226 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5227 .Authorization(TAG_NO_AUTH_REQUIRED)
5228 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005229 .Padding(PaddingMode::NONE)
5230 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005231
5232 string message = "1";
5233 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5234
David Drysdale59cae642021-05-12 13:52:03 +01005235 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005236 EXPECT_EQ(2048U / 8, ciphertext.size());
5237
5238 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5239 string plaintext = DecryptMessage(ciphertext, params);
5240
5241 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005242}
5243
5244/*
Selene Huang31ab4042020-04-29 04:22:39 -07005245 * EncryptionOperationsTest.RsaOaepSuccess
5246 *
David Drysdale59cae642021-05-12 13:52:03 +01005247 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005248 */
5249TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5250 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005251 auto mgf_digest = Digest::SHA1;
Selene Huang31ab4042020-04-29 04:22:39 -07005252
5253 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005254 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5255 .Authorization(TAG_NO_AUTH_REQUIRED)
5256 .RsaEncryptionKey(key_size, 65537)
5257 .Padding(PaddingMode::RSA_OAEP)
5258 .Digest(digests)
5259 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5260 .SetDefaultValidity()));
5261
5262 // Make sure explicitly specified mgf-digest exist in key characteristics.
5263 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
Selene Huang31ab4042020-04-29 04:22:39 -07005264
5265 string message = "Hello";
5266
5267 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005268 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5269
5270 auto params = AuthorizationSetBuilder()
5271 .Digest(digest)
5272 .Padding(PaddingMode::RSA_OAEP)
5273 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5274 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005275 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5276 EXPECT_EQ(key_size / 8, ciphertext1.size());
5277
David Drysdale59cae642021-05-12 13:52:03 +01005278 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005279 EXPECT_EQ(key_size / 8, ciphertext2.size());
5280
5281 // OAEP randomizes padding so every result should be different (with astronomically high
5282 // probability).
5283 EXPECT_NE(ciphertext1, ciphertext2);
5284
5285 string plaintext1 = DecryptMessage(ciphertext1, params);
5286 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5287 string plaintext2 = DecryptMessage(ciphertext2, params);
5288 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5289
5290 // Decrypting corrupted ciphertext should fail.
5291 size_t offset_to_corrupt = random() % ciphertext1.size();
5292 char corrupt_byte;
5293 do {
5294 corrupt_byte = static_cast<char>(random() % 256);
5295 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5296 ciphertext1[offset_to_corrupt] = corrupt_byte;
5297
5298 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5299 string result;
5300 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5301 EXPECT_EQ(0U, result.size());
5302 }
5303}
5304
5305/*
5306 * EncryptionOperationsTest.RsaOaepInvalidDigest
5307 *
David Drysdale59cae642021-05-12 13:52:03 +01005308 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005309 * without a digest.
5310 */
5311TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5312 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5313 .Authorization(TAG_NO_AUTH_REQUIRED)
5314 .RsaEncryptionKey(2048, 65537)
5315 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005316 .Digest(Digest::NONE)
5317 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005318
5319 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005320 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005321}
5322
5323/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005324 * EncryptionOperationsTest.RsaOaepInvalidPadding
5325 *
David Drysdale59cae642021-05-12 13:52:03 +01005326 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005327 * with a padding value that is only suitable for signing/verifying.
5328 */
5329TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5331 .Authorization(TAG_NO_AUTH_REQUIRED)
5332 .RsaEncryptionKey(2048, 65537)
5333 .Padding(PaddingMode::RSA_PSS)
5334 .Digest(Digest::NONE)
5335 .SetDefaultValidity()));
5336
5337 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005338 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005339}
5340
5341/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005342 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005343 *
David Drysdale59cae642021-05-12 13:52:03 +01005344 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005345 * with a different digest than was used to encrypt.
5346 */
5347TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005348 if (SecLevel() == SecurityLevel::STRONGBOX) {
5349 GTEST_SKIP() << "Test not applicable to StrongBox device";
5350 }
Selene Huang31ab4042020-04-29 04:22:39 -07005351
5352 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5353 .Authorization(TAG_NO_AUTH_REQUIRED)
5354 .RsaEncryptionKey(1024, 65537)
5355 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005356 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5357 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005358 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005359 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005360 message,
5361 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5362
5363 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5364 .Digest(Digest::SHA_2_256)
5365 .Padding(PaddingMode::RSA_OAEP)));
5366 string result;
5367 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5368 EXPECT_EQ(0U, result.size());
5369}
5370
5371/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005372 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5373 *
David Drysdale59cae642021-05-12 13:52:03 +01005374 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005375 * digests.
5376 */
5377TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5378 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5379
5380 size_t key_size = 2048; // Need largish key for SHA-512 test.
5381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5382 .OaepMGFDigest(digests)
5383 .Authorization(TAG_NO_AUTH_REQUIRED)
5384 .RsaEncryptionKey(key_size, 65537)
5385 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005386 .Digest(Digest::SHA_2_256)
5387 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005388
Shawn Willden20732262023-04-21 16:36:00 -06005389 std::vector<Digest> mgf1DigestsInAuths;
5390 mgf1DigestsInAuths.reserve(digests.size());
5391 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5392 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5393 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5394 KeyParameterValue value = param.value;
5395 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5396 }
5397 });
5398
5399 std::sort(digests.begin(), digests.end());
5400 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5401 EXPECT_EQ(digests, mgf1DigestsInAuths);
5402
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005403 string message = "Hello";
5404
5405 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005406 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005407 auto params = AuthorizationSetBuilder()
5408 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5409 .Digest(Digest::SHA_2_256)
5410 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005411 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005412 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5413 EXPECT_EQ(key_size / 8, ciphertext1.size());
5414
David Drysdale59cae642021-05-12 13:52:03 +01005415 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005416 EXPECT_EQ(key_size / 8, ciphertext2.size());
5417
5418 // OAEP randomizes padding so every result should be different (with astronomically high
5419 // probability).
5420 EXPECT_NE(ciphertext1, ciphertext2);
5421
5422 string plaintext1 = DecryptMessage(ciphertext1, params);
5423 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5424 string plaintext2 = DecryptMessage(ciphertext2, params);
5425 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5426
5427 // Decrypting corrupted ciphertext should fail.
5428 size_t offset_to_corrupt = random() % ciphertext1.size();
5429 char corrupt_byte;
5430 do {
5431 corrupt_byte = static_cast<char>(random() % 256);
5432 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5433 ciphertext1[offset_to_corrupt] = corrupt_byte;
5434
5435 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5436 string result;
5437 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5438 EXPECT_EQ(0U, result.size());
5439 }
5440}
5441
5442/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005443 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5444 *
5445 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5446 * specified, defaulting to SHA-1.
5447 */
5448TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5449 size_t key_size = 2048;
5450 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5451 .Authorization(TAG_NO_AUTH_REQUIRED)
5452 .RsaEncryptionKey(key_size, 65537)
5453 .Padding(PaddingMode::RSA_OAEP)
5454 .Digest(Digest::SHA_2_256)
5455 .SetDefaultValidity()));
5456
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005457 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
5458 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
5459
David Drysdaleae3727b2021-11-11 09:00:14 +00005460 // Do local RSA encryption using the default MGF digest of SHA-1.
5461 string message = "Hello";
5462 auto params =
5463 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5464 string ciphertext = LocalRsaEncryptMessage(message, params);
5465 EXPECT_EQ(key_size / 8, ciphertext.size());
5466
5467 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5468 string plaintext = DecryptMessage(ciphertext, params);
5469 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5470
5471 // Decrypting corrupted ciphertext should fail.
5472 size_t offset_to_corrupt = random() % ciphertext.size();
5473 char corrupt_byte;
5474 do {
5475 corrupt_byte = static_cast<char>(random() % 256);
5476 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5477 ciphertext[offset_to_corrupt] = corrupt_byte;
5478
5479 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5480 string result;
5481 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5482 EXPECT_EQ(0U, result.size());
5483}
5484
5485/*
5486 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5487 *
5488 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5489 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5490 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5491 */
5492TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5493 size_t key_size = 2048;
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005494 auto mgf_digest = Digest::SHA_2_256;
5495 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5496 .Authorization(TAG_NO_AUTH_REQUIRED)
5497 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5498 .RsaEncryptionKey(key_size, 65537)
5499 .Padding(PaddingMode::RSA_OAEP)
5500 .Digest(Digest::SHA_2_256)
5501 .SetDefaultValidity()));
5502
5503 // Make sure explicitly specified mgf-digest exist in key characteristics.
5504 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5505 // Make sure default mgf-digest is not included in key characteristics.
5506 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
David Drysdaleae3727b2021-11-11 09:00:14 +00005507
5508 // Do local RSA encryption using the default MGF digest of SHA-1.
5509 string message = "Hello";
5510 auto params =
5511 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5512 string ciphertext = LocalRsaEncryptMessage(message, params);
5513 EXPECT_EQ(key_size / 8, ciphertext.size());
5514
5515 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5516 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5517 // is checked against those values, and found absent.
5518 auto result = Begin(KeyPurpose::DECRYPT, params);
5519 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5520 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5521}
5522
5523/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005524 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5525 *
David Drysdale59cae642021-05-12 13:52:03 +01005526 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005527 * with incompatible MGF digest.
5528 */
5529TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005530 auto mgf_digest = Digest::SHA_2_256;
5531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5532 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5533 .Authorization(TAG_NO_AUTH_REQUIRED)
5534 .RsaEncryptionKey(2048, 65537)
5535 .Padding(PaddingMode::RSA_OAEP)
5536 .Digest(Digest::SHA_2_256)
5537 .SetDefaultValidity()));
5538 // Make sure explicitly specified mgf-digest exist in key characteristics.
5539 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5540
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005541 string message = "Hello World!";
5542
5543 auto params = AuthorizationSetBuilder()
5544 .Padding(PaddingMode::RSA_OAEP)
5545 .Digest(Digest::SHA_2_256)
5546 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005547 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005548}
5549
5550/*
5551 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5552 *
5553 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5554 * with unsupported MGF digest.
5555 */
5556TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005557 auto mgf_digest = Digest::SHA_2_256;
5558 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5559 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5560 .Authorization(TAG_NO_AUTH_REQUIRED)
5561 .RsaEncryptionKey(2048, 65537)
5562 .Padding(PaddingMode::RSA_OAEP)
5563 .Digest(Digest::SHA_2_256)
5564 .SetDefaultValidity()));
5565 // Make sure explicitly specified mgf-digest exist in key characteristics.
5566 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5567
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005568 string message = "Hello World!";
5569
5570 auto params = AuthorizationSetBuilder()
5571 .Padding(PaddingMode::RSA_OAEP)
5572 .Digest(Digest::SHA_2_256)
5573 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005574 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005575}
5576
5577/*
Selene Huang31ab4042020-04-29 04:22:39 -07005578 * EncryptionOperationsTest.RsaPkcs1Success
5579 *
5580 * Verifies that RSA PKCS encryption/decrypts works.
5581 */
5582TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5583 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5584 .Authorization(TAG_NO_AUTH_REQUIRED)
5585 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005586 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5587 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005588
5589 string message = "Hello World!";
5590 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005591 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005592 EXPECT_EQ(2048U / 8, ciphertext1.size());
5593
David Drysdale59cae642021-05-12 13:52:03 +01005594 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005595 EXPECT_EQ(2048U / 8, ciphertext2.size());
5596
5597 // PKCS1 v1.5 randomizes padding so every result should be different.
5598 EXPECT_NE(ciphertext1, ciphertext2);
5599
5600 string plaintext = DecryptMessage(ciphertext1, params);
5601 EXPECT_EQ(message, plaintext);
5602
5603 // Decrypting corrupted ciphertext should fail.
5604 size_t offset_to_corrupt = random() % ciphertext1.size();
5605 char corrupt_byte;
5606 do {
5607 corrupt_byte = static_cast<char>(random() % 256);
5608 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5609 ciphertext1[offset_to_corrupt] = corrupt_byte;
5610
5611 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5612 string result;
5613 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5614 EXPECT_EQ(0U, result.size());
5615}
5616
5617/*
Selene Huang31ab4042020-04-29 04:22:39 -07005618 * EncryptionOperationsTest.EcdsaEncrypt
5619 *
5620 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5621 */
5622TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5624 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005625 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005626 .Digest(Digest::NONE)
5627 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005628 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5629 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5630 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5631}
5632
5633/*
5634 * EncryptionOperationsTest.HmacEncrypt
5635 *
5636 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5637 */
5638TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5639 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5640 .Authorization(TAG_NO_AUTH_REQUIRED)
5641 .HmacKey(128)
5642 .Digest(Digest::SHA_2_256)
5643 .Padding(PaddingMode::NONE)
5644 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5645 auto params = AuthorizationSetBuilder()
5646 .Digest(Digest::SHA_2_256)
5647 .Padding(PaddingMode::NONE)
5648 .Authorization(TAG_MAC_LENGTH, 128);
5649 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5650 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5651}
5652
5653/*
5654 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5655 *
5656 * Verifies that AES ECB mode works.
5657 */
5658TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5659 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5660 .Authorization(TAG_NO_AUTH_REQUIRED)
5661 .AesEncryptionKey(128)
5662 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5663 .Padding(PaddingMode::NONE)));
5664
5665 ASSERT_GT(key_blob_.size(), 0U);
5666 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5667
5668 // Two-block message.
5669 string message = "12345678901234567890123456789012";
5670 string ciphertext1 = EncryptMessage(message, params);
5671 EXPECT_EQ(message.size(), ciphertext1.size());
5672
5673 string ciphertext2 = EncryptMessage(string(message), params);
5674 EXPECT_EQ(message.size(), ciphertext2.size());
5675
5676 // ECB is deterministic.
5677 EXPECT_EQ(ciphertext1, ciphertext2);
5678
5679 string plaintext = DecryptMessage(ciphertext1, params);
5680 EXPECT_EQ(message, plaintext);
5681}
5682
5683/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005684 * EncryptionOperationsTest.AesEcbUnknownTag
5685 *
5686 * Verifies that AES ECB operations ignore unknown tags.
5687 */
5688TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5689 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5690 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5691 KeyParameter unknown_param;
5692 unknown_param.tag = unknown_tag;
5693
5694 vector<KeyCharacteristics> key_characteristics;
5695 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5696 .Authorization(TAG_NO_AUTH_REQUIRED)
5697 .AesEncryptionKey(128)
5698 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5699 .Padding(PaddingMode::NONE)
5700 .Authorization(unknown_param),
5701 &key_blob_, &key_characteristics));
5702 ASSERT_GT(key_blob_.size(), 0U);
5703
5704 // Unknown tags should not be returned in key characteristics.
5705 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5706 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5707 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5708 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5709
5710 // Encrypt without mentioning the unknown parameter.
5711 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5712 string message = "12345678901234567890123456789012";
5713 string ciphertext = EncryptMessage(message, params);
5714 EXPECT_EQ(message.size(), ciphertext.size());
5715
5716 // Decrypt including the unknown parameter.
5717 auto decrypt_params = AuthorizationSetBuilder()
5718 .BlockMode(BlockMode::ECB)
5719 .Padding(PaddingMode::NONE)
5720 .Authorization(unknown_param);
5721 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5722 EXPECT_EQ(message, plaintext);
5723}
5724
5725/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005726 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005727 *
5728 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5729 */
5730TEST_P(EncryptionOperationsTest, AesWrongMode) {
5731 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5732 .Authorization(TAG_NO_AUTH_REQUIRED)
5733 .AesEncryptionKey(128)
5734 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5735 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005736 ASSERT_GT(key_blob_.size(), 0U);
5737
Selene Huang31ab4042020-04-29 04:22:39 -07005738 EXPECT_EQ(
5739 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5740 Begin(KeyPurpose::ENCRYPT,
5741 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5742}
5743
5744/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005745 * EncryptionOperationsTest.AesWrongPadding
5746 *
5747 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5748 */
5749TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5751 .Authorization(TAG_NO_AUTH_REQUIRED)
5752 .AesEncryptionKey(128)
5753 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5754 .Padding(PaddingMode::NONE)));
5755 ASSERT_GT(key_blob_.size(), 0U);
5756
5757 EXPECT_EQ(
5758 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5759 Begin(KeyPurpose::ENCRYPT,
5760 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5761}
5762
5763/*
5764 * EncryptionOperationsTest.AesInvalidParams
5765 *
5766 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5767 */
5768TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5770 .Authorization(TAG_NO_AUTH_REQUIRED)
5771 .AesEncryptionKey(128)
5772 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5773 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5774 .Padding(PaddingMode::NONE)
5775 .Padding(PaddingMode::PKCS7)));
5776 ASSERT_GT(key_blob_.size(), 0U);
5777
5778 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5779 .BlockMode(BlockMode::CBC)
5780 .BlockMode(BlockMode::ECB)
5781 .Padding(PaddingMode::NONE));
5782 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5783 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5784
5785 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5786 .BlockMode(BlockMode::ECB)
5787 .Padding(PaddingMode::NONE)
5788 .Padding(PaddingMode::PKCS7));
5789 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5790 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5791}
5792
5793/*
Selene Huang31ab4042020-04-29 04:22:39 -07005794 * EncryptionOperationsTest.AesWrongPurpose
5795 *
5796 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5797 * specified.
5798 */
5799TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5800 auto err = GenerateKey(AuthorizationSetBuilder()
5801 .Authorization(TAG_NO_AUTH_REQUIRED)
5802 .AesKey(128)
5803 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5804 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5805 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5806 .Padding(PaddingMode::NONE));
5807 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5808 ASSERT_GT(key_blob_.size(), 0U);
5809
5810 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5811 .BlockMode(BlockMode::GCM)
5812 .Padding(PaddingMode::NONE)
5813 .Authorization(TAG_MAC_LENGTH, 128));
5814 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5815
5816 CheckedDeleteKey();
5817
5818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5819 .Authorization(TAG_NO_AUTH_REQUIRED)
5820 .AesKey(128)
5821 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5822 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5823 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5824 .Padding(PaddingMode::NONE)));
5825
5826 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5827 .BlockMode(BlockMode::GCM)
5828 .Padding(PaddingMode::NONE)
5829 .Authorization(TAG_MAC_LENGTH, 128));
5830 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5831}
5832
5833/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005834 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005835 *
5836 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5837 * multiple of the block size and no padding is specified.
5838 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005839TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5840 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005841 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005842 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5843 .Authorization(TAG_NO_AUTH_REQUIRED)
5844 .AesEncryptionKey(128)
5845 .Authorization(TAG_BLOCK_MODE, blockMode)
5846 .Padding(PaddingMode::NONE)));
5847 // Message is slightly shorter than two blocks.
5848 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005849
David Drysdaled2cc8c22021-04-15 13:29:45 +01005850 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5851 AuthorizationSet out_params;
5852 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5853 string ciphertext;
5854 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5855 EXPECT_EQ(0U, ciphertext.size());
5856
5857 CheckedDeleteKey();
5858 }
Selene Huang31ab4042020-04-29 04:22:39 -07005859}
5860
5861/*
5862 * EncryptionOperationsTest.AesEcbPkcs7Padding
5863 *
5864 * Verifies that AES PKCS7 padding works for any message length.
5865 */
5866TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5867 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5868 .Authorization(TAG_NO_AUTH_REQUIRED)
5869 .AesEncryptionKey(128)
5870 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5871 .Padding(PaddingMode::PKCS7)));
5872
5873 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5874
5875 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005876 for (size_t i = 0; i <= 48; i++) {
5877 SCOPED_TRACE(testing::Message() << "i = " << i);
5878 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5879 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005880 string ciphertext = EncryptMessage(message, params);
5881 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5882 string plaintext = DecryptMessage(ciphertext, params);
5883 EXPECT_EQ(message, plaintext);
5884 }
5885}
5886
5887/*
5888 * EncryptionOperationsTest.AesEcbWrongPadding
5889 *
5890 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5891 * specified.
5892 */
5893TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5894 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5895 .Authorization(TAG_NO_AUTH_REQUIRED)
5896 .AesEncryptionKey(128)
5897 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5898 .Padding(PaddingMode::NONE)));
5899
5900 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5901
5902 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005903 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005904 string message(i, 'a');
5905 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5906 }
5907}
5908
5909/*
5910 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5911 *
5912 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5913 */
5914TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5916 .Authorization(TAG_NO_AUTH_REQUIRED)
5917 .AesEncryptionKey(128)
5918 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5919 .Padding(PaddingMode::PKCS7)));
5920
5921 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5922
5923 string message = "a";
5924 string ciphertext = EncryptMessage(message, params);
5925 EXPECT_EQ(16U, ciphertext.size());
5926 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005927
Seth Moore7a55ae32021-06-23 14:28:11 -07005928 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5929 ++ciphertext[ciphertext.size() / 2];
5930
5931 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5932 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005933 ErrorCode error = Finish(ciphertext, &plaintext);
5934 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005935 // This is the expected error, we can exit the test now.
5936 return;
5937 } else {
5938 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005939 ASSERT_EQ(error, ErrorCode::OK)
5940 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005941 }
5942 }
5943 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005944}
5945
David Drysdaleb8093292022-04-08 12:22:35 +01005946/*
5947 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5948 *
5949 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5950 */
5951TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5952 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5953 .Authorization(TAG_NO_AUTH_REQUIRED)
5954 .AesEncryptionKey(128)
5955 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5956 .Padding(PaddingMode::PKCS7)));
5957
5958 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5959
5960 string message = "a";
5961 string ciphertext = EncryptMessage(message, params);
5962 EXPECT_EQ(16U, ciphertext.size());
5963 EXPECT_NE(ciphertext, message);
5964
5965 // Shorten the ciphertext.
5966 ciphertext.resize(ciphertext.size() - 1);
5967 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5968 string plaintext;
5969 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5970}
5971
Selene Huang31ab4042020-04-29 04:22:39 -07005972vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5973 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005974 EXPECT_TRUE(iv);
5975 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005976}
5977
5978/*
5979 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5980 *
5981 * Verifies that AES CTR mode works.
5982 */
5983TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5985 .Authorization(TAG_NO_AUTH_REQUIRED)
5986 .AesEncryptionKey(128)
5987 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5988 .Padding(PaddingMode::NONE)));
5989
5990 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5991
5992 string message = "123";
5993 AuthorizationSet out_params;
5994 string ciphertext1 = EncryptMessage(message, params, &out_params);
5995 vector<uint8_t> iv1 = CopyIv(out_params);
5996 EXPECT_EQ(16U, iv1.size());
5997
5998 EXPECT_EQ(message.size(), ciphertext1.size());
5999
6000 out_params.Clear();
6001 string ciphertext2 = EncryptMessage(message, params, &out_params);
6002 vector<uint8_t> iv2 = CopyIv(out_params);
6003 EXPECT_EQ(16U, iv2.size());
6004
6005 // IVs should be random, so ciphertexts should differ.
6006 EXPECT_NE(ciphertext1, ciphertext2);
6007
6008 auto params_iv1 =
6009 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6010 auto params_iv2 =
6011 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6012
6013 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6014 EXPECT_EQ(message, plaintext);
6015 plaintext = DecryptMessage(ciphertext2, params_iv2);
6016 EXPECT_EQ(message, plaintext);
6017
6018 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6019 plaintext = DecryptMessage(ciphertext1, params_iv2);
6020 EXPECT_NE(message, plaintext);
6021 plaintext = DecryptMessage(ciphertext2, params_iv1);
6022 EXPECT_NE(message, plaintext);
6023}
6024
6025/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306026 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006027 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306028 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006029 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306030TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6031 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6032}
Selene Huang31ab4042020-04-29 04:22:39 -07006033
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306034/*
6035 * EncryptionOperationsTest.AesCbcIncremental
6036 *
6037 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6038 */
6039TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6040 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6041}
Selene Huang31ab4042020-04-29 04:22:39 -07006042
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306043/*
6044 * EncryptionOperationsTest.AesCtrIncremental
6045 *
6046 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6047 */
6048TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6049 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6050}
Selene Huang31ab4042020-04-29 04:22:39 -07006051
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306052/*
6053 * EncryptionOperationsTest.AesGcmIncremental
6054 *
6055 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6056 */
6057TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6058 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006059}
6060
Prashant Patildd5f7f02022-07-06 18:58:07 +00006061/*
6062 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6063 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6064 */
6065TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6066 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6067 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6068 string kat_plaintext =
6069 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6070 "809FFF37081C22EF278F896AB213A2A631");
6071 string kat_ciphertext =
6072 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6073 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6074 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6075 kat_ciphertext);
6076}
6077
6078/*
6079 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6080 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6081 */
6082TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6083 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6084 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6085 string kat_plaintext =
6086 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6087 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6088 string kat_ciphertext =
6089 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6090 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6091 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6092 kat_plaintext, kat_ciphertext);
6093}
6094
6095/*
6096 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6097 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6098 */
6099TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6100 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6101 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6102 string kat_plaintext =
6103 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6104 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6105 string kat_ciphertext =
6106 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6107 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6108 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6109 kat_ciphertext);
6110}
6111
6112/*
6113 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6114 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6115 */
6116TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6117 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6118 string kat_plaintext =
6119 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6120 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6121 string kat_ciphertext =
6122 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6123 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6124 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6125 kat_ciphertext);
6126}
6127
6128/*
6129 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6130 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6131 */
6132TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6133 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6134 string kat_plaintext =
6135 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6136 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6137 string kat_ciphertext =
6138 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6139 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6140 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6141 kat_ciphertext);
6142}
6143
6144/*
6145 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6146 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6147 */
6148TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6149 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6150 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6151 string kat_plaintext =
6152 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6153 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6154 string kat_ciphertext =
6155 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6156 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6157 "bdfcc0cba0");
6158
6159 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6160 kat_ciphertext);
6161}
6162
6163/*
6164 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6165 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6166 */
6167TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6168 if (SecLevel() == SecurityLevel::STRONGBOX) {
6169 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6170 }
6171 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6172 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6173 string kat_plaintext =
6174 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6175 "167f2497c994bd496eb80bfb2ba2c9d5af");
6176 string kat_ciphertext =
6177 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6178 "72c134552f3a138e726fbe493b3a839598");
6179 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6180 kat_ciphertext);
6181}
6182
6183/*
6184 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6185 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6186 */
6187TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6188 if (SecLevel() == SecurityLevel::STRONGBOX) {
6189 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6190 }
6191 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6192 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6193 string kat_plaintext =
6194 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6195 "b170");
6196 string kat_ciphertext =
6197 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6198 "4e3884138ff403a41fd99818708ada301c");
6199 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6200 kat_plaintext, kat_ciphertext);
6201}
6202
6203/*
6204 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6205 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6206 */
6207TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6208 if (SecLevel() == SecurityLevel::STRONGBOX) {
6209 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6210 }
6211 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6212 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6213 string kat_plaintext =
6214 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6215 "28091e09cdbbd3b42b");
6216 string kat_ciphertext =
6217 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6218 "2ae0f90f0c19f42b4a");
6219 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6220 kat_ciphertext);
6221}
6222
6223/*
6224 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6225 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6226 */
6227TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6228 if (SecLevel() == SecurityLevel::STRONGBOX) {
6229 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6230 }
6231 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6232 string kat_plaintext =
6233 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6234 "44ab");
6235 string kat_ciphertext =
6236 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6237 "2453");
6238 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6239 kat_ciphertext);
6240}
6241
6242/*
6243 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6244 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6245 */
6246TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6247 if (SecLevel() == SecurityLevel::STRONGBOX) {
6248 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6249 }
6250 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6251 string kat_plaintext =
6252 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6253 "e2c7");
6254 string kat_ciphertext =
6255 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6256 "bb7e3a889dd4a9589098b44acf1056e7aa");
6257 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6258 kat_ciphertext);
6259}
6260
6261/*
6262 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6263 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6264 */
6265TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6266 if (SecLevel() == SecurityLevel::STRONGBOX) {
6267 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6268 }
6269 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6270 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6271 string kat_plaintext =
6272 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6273 "ff52");
6274 string kat_ciphertext =
6275 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6276 "1413ad70fb0e1970669095ad77ebb5974ae8");
6277
6278 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6279 kat_ciphertext);
6280}
6281
6282/*
6283 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6284 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6285 */
6286TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6287 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6288 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6289 string kat_plaintext =
6290 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6291 "494cb53caca353e4b637ba05687be20f8d");
6292 string kat_ciphertext =
6293 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6294 "6047da1e4fd7c4e1cf2656097f75ae8685");
6295 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6296 kat_ciphertext);
6297}
6298
6299/*
6300 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6301 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6302 */
6303TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6304 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6305 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6306 string kat_plaintext =
6307 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6308 "2545a82b73c48078b9dae62261c65909");
6309 string kat_ciphertext =
6310 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6311 "9403a71987b95124073d69f2a3cb95b0ab");
6312 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6313 kat_plaintext, kat_ciphertext);
6314}
6315
6316/*
6317 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6318 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6319 */
6320TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6321 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6322 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6323 string kat_plaintext =
6324 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6325 "1f6db3c884");
6326 string kat_ciphertext =
6327 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6328 "a7be30d4c3");
6329 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6330 kat_ciphertext);
6331}
6332
6333/*
6334 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6335 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6336 */
6337TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6338 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6339 string kat_plaintext =
6340 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6341 "31a476d6806b8116089c6ec50bb543200f");
6342 string kat_ciphertext =
6343 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6344 "c83e377faf246288931136bef2a07c0be4");
6345 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6346 kat_ciphertext);
6347}
6348
6349/*
6350 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6351 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6352 */
6353TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6354 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6355 string kat_plaintext =
6356 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6357 "6f");
6358 string kat_ciphertext =
6359 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6360 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6361 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6362 kat_ciphertext);
6363}
6364
6365/*
6366 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6367 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6368 */
6369TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6370 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6371 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6372 string kat_plaintext =
6373 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6374 "f0");
6375 string kat_ciphertext =
6376 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6377 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6378
6379 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6380 kat_ciphertext);
6381}
6382
Selene Huang31ab4042020-04-29 04:22:39 -07006383struct AesCtrSp80038aTestVector {
6384 const char* key;
6385 const char* nonce;
6386 const char* plaintext;
6387 const char* ciphertext;
6388};
6389
6390// These test vectors are taken from
6391// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6392static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6393 // AES-128
6394 {
6395 "2b7e151628aed2a6abf7158809cf4f3c",
6396 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6397 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6398 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6399 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6400 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6401 },
6402 // AES-192
6403 {
6404 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6405 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6406 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6407 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6408 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6409 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6410 },
6411 // AES-256
6412 {
6413 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6414 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6415 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6416 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6417 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6418 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6419 },
6420};
6421
6422/*
6423 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6424 *
6425 * Verifies AES CTR implementation against SP800-38A test vectors.
6426 */
6427TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6428 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6429 for (size_t i = 0; i < 3; i++) {
6430 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6431 const string key = hex2str(test.key);
6432 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6433 InvalidSizes.end())
6434 continue;
6435 const string nonce = hex2str(test.nonce);
6436 const string plaintext = hex2str(test.plaintext);
6437 const string ciphertext = hex2str(test.ciphertext);
6438 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6439 }
6440}
6441
6442/*
6443 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6444 *
6445 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6446 */
6447TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6448 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6449 .Authorization(TAG_NO_AUTH_REQUIRED)
6450 .AesEncryptionKey(128)
6451 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6452 .Padding(PaddingMode::PKCS7)));
6453 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6454 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6455}
6456
6457/*
6458 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6459 *
6460 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6461 */
6462TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6464 .Authorization(TAG_NO_AUTH_REQUIRED)
6465 .AesEncryptionKey(128)
6466 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6467 .Authorization(TAG_CALLER_NONCE)
6468 .Padding(PaddingMode::NONE)));
6469
6470 auto params = AuthorizationSetBuilder()
6471 .BlockMode(BlockMode::CTR)
6472 .Padding(PaddingMode::NONE)
6473 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6474 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6475
6476 params = AuthorizationSetBuilder()
6477 .BlockMode(BlockMode::CTR)
6478 .Padding(PaddingMode::NONE)
6479 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6480 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6481
6482 params = AuthorizationSetBuilder()
6483 .BlockMode(BlockMode::CTR)
6484 .Padding(PaddingMode::NONE)
6485 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6486 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6487}
6488
6489/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006490 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006491 *
6492 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6493 */
6494TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6495 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6496 .Authorization(TAG_NO_AUTH_REQUIRED)
6497 .AesEncryptionKey(128)
6498 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6499 .Padding(PaddingMode::NONE)));
6500 // Two-block message.
6501 string message = "12345678901234567890123456789012";
6502 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6503 AuthorizationSet out_params;
6504 string ciphertext1 = EncryptMessage(message, params, &out_params);
6505 vector<uint8_t> iv1 = CopyIv(out_params);
6506 EXPECT_EQ(message.size(), ciphertext1.size());
6507
6508 out_params.Clear();
6509
6510 string ciphertext2 = EncryptMessage(message, params, &out_params);
6511 vector<uint8_t> iv2 = CopyIv(out_params);
6512 EXPECT_EQ(message.size(), ciphertext2.size());
6513
6514 // IVs should be random, so ciphertexts should differ.
6515 EXPECT_NE(ciphertext1, ciphertext2);
6516
6517 params.push_back(TAG_NONCE, iv1);
6518 string plaintext = DecryptMessage(ciphertext1, params);
6519 EXPECT_EQ(message, plaintext);
6520}
6521
6522/*
Tommy Chiuee705692021-09-23 20:09:13 +08006523 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6524 *
6525 * Verifies that keymaster generates correct output on zero-input with
6526 * NonePadding mode
6527 */
6528TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6530 .Authorization(TAG_NO_AUTH_REQUIRED)
6531 .AesEncryptionKey(128)
6532 .BlockMode(BlockMode::CBC)
6533 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6534
6535 // Zero input message
6536 string message = "";
6537 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006538 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006539 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6540 AuthorizationSet out_params;
6541 string ciphertext1 = EncryptMessage(message, params, &out_params);
6542 vector<uint8_t> iv1 = CopyIv(out_params);
6543 if (padding == PaddingMode::NONE)
6544 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6545 else
6546 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6547
6548 out_params.Clear();
6549
6550 string ciphertext2 = EncryptMessage(message, params, &out_params);
6551 vector<uint8_t> iv2 = CopyIv(out_params);
6552 if (padding == PaddingMode::NONE)
6553 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6554 else
6555 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6556
6557 // IVs should be random
6558 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6559
6560 params.push_back(TAG_NONCE, iv1);
6561 string plaintext = DecryptMessage(ciphertext1, params);
6562 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6563 }
6564}
6565
6566/*
Selene Huang31ab4042020-04-29 04:22:39 -07006567 * EncryptionOperationsTest.AesCallerNonce
6568 *
6569 * Verifies that AES caller-provided nonces work correctly.
6570 */
6571TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6572 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6573 .Authorization(TAG_NO_AUTH_REQUIRED)
6574 .AesEncryptionKey(128)
6575 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6576 .Authorization(TAG_CALLER_NONCE)
6577 .Padding(PaddingMode::NONE)));
6578
6579 string message = "12345678901234567890123456789012";
6580
6581 // Don't specify nonce, should get a random one.
6582 AuthorizationSetBuilder params =
6583 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6584 AuthorizationSet out_params;
6585 string ciphertext = EncryptMessage(message, params, &out_params);
6586 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006587 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006588
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006589 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006590 string plaintext = DecryptMessage(ciphertext, params);
6591 EXPECT_EQ(message, plaintext);
6592
6593 // Now specify a nonce, should also work.
6594 params = AuthorizationSetBuilder()
6595 .BlockMode(BlockMode::CBC)
6596 .Padding(PaddingMode::NONE)
6597 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6598 out_params.Clear();
6599 ciphertext = EncryptMessage(message, params, &out_params);
6600
6601 // Decrypt with correct nonce.
6602 plaintext = DecryptMessage(ciphertext, params);
6603 EXPECT_EQ(message, plaintext);
6604
6605 // Try with wrong nonce.
6606 params = AuthorizationSetBuilder()
6607 .BlockMode(BlockMode::CBC)
6608 .Padding(PaddingMode::NONE)
6609 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6610 plaintext = DecryptMessage(ciphertext, params);
6611 EXPECT_NE(message, plaintext);
6612}
6613
6614/*
6615 * EncryptionOperationsTest.AesCallerNonceProhibited
6616 *
6617 * Verifies that caller-provided nonces are not permitted when not specified in the key
6618 * authorizations.
6619 */
6620TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6621 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6622 .Authorization(TAG_NO_AUTH_REQUIRED)
6623 .AesEncryptionKey(128)
6624 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6625 .Padding(PaddingMode::NONE)));
6626
6627 string message = "12345678901234567890123456789012";
6628
6629 // Don't specify nonce, should get a random one.
6630 AuthorizationSetBuilder params =
6631 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6632 AuthorizationSet out_params;
6633 string ciphertext = EncryptMessage(message, params, &out_params);
6634 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006635 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006636
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006637 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006638 string plaintext = DecryptMessage(ciphertext, params);
6639 EXPECT_EQ(message, plaintext);
6640
6641 // Now specify a nonce, should fail
6642 params = AuthorizationSetBuilder()
6643 .BlockMode(BlockMode::CBC)
6644 .Padding(PaddingMode::NONE)
6645 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6646 out_params.Clear();
6647 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6648}
6649
6650/*
6651 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6652 *
6653 * Verifies that AES GCM mode works.
6654 */
6655TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6657 .Authorization(TAG_NO_AUTH_REQUIRED)
6658 .AesEncryptionKey(128)
6659 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6660 .Padding(PaddingMode::NONE)
6661 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6662
6663 string aad = "foobar";
6664 string message = "123456789012345678901234567890123456";
6665
6666 auto begin_params = AuthorizationSetBuilder()
6667 .BlockMode(BlockMode::GCM)
6668 .Padding(PaddingMode::NONE)
6669 .Authorization(TAG_MAC_LENGTH, 128);
6670
Selene Huang31ab4042020-04-29 04:22:39 -07006671 // Encrypt
6672 AuthorizationSet begin_out_params;
6673 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6674 << "Begin encrypt";
6675 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006676 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6677 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006678 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6679
6680 // Grab nonce
6681 begin_params.push_back(begin_out_params);
6682
6683 // Decrypt.
6684 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006685 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006686 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006687 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006688 EXPECT_EQ(message.length(), plaintext.length());
6689 EXPECT_EQ(message, plaintext);
6690}
6691
6692/*
6693 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6694 *
6695 * Verifies that AES GCM mode works, even when there's a long delay
6696 * between operations.
6697 */
6698TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6699 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6700 .Authorization(TAG_NO_AUTH_REQUIRED)
6701 .AesEncryptionKey(128)
6702 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6703 .Padding(PaddingMode::NONE)
6704 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6705
6706 string aad = "foobar";
6707 string message = "123456789012345678901234567890123456";
6708
6709 auto begin_params = AuthorizationSetBuilder()
6710 .BlockMode(BlockMode::GCM)
6711 .Padding(PaddingMode::NONE)
6712 .Authorization(TAG_MAC_LENGTH, 128);
6713
Selene Huang31ab4042020-04-29 04:22:39 -07006714 // Encrypt
6715 AuthorizationSet begin_out_params;
6716 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6717 << "Begin encrypt";
6718 string ciphertext;
6719 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006720 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006721 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006722 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006723
6724 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6725
6726 // Grab nonce
6727 begin_params.push_back(begin_out_params);
6728
6729 // Decrypt.
6730 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6731 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006732 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006733 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006734 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006735 sleep(5);
6736 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6737 EXPECT_EQ(message.length(), plaintext.length());
6738 EXPECT_EQ(message, plaintext);
6739}
6740
6741/*
6742 * EncryptionOperationsTest.AesGcmDifferentNonces
6743 *
6744 * Verifies that encrypting the same data with different nonces produces different outputs.
6745 */
6746TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6748 .Authorization(TAG_NO_AUTH_REQUIRED)
6749 .AesEncryptionKey(128)
6750 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6751 .Padding(PaddingMode::NONE)
6752 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6753 .Authorization(TAG_CALLER_NONCE)));
6754
6755 string aad = "foobar";
6756 string message = "123456789012345678901234567890123456";
6757 string nonce1 = "000000000000";
6758 string nonce2 = "111111111111";
6759 string nonce3 = "222222222222";
6760
6761 string ciphertext1 =
6762 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6763 string ciphertext2 =
6764 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6765 string ciphertext3 =
6766 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6767
6768 ASSERT_NE(ciphertext1, ciphertext2);
6769 ASSERT_NE(ciphertext1, ciphertext3);
6770 ASSERT_NE(ciphertext2, ciphertext3);
6771}
6772
6773/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006774 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6775 *
6776 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6777 */
6778TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6779 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6780 .Authorization(TAG_NO_AUTH_REQUIRED)
6781 .AesEncryptionKey(128)
6782 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6783 .Padding(PaddingMode::NONE)
6784 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6785
6786 string aad = "foobar";
6787 string message = "123456789012345678901234567890123456";
6788
6789 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6790 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6791 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6792
6793 ASSERT_NE(ciphertext1, ciphertext2);
6794 ASSERT_NE(ciphertext1, ciphertext3);
6795 ASSERT_NE(ciphertext2, ciphertext3);
6796}
6797
6798/*
Selene Huang31ab4042020-04-29 04:22:39 -07006799 * EncryptionOperationsTest.AesGcmTooShortTag
6800 *
6801 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6802 */
6803TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6805 .Authorization(TAG_NO_AUTH_REQUIRED)
6806 .AesEncryptionKey(128)
6807 .BlockMode(BlockMode::GCM)
6808 .Padding(PaddingMode::NONE)
6809 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6810 string message = "123456789012345678901234567890123456";
6811 auto params = AuthorizationSetBuilder()
6812 .BlockMode(BlockMode::GCM)
6813 .Padding(PaddingMode::NONE)
6814 .Authorization(TAG_MAC_LENGTH, 96);
6815
6816 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6817}
6818
6819/*
6820 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6821 *
6822 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6823 */
6824TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6826 .Authorization(TAG_NO_AUTH_REQUIRED)
6827 .AesEncryptionKey(128)
6828 .BlockMode(BlockMode::GCM)
6829 .Padding(PaddingMode::NONE)
6830 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6831 string aad = "foobar";
6832 string message = "123456789012345678901234567890123456";
6833 auto params = AuthorizationSetBuilder()
6834 .BlockMode(BlockMode::GCM)
6835 .Padding(PaddingMode::NONE)
6836 .Authorization(TAG_MAC_LENGTH, 128);
6837
Selene Huang31ab4042020-04-29 04:22:39 -07006838 // Encrypt
6839 AuthorizationSet begin_out_params;
6840 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6841 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006842 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006843
6844 AuthorizationSet finish_out_params;
6845 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006846 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6847 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006848
6849 params = AuthorizationSetBuilder()
6850 .Authorizations(begin_out_params)
6851 .BlockMode(BlockMode::GCM)
6852 .Padding(PaddingMode::NONE)
6853 .Authorization(TAG_MAC_LENGTH, 96);
6854
6855 // Decrypt.
6856 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6857}
6858
6859/*
6860 * EncryptionOperationsTest.AesGcmCorruptKey
6861 *
6862 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6863 */
6864TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6865 const uint8_t nonce_bytes[] = {
6866 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6867 };
6868 string nonce = make_string(nonce_bytes);
6869 const uint8_t ciphertext_bytes[] = {
6870 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6871 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6872 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6873 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6874 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6875 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6876 };
6877 string ciphertext = make_string(ciphertext_bytes);
6878
6879 auto params = AuthorizationSetBuilder()
6880 .BlockMode(BlockMode::GCM)
6881 .Padding(PaddingMode::NONE)
6882 .Authorization(TAG_MAC_LENGTH, 128)
6883 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6884
6885 auto import_params = AuthorizationSetBuilder()
6886 .Authorization(TAG_NO_AUTH_REQUIRED)
6887 .AesEncryptionKey(128)
6888 .BlockMode(BlockMode::GCM)
6889 .Padding(PaddingMode::NONE)
6890 .Authorization(TAG_CALLER_NONCE)
6891 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6892
6893 // Import correct key and decrypt
6894 const uint8_t key_bytes[] = {
6895 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6896 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6897 };
6898 string key = make_string(key_bytes);
6899 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6900 string plaintext = DecryptMessage(ciphertext, params);
6901 CheckedDeleteKey();
6902
6903 // Corrupt key and attempt to decrypt
6904 key[0] = 0;
6905 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6906 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6907 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6908 CheckedDeleteKey();
6909}
6910
6911/*
6912 * EncryptionOperationsTest.AesGcmAadNoData
6913 *
6914 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6915 * encrypt.
6916 */
6917TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6919 .Authorization(TAG_NO_AUTH_REQUIRED)
6920 .AesEncryptionKey(128)
6921 .BlockMode(BlockMode::GCM)
6922 .Padding(PaddingMode::NONE)
6923 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6924
6925 string aad = "1234567890123456";
6926 auto params = AuthorizationSetBuilder()
6927 .BlockMode(BlockMode::GCM)
6928 .Padding(PaddingMode::NONE)
6929 .Authorization(TAG_MAC_LENGTH, 128);
6930
Selene Huang31ab4042020-04-29 04:22:39 -07006931 // Encrypt
6932 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006933 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006934 string ciphertext;
6935 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006936 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6937 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006938 EXPECT_TRUE(finish_out_params.empty());
6939
6940 // Grab nonce
6941 params.push_back(begin_out_params);
6942
6943 // Decrypt.
6944 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006945 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006946 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006947 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006948
6949 EXPECT_TRUE(finish_out_params.empty());
6950
6951 EXPECT_EQ("", plaintext);
6952}
6953
6954/*
6955 * EncryptionOperationsTest.AesGcmMultiPartAad
6956 *
6957 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6958 * chunks.
6959 */
6960TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6961 const size_t tag_bits = 128;
6962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6963 .Authorization(TAG_NO_AUTH_REQUIRED)
6964 .AesEncryptionKey(128)
6965 .BlockMode(BlockMode::GCM)
6966 .Padding(PaddingMode::NONE)
6967 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6968
6969 string message = "123456789012345678901234567890123456";
6970 auto begin_params = AuthorizationSetBuilder()
6971 .BlockMode(BlockMode::GCM)
6972 .Padding(PaddingMode::NONE)
6973 .Authorization(TAG_MAC_LENGTH, tag_bits);
6974 AuthorizationSet begin_out_params;
6975
David Drysdale7fc26b92022-05-13 09:54:24 +01006976 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006977
6978 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006979 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6980 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006981 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006982 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6983 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006984
Selene Huang31ab4042020-04-29 04:22:39 -07006985 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006986 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006987
6988 // Grab nonce.
6989 begin_params.push_back(begin_out_params);
6990
6991 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006992 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006993 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006994 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006995 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006996 EXPECT_EQ(message, plaintext);
6997}
6998
6999/*
7000 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7001 *
7002 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7003 */
7004TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7005 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7006 .Authorization(TAG_NO_AUTH_REQUIRED)
7007 .AesEncryptionKey(128)
7008 .BlockMode(BlockMode::GCM)
7009 .Padding(PaddingMode::NONE)
7010 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7011
7012 string message = "123456789012345678901234567890123456";
7013 auto begin_params = AuthorizationSetBuilder()
7014 .BlockMode(BlockMode::GCM)
7015 .Padding(PaddingMode::NONE)
7016 .Authorization(TAG_MAC_LENGTH, 128);
7017 AuthorizationSet begin_out_params;
7018
David Drysdale7fc26b92022-05-13 09:54:24 +01007019 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007020
Shawn Willden92d79c02021-02-19 07:31:55 -07007021 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007022 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007023 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7024 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007025
David Drysdaled2cc8c22021-04-15 13:29:45 +01007026 // The failure should have already cancelled the operation.
7027 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7028
Shawn Willden92d79c02021-02-19 07:31:55 -07007029 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007030}
7031
7032/*
7033 * EncryptionOperationsTest.AesGcmBadAad
7034 *
7035 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7036 */
7037TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7038 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7039 .Authorization(TAG_NO_AUTH_REQUIRED)
7040 .AesEncryptionKey(128)
7041 .BlockMode(BlockMode::GCM)
7042 .Padding(PaddingMode::NONE)
7043 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7044
7045 string message = "12345678901234567890123456789012";
7046 auto begin_params = AuthorizationSetBuilder()
7047 .BlockMode(BlockMode::GCM)
7048 .Padding(PaddingMode::NONE)
7049 .Authorization(TAG_MAC_LENGTH, 128);
7050
Selene Huang31ab4042020-04-29 04:22:39 -07007051 // Encrypt
7052 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007053 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007054 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007055 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007056 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007057
7058 // Grab nonce
7059 begin_params.push_back(begin_out_params);
7060
Selene Huang31ab4042020-04-29 04:22:39 -07007061 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007062 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007063 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007064 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007065 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007066}
7067
7068/*
7069 * EncryptionOperationsTest.AesGcmWrongNonce
7070 *
7071 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7072 */
7073TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7075 .Authorization(TAG_NO_AUTH_REQUIRED)
7076 .AesEncryptionKey(128)
7077 .BlockMode(BlockMode::GCM)
7078 .Padding(PaddingMode::NONE)
7079 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7080
7081 string message = "12345678901234567890123456789012";
7082 auto begin_params = AuthorizationSetBuilder()
7083 .BlockMode(BlockMode::GCM)
7084 .Padding(PaddingMode::NONE)
7085 .Authorization(TAG_MAC_LENGTH, 128);
7086
Selene Huang31ab4042020-04-29 04:22:39 -07007087 // Encrypt
7088 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007089 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007090 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007091 string ciphertext;
7092 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007093 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007094
7095 // Wrong nonce
7096 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7097
7098 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007099 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007100 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007101 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007102 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007103
7104 // With wrong nonce, should have gotten garbage plaintext (or none).
7105 EXPECT_NE(message, plaintext);
7106}
7107
7108/*
7109 * EncryptionOperationsTest.AesGcmCorruptTag
7110 *
7111 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7112 */
7113TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7115 .Authorization(TAG_NO_AUTH_REQUIRED)
7116 .AesEncryptionKey(128)
7117 .BlockMode(BlockMode::GCM)
7118 .Padding(PaddingMode::NONE)
7119 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7120
7121 string aad = "1234567890123456";
7122 string message = "123456789012345678901234567890123456";
7123
7124 auto params = AuthorizationSetBuilder()
7125 .BlockMode(BlockMode::GCM)
7126 .Padding(PaddingMode::NONE)
7127 .Authorization(TAG_MAC_LENGTH, 128);
7128
Selene Huang31ab4042020-04-29 04:22:39 -07007129 // Encrypt
7130 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007131 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007132 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007133 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007134 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007135
7136 // Corrupt tag
7137 ++(*ciphertext.rbegin());
7138
7139 // Grab nonce
7140 params.push_back(begin_out_params);
7141
7142 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007143 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007144 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007145 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007146 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007147}
7148
7149/*
7150 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7151 *
7152 * Verifies that 3DES is basically functional.
7153 */
7154TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7155 auto auths = AuthorizationSetBuilder()
7156 .TripleDesEncryptionKey(168)
7157 .BlockMode(BlockMode::ECB)
7158 .Authorization(TAG_NO_AUTH_REQUIRED)
7159 .Padding(PaddingMode::NONE);
7160
7161 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7162 // Two-block message.
7163 string message = "1234567890123456";
7164 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7165 string ciphertext1 = EncryptMessage(message, inParams);
7166 EXPECT_EQ(message.size(), ciphertext1.size());
7167
7168 string ciphertext2 = EncryptMessage(string(message), inParams);
7169 EXPECT_EQ(message.size(), ciphertext2.size());
7170
7171 // ECB is deterministic.
7172 EXPECT_EQ(ciphertext1, ciphertext2);
7173
7174 string plaintext = DecryptMessage(ciphertext1, inParams);
7175 EXPECT_EQ(message, plaintext);
7176}
7177
7178/*
7179 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7180 *
7181 * Verifies that CBC keys reject ECB usage.
7182 */
7183TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7184 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7185 .TripleDesEncryptionKey(168)
7186 .BlockMode(BlockMode::CBC)
7187 .Authorization(TAG_NO_AUTH_REQUIRED)
7188 .Padding(PaddingMode::NONE)));
7189
7190 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7191 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7192}
7193
7194/*
7195 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7196 *
7197 * Tests ECB mode with PKCS#7 padding, various message sizes.
7198 */
7199TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7200 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7201 .TripleDesEncryptionKey(168)
7202 .BlockMode(BlockMode::ECB)
7203 .Authorization(TAG_NO_AUTH_REQUIRED)
7204 .Padding(PaddingMode::PKCS7)));
7205
7206 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007207 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007208 string message(i, 'a');
7209 auto inParams =
7210 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7211 string ciphertext = EncryptMessage(message, inParams);
7212 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7213 string plaintext = DecryptMessage(ciphertext, inParams);
7214 EXPECT_EQ(message, plaintext);
7215 }
7216}
7217
7218/*
7219 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7220 *
7221 * Verifies that keys configured for no padding reject PKCS7 padding
7222 */
7223TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7225 .TripleDesEncryptionKey(168)
7226 .BlockMode(BlockMode::ECB)
7227 .Authorization(TAG_NO_AUTH_REQUIRED)
7228 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007229 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7230 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007231}
7232
7233/*
7234 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7235 *
7236 * Verifies that corrupted padding is detected.
7237 */
7238TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
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 string message = "a";
7246 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7247 EXPECT_EQ(8U, ciphertext.size());
7248 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007249
7250 AuthorizationSetBuilder begin_params;
7251 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7252 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007253
7254 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7255 ++ciphertext[ciphertext.size() / 2];
7256
David Drysdale7fc26b92022-05-13 09:54:24 +01007257 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007258 string plaintext;
7259 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7260 ErrorCode error = Finish(&plaintext);
7261 if (error == ErrorCode::INVALID_ARGUMENT) {
7262 // This is the expected error, we can exit the test now.
7263 return;
7264 } else {
7265 // Very small chance we got valid decryption, so try again.
7266 ASSERT_EQ(error, ErrorCode::OK);
7267 }
7268 }
7269 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007270}
7271
7272struct TripleDesTestVector {
7273 const char* name;
7274 const KeyPurpose purpose;
7275 const BlockMode block_mode;
7276 const PaddingMode padding_mode;
7277 const char* key;
7278 const char* iv;
7279 const char* input;
7280 const char* output;
7281};
7282
7283// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7284// of the NIST vectors are multiples of the block size.
7285static const TripleDesTestVector kTripleDesTestVectors[] = {
7286 {
7287 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7288 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7289 "", // IV
7290 "329d86bdf1bc5af4", // input
7291 "d946c2756d78633f", // output
7292 },
7293 {
7294 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7295 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7296 "", // IV
7297 "6b1540781b01ce1997adae102dbf3c5b", // input
7298 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7299 },
7300 {
7301 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7302 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7303 "", // IV
7304 "6daad94ce08acfe7", // input
7305 "660e7d32dcc90e79", // output
7306 },
7307 {
7308 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7309 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7310 "", // IV
7311 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7312 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7313 },
7314 {
7315 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7316 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7317 "43f791134c5647ba", // IV
7318 "dcc153cef81d6f24", // input
7319 "92538bd8af18d3ba", // output
7320 },
7321 {
7322 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7323 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7324 "c2e999cb6249023c", // IV
7325 "c689aee38a301bb316da75db36f110b5", // input
7326 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7327 },
7328 {
7329 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7330 PaddingMode::PKCS7,
7331 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7332 "c2e999cb6249023c", // IV
7333 "c689aee38a301bb316da75db36f110b500", // input
7334 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7335 },
7336 {
7337 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7338 PaddingMode::PKCS7,
7339 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7340 "c2e999cb6249023c", // IV
7341 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7342 "c689aee38a301bb316da75db36f110b500", // output
7343 },
7344 {
7345 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7346 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7347 "41746c7e442d3681", // IV
7348 "c53a7b0ec40600fe", // input
7349 "d4f00eb455de1034", // output
7350 },
7351 {
7352 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7353 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7354 "3982bc02c3727d45", // IV
7355 "6006f10adef52991fcc777a1238bbb65", // input
7356 "edae09288e9e3bc05746d872b48e3b29", // output
7357 },
7358};
7359
7360/*
7361 * EncryptionOperationsTest.TripleDesTestVector
7362 *
7363 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7364 */
7365TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7366 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7367 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7368 SCOPED_TRACE(test->name);
7369 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7370 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7371 hex2str(test->output));
7372 }
7373}
7374
7375/*
7376 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7377 *
7378 * Validates CBC mode functionality.
7379 */
7380TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7382 .TripleDesEncryptionKey(168)
7383 .BlockMode(BlockMode::CBC)
7384 .Authorization(TAG_NO_AUTH_REQUIRED)
7385 .Padding(PaddingMode::NONE)));
7386
7387 ASSERT_GT(key_blob_.size(), 0U);
7388
Brian J Murray734c8412022-01-13 14:55:30 -08007389 // Four-block message.
7390 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007391 vector<uint8_t> iv1;
7392 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7393 EXPECT_EQ(message.size(), ciphertext1.size());
7394
7395 vector<uint8_t> iv2;
7396 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7397 EXPECT_EQ(message.size(), ciphertext2.size());
7398
7399 // IVs should be random, so ciphertexts should differ.
7400 EXPECT_NE(iv1, iv2);
7401 EXPECT_NE(ciphertext1, ciphertext2);
7402
7403 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7404 EXPECT_EQ(message, plaintext);
7405}
7406
7407/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007408 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7409 *
7410 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7411 */
7412TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7413 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7414 .TripleDesEncryptionKey(168)
7415 .BlockMode(BlockMode::CBC)
7416 .Authorization(TAG_NO_AUTH_REQUIRED)
7417 .Authorization(TAG_CALLER_NONCE)
7418 .Padding(PaddingMode::NONE)));
7419 auto params = AuthorizationSetBuilder()
7420 .BlockMode(BlockMode::CBC)
7421 .Padding(PaddingMode::NONE)
7422 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7423 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7424}
7425
7426/*
Selene Huang31ab4042020-04-29 04:22:39 -07007427 * EncryptionOperationsTest.TripleDesCallerIv
7428 *
7429 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7430 */
7431TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7433 .TripleDesEncryptionKey(168)
7434 .BlockMode(BlockMode::CBC)
7435 .Authorization(TAG_NO_AUTH_REQUIRED)
7436 .Authorization(TAG_CALLER_NONCE)
7437 .Padding(PaddingMode::NONE)));
7438 string message = "1234567890123456";
7439 vector<uint8_t> iv;
7440 // Don't specify IV, should get a random one.
7441 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7442 EXPECT_EQ(message.size(), ciphertext1.size());
7443 EXPECT_EQ(8U, iv.size());
7444
7445 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7446 EXPECT_EQ(message, plaintext);
7447
7448 // Now specify an IV, should also work.
7449 iv = AidlBuf("abcdefgh");
7450 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7451
7452 // Decrypt with correct IV.
7453 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7454 EXPECT_EQ(message, plaintext);
7455
7456 // Now try with wrong IV.
7457 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7458 EXPECT_NE(message, plaintext);
7459}
7460
7461/*
7462 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7463 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007464 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007465 */
7466TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7467 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7468 .TripleDesEncryptionKey(168)
7469 .BlockMode(BlockMode::CBC)
7470 .Authorization(TAG_NO_AUTH_REQUIRED)
7471 .Padding(PaddingMode::NONE)));
7472
7473 string message = "12345678901234567890123456789012";
7474 vector<uint8_t> iv;
7475 // Don't specify nonce, should get a random one.
7476 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7477 EXPECT_EQ(message.size(), ciphertext1.size());
7478 EXPECT_EQ(8U, iv.size());
7479
7480 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7481 EXPECT_EQ(message, plaintext);
7482
7483 // Now specify a nonce, should fail.
7484 auto input_params = AuthorizationSetBuilder()
7485 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7486 .BlockMode(BlockMode::CBC)
7487 .Padding(PaddingMode::NONE);
7488 AuthorizationSet output_params;
7489 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7490 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7491}
7492
7493/*
7494 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7495 *
7496 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7497 */
7498TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7500 .TripleDesEncryptionKey(168)
7501 .BlockMode(BlockMode::ECB)
7502 .Authorization(TAG_NO_AUTH_REQUIRED)
7503 .Padding(PaddingMode::NONE)));
7504 // Two-block message.
7505 string message = "1234567890123456";
7506 auto begin_params =
7507 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7508 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7509}
7510
7511/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007512 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007513 *
7514 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7515 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007516TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7517 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007518 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007519 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7520 .TripleDesEncryptionKey(168)
7521 .BlockMode(blockMode)
7522 .Authorization(TAG_NO_AUTH_REQUIRED)
7523 .Padding(PaddingMode::NONE)));
7524 // Message is slightly shorter than two blocks.
7525 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007526
David Drysdaled2cc8c22021-04-15 13:29:45 +01007527 auto begin_params =
7528 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7529 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007530 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007531 string ciphertext;
7532 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7533
7534 CheckedDeleteKey();
7535 }
Selene Huang31ab4042020-04-29 04:22:39 -07007536}
7537
7538/*
7539 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7540 *
7541 * Verifies that PKCS7 padding works correctly in CBC mode.
7542 */
7543TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7545 .TripleDesEncryptionKey(168)
7546 .BlockMode(BlockMode::CBC)
7547 .Authorization(TAG_NO_AUTH_REQUIRED)
7548 .Padding(PaddingMode::PKCS7)));
7549
7550 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007551 for (size_t i = 0; i <= 32; i++) {
7552 SCOPED_TRACE(testing::Message() << "i = " << i);
7553 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7554 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007555 vector<uint8_t> iv;
7556 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7557 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7558 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7559 EXPECT_EQ(message, plaintext);
7560 }
7561}
7562
7563/*
7564 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7565 *
7566 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7567 */
7568TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7569 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7570 .TripleDesEncryptionKey(168)
7571 .BlockMode(BlockMode::CBC)
7572 .Authorization(TAG_NO_AUTH_REQUIRED)
7573 .Padding(PaddingMode::NONE)));
7574
7575 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007576 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007577 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007578 auto begin_params =
7579 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7580 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7581 }
7582}
7583
7584/*
7585 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7586 *
7587 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7588 */
7589TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7591 .TripleDesEncryptionKey(168)
7592 .BlockMode(BlockMode::CBC)
7593 .Authorization(TAG_NO_AUTH_REQUIRED)
7594 .Padding(PaddingMode::PKCS7)));
7595
7596 string message = "a";
7597 vector<uint8_t> iv;
7598 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7599 EXPECT_EQ(8U, ciphertext.size());
7600 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007601
7602 auto begin_params = AuthorizationSetBuilder()
7603 .BlockMode(BlockMode::CBC)
7604 .Padding(PaddingMode::PKCS7)
7605 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007606
7607 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007608 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007609 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007610 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007611 string plaintext;
7612 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7613 ErrorCode error = Finish(&plaintext);
7614 if (error == ErrorCode::INVALID_ARGUMENT) {
7615 // This is the expected error, we can exit the test now.
7616 return;
7617 } else {
7618 // Very small chance we got valid decryption, so try again.
7619 ASSERT_EQ(error, ErrorCode::OK);
7620 }
7621 }
7622 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007623}
7624
7625/*
7626 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7627 *
7628 * Verifies that 3DES CBC works with many different input sizes.
7629 */
7630TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7632 .TripleDesEncryptionKey(168)
7633 .BlockMode(BlockMode::CBC)
7634 .Authorization(TAG_NO_AUTH_REQUIRED)
7635 .Padding(PaddingMode::NONE)));
7636
7637 int increment = 7;
7638 string message(240, 'a');
7639 AuthorizationSet input_params =
7640 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7641 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007642 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007643
7644 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007645 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007646 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007647 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7648 EXPECT_EQ(message.size(), ciphertext.size());
7649
7650 // Move TAG_NONCE into input_params
7651 input_params = output_params;
7652 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7653 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7654 output_params.Clear();
7655
David Drysdale7fc26b92022-05-13 09:54:24 +01007656 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007657 string plaintext;
7658 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007659 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007660 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7661 EXPECT_EQ(ciphertext.size(), plaintext.size());
7662 EXPECT_EQ(message, plaintext);
7663}
7664
7665INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7666
7667typedef KeyMintAidlTestBase MaxOperationsTest;
7668
7669/*
7670 * MaxOperationsTest.TestLimitAes
7671 *
7672 * Verifies that the max uses per boot tag works correctly with AES keys.
7673 */
7674TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007675 if (SecLevel() == SecurityLevel::STRONGBOX) {
7676 GTEST_SKIP() << "Test not applicable to StrongBox device";
7677 }
Selene Huang31ab4042020-04-29 04:22:39 -07007678
7679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7680 .Authorization(TAG_NO_AUTH_REQUIRED)
7681 .AesEncryptionKey(128)
7682 .EcbMode()
7683 .Padding(PaddingMode::NONE)
7684 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7685
7686 string message = "1234567890123456";
7687
7688 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7689
7690 EncryptMessage(message, params);
7691 EncryptMessage(message, params);
7692 EncryptMessage(message, params);
7693
7694 // Fourth time should fail.
7695 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7696}
7697
7698/*
Qi Wud22ec842020-11-26 13:27:53 +08007699 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007700 *
7701 * Verifies that the max uses per boot tag works correctly with RSA keys.
7702 */
7703TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007704 if (SecLevel() == SecurityLevel::STRONGBOX) {
7705 GTEST_SKIP() << "Test not applicable to StrongBox device";
7706 }
Selene Huang31ab4042020-04-29 04:22:39 -07007707
7708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7709 .Authorization(TAG_NO_AUTH_REQUIRED)
7710 .RsaSigningKey(1024, 65537)
7711 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007712 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7713 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007714
7715 string message = "1234567890123456";
7716
7717 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7718
7719 SignMessage(message, params);
7720 SignMessage(message, params);
7721 SignMessage(message, params);
7722
7723 // Fourth time should fail.
7724 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7725}
7726
7727INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7728
Qi Wud22ec842020-11-26 13:27:53 +08007729typedef KeyMintAidlTestBase UsageCountLimitTest;
7730
7731/*
Qi Wubeefae42021-01-28 23:16:37 +08007732 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007733 *
Qi Wubeefae42021-01-28 23:16:37 +08007734 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007735 */
Qi Wubeefae42021-01-28 23:16:37 +08007736TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007737 if (SecLevel() == SecurityLevel::STRONGBOX) {
7738 GTEST_SKIP() << "Test not applicable to StrongBox device";
7739 }
Qi Wud22ec842020-11-26 13:27:53 +08007740
7741 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7742 .Authorization(TAG_NO_AUTH_REQUIRED)
7743 .AesEncryptionKey(128)
7744 .EcbMode()
7745 .Padding(PaddingMode::NONE)
7746 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7747
7748 // Check the usage count limit tag appears in the authorizations.
7749 AuthorizationSet auths;
7750 for (auto& entry : key_characteristics_) {
7751 auths.push_back(AuthorizationSet(entry.authorizations));
7752 }
7753 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7754 << "key usage count limit " << 1U << " missing";
7755
7756 string message = "1234567890123456";
7757 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7758
Qi Wubeefae42021-01-28 23:16:37 +08007759 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7760 AuthorizationSet keystore_auths =
7761 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7762
Qi Wud22ec842020-11-26 13:27:53 +08007763 // First usage of AES key should work.
7764 EncryptMessage(message, params);
7765
Qi Wud22ec842020-11-26 13:27:53 +08007766 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7767 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7768 // must be invalidated from secure storage (such as RPMB partition).
7769 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7770 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007771 // Usage count limit tag is enforced by keystore, keymint does nothing.
7772 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007773 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007774 }
7775}
7776
7777/*
Qi Wubeefae42021-01-28 23:16:37 +08007778 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007779 *
Qi Wubeefae42021-01-28 23:16:37 +08007780 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007781 */
Qi Wubeefae42021-01-28 23:16:37 +08007782TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007783 if (SecLevel() == SecurityLevel::STRONGBOX) {
7784 GTEST_SKIP() << "Test not applicable to StrongBox device";
7785 }
Qi Wubeefae42021-01-28 23:16:37 +08007786
7787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7788 .Authorization(TAG_NO_AUTH_REQUIRED)
7789 .AesEncryptionKey(128)
7790 .EcbMode()
7791 .Padding(PaddingMode::NONE)
7792 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7793
7794 // Check the usage count limit tag appears in the authorizations.
7795 AuthorizationSet auths;
7796 for (auto& entry : key_characteristics_) {
7797 auths.push_back(AuthorizationSet(entry.authorizations));
7798 }
7799 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7800 << "key usage count limit " << 3U << " missing";
7801
7802 string message = "1234567890123456";
7803 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7804
7805 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7806 AuthorizationSet keystore_auths =
7807 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7808
7809 EncryptMessage(message, params);
7810 EncryptMessage(message, params);
7811 EncryptMessage(message, params);
7812
7813 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7814 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7815 // must be invalidated from secure storage (such as RPMB partition).
7816 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7817 } else {
7818 // Usage count limit tag is enforced by keystore, keymint does nothing.
7819 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007820 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007821 }
7822}
7823
7824/*
7825 * UsageCountLimitTest.TestSingleUseRsa
7826 *
7827 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7828 */
7829TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007830 if (SecLevel() == SecurityLevel::STRONGBOX) {
7831 GTEST_SKIP() << "Test not applicable to StrongBox device";
7832 }
Qi Wud22ec842020-11-26 13:27:53 +08007833
7834 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7835 .Authorization(TAG_NO_AUTH_REQUIRED)
7836 .RsaSigningKey(1024, 65537)
7837 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007838 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7839 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007840
7841 // Check the usage count limit tag appears in the authorizations.
7842 AuthorizationSet auths;
7843 for (auto& entry : key_characteristics_) {
7844 auths.push_back(AuthorizationSet(entry.authorizations));
7845 }
7846 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7847 << "key usage count limit " << 1U << " missing";
7848
7849 string message = "1234567890123456";
7850 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7851
Qi Wubeefae42021-01-28 23:16:37 +08007852 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7853 AuthorizationSet keystore_auths =
7854 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7855
Qi Wud22ec842020-11-26 13:27:53 +08007856 // First usage of RSA key should work.
7857 SignMessage(message, params);
7858
Qi Wud22ec842020-11-26 13:27:53 +08007859 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7860 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7861 // must be invalidated from secure storage (such as RPMB partition).
7862 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7863 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007864 // Usage count limit tag is enforced by keystore, keymint does nothing.
7865 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007866 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007867 }
7868}
7869
7870/*
7871 * UsageCountLimitTest.TestLimitUseRsa
7872 *
7873 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7874 */
7875TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007876 if (SecLevel() == SecurityLevel::STRONGBOX) {
7877 GTEST_SKIP() << "Test not applicable to StrongBox device";
7878 }
Qi Wubeefae42021-01-28 23:16:37 +08007879
7880 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7881 .Authorization(TAG_NO_AUTH_REQUIRED)
7882 .RsaSigningKey(1024, 65537)
7883 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007884 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7885 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007886
7887 // Check the usage count limit tag appears in the authorizations.
7888 AuthorizationSet auths;
7889 for (auto& entry : key_characteristics_) {
7890 auths.push_back(AuthorizationSet(entry.authorizations));
7891 }
7892 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7893 << "key usage count limit " << 3U << " missing";
7894
7895 string message = "1234567890123456";
7896 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7897
7898 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7899 AuthorizationSet keystore_auths =
7900 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7901
7902 SignMessage(message, params);
7903 SignMessage(message, params);
7904 SignMessage(message, params);
7905
7906 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7907 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7908 // must be invalidated from secure storage (such as RPMB partition).
7909 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7910 } else {
7911 // Usage count limit tag is enforced by keystore, keymint does nothing.
7912 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007913 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007914 }
7915}
7916
Qi Wu8e727f72021-02-11 02:49:33 +08007917/*
7918 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7919 *
7920 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7921 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7922 * in hardware.
7923 */
7924TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007925 auto error = GenerateKey(AuthorizationSetBuilder()
7926 .RsaSigningKey(2048, 65537)
7927 .Digest(Digest::NONE)
7928 .Padding(PaddingMode::NONE)
7929 .Authorization(TAG_NO_AUTH_REQUIRED)
7930 .Authorization(TAG_ROLLBACK_RESISTANCE)
7931 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007932 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7933 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007934 }
David Drysdale513bf122021-10-06 11:53:13 +01007935
7936 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7937 ASSERT_EQ(ErrorCode::OK, error);
7938 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7939 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7940 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7941
7942 // The KeyMint should also enforce single use key in hardware when it supports rollback
7943 // resistance.
7944 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7945 .Authorization(TAG_NO_AUTH_REQUIRED)
7946 .RsaSigningKey(1024, 65537)
7947 .NoDigestOrPadding()
7948 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7949 .SetDefaultValidity()));
7950
7951 // Check the usage count limit tag appears in the hardware authorizations.
7952 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7953 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7954 << "key usage count limit " << 1U << " missing";
7955
7956 string message = "1234567890123456";
7957 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7958
7959 // First usage of RSA key should work.
7960 SignMessage(message, params);
7961
7962 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7963 // must be invalidated from secure storage (such as RPMB partition).
7964 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007965}
7966
Qi Wud22ec842020-11-26 13:27:53 +08007967INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7968
David Drysdale7de9feb2021-03-05 14:56:19 +00007969typedef KeyMintAidlTestBase GetHardwareInfoTest;
7970
7971TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7972 // Retrieving hardware info should give the same result each time.
7973 KeyMintHardwareInfo info;
7974 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7975 KeyMintHardwareInfo info2;
7976 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7977 EXPECT_EQ(info, info2);
7978}
7979
7980INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7981
Selene Huang31ab4042020-04-29 04:22:39 -07007982typedef KeyMintAidlTestBase AddEntropyTest;
7983
7984/*
7985 * AddEntropyTest.AddEntropy
7986 *
7987 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7988 * is actually added.
7989 */
7990TEST_P(AddEntropyTest, AddEntropy) {
7991 string data = "foo";
7992 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7993}
7994
7995/*
7996 * AddEntropyTest.AddEmptyEntropy
7997 *
7998 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7999 */
8000TEST_P(AddEntropyTest, AddEmptyEntropy) {
8001 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8002}
8003
8004/*
8005 * AddEntropyTest.AddLargeEntropy
8006 *
8007 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8008 */
8009TEST_P(AddEntropyTest, AddLargeEntropy) {
8010 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8011}
8012
David Drysdalebb3d85e2021-04-13 11:15:51 +01008013/*
8014 * AddEntropyTest.AddTooLargeEntropy
8015 *
8016 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8017 */
8018TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8019 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8020 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8021}
8022
Selene Huang31ab4042020-04-29 04:22:39 -07008023INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8024
Selene Huang31ab4042020-04-29 04:22:39 -07008025typedef KeyMintAidlTestBase KeyDeletionTest;
8026
8027/**
8028 * KeyDeletionTest.DeleteKey
8029 *
8030 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8031 * valid key blob.
8032 */
8033TEST_P(KeyDeletionTest, DeleteKey) {
8034 auto error = GenerateKey(AuthorizationSetBuilder()
8035 .RsaSigningKey(2048, 65537)
8036 .Digest(Digest::NONE)
8037 .Padding(PaddingMode::NONE)
8038 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008039 .Authorization(TAG_ROLLBACK_RESISTANCE)
8040 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008041 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8042 GTEST_SKIP() << "Rollback resistance not supported";
8043 }
Selene Huang31ab4042020-04-29 04:22:39 -07008044
8045 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008046 ASSERT_EQ(ErrorCode::OK, error);
8047 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8048 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008049
David Drysdale513bf122021-10-06 11:53:13 +01008050 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008051
David Drysdale513bf122021-10-06 11:53:13 +01008052 string message = "12345678901234567890123456789012";
8053 AuthorizationSet begin_out_params;
8054 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8055 Begin(KeyPurpose::SIGN, key_blob_,
8056 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8057 &begin_out_params));
8058 AbortIfNeeded();
8059 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008060}
8061
8062/**
8063 * KeyDeletionTest.DeleteInvalidKey
8064 *
8065 * This test checks that the HAL excepts invalid key blobs..
8066 */
8067TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8068 // Generate key just to check if rollback protection is implemented
8069 auto error = GenerateKey(AuthorizationSetBuilder()
8070 .RsaSigningKey(2048, 65537)
8071 .Digest(Digest::NONE)
8072 .Padding(PaddingMode::NONE)
8073 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008074 .Authorization(TAG_ROLLBACK_RESISTANCE)
8075 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008076 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8077 GTEST_SKIP() << "Rollback resistance not supported";
8078 }
Selene Huang31ab4042020-04-29 04:22:39 -07008079
8080 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008081 ASSERT_EQ(ErrorCode::OK, error);
8082 AuthorizationSet enforced(SecLevelAuthorizations());
8083 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008084
David Drysdale513bf122021-10-06 11:53:13 +01008085 // Delete the key we don't care about the result at this point.
8086 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008087
David Drysdale513bf122021-10-06 11:53:13 +01008088 // Now create an invalid key blob and delete it.
8089 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008090
David Drysdale513bf122021-10-06 11:53:13 +01008091 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008092}
8093
8094/**
8095 * KeyDeletionTest.DeleteAllKeys
8096 *
8097 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8098 *
8099 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8100 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8101 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8102 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8103 * credentials stored in Keystore/Keymint.
8104 */
8105TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008106 if (!arm_deleteAllKeys) {
8107 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8108 return;
8109 }
Selene Huang31ab4042020-04-29 04:22:39 -07008110 auto error = GenerateKey(AuthorizationSetBuilder()
8111 .RsaSigningKey(2048, 65537)
8112 .Digest(Digest::NONE)
8113 .Padding(PaddingMode::NONE)
8114 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008115 .Authorization(TAG_ROLLBACK_RESISTANCE)
8116 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008117 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8118 GTEST_SKIP() << "Rollback resistance not supported";
8119 }
Selene Huang31ab4042020-04-29 04:22:39 -07008120
8121 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008122 ASSERT_EQ(ErrorCode::OK, error);
8123 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8124 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008125
David Drysdale513bf122021-10-06 11:53:13 +01008126 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008127
David Drysdale513bf122021-10-06 11:53:13 +01008128 string message = "12345678901234567890123456789012";
8129 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008130
David Drysdale513bf122021-10-06 11:53:13 +01008131 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8132 Begin(KeyPurpose::SIGN, key_blob_,
8133 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8134 &begin_out_params));
8135 AbortIfNeeded();
8136 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008137}
8138
8139INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8140
David Drysdaled2cc8c22021-04-15 13:29:45 +01008141typedef KeyMintAidlTestBase KeyUpgradeTest;
8142
8143/**
8144 * KeyUpgradeTest.UpgradeInvalidKey
8145 *
8146 * This test checks that the HAL excepts invalid key blobs..
8147 */
8148TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8149 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8150
8151 std::vector<uint8_t> new_blob;
8152 Status result = keymint_->upgradeKey(key_blob,
8153 AuthorizationSetBuilder()
8154 .Authorization(TAG_APPLICATION_ID, "clientid")
8155 .Authorization(TAG_APPLICATION_DATA, "appdata")
8156 .vector_data(),
8157 &new_blob);
8158 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8159}
8160
8161INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8162
Selene Huang31ab4042020-04-29 04:22:39 -07008163using UpgradeKeyTest = KeyMintAidlTestBase;
8164
8165/*
8166 * UpgradeKeyTest.UpgradeKey
8167 *
8168 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8169 */
8170TEST_P(UpgradeKeyTest, UpgradeKey) {
8171 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8172 .AesEncryptionKey(128)
8173 .Padding(PaddingMode::NONE)
8174 .Authorization(TAG_NO_AUTH_REQUIRED)));
8175
8176 auto result = UpgradeKey(key_blob_);
8177
8178 // Key doesn't need upgrading. Should get okay, but no new key blob.
8179 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8180}
8181
8182INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8183
8184using ClearOperationsTest = KeyMintAidlTestBase;
8185
8186/*
8187 * ClearSlotsTest.TooManyOperations
8188 *
8189 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8190 * operations are started without being finished or aborted. Also verifies
8191 * that aborting the operations clears the operations.
8192 *
8193 */
8194TEST_P(ClearOperationsTest, TooManyOperations) {
8195 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8196 .Authorization(TAG_NO_AUTH_REQUIRED)
8197 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008198 .Padding(PaddingMode::NONE)
8199 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008200
8201 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8202 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008203 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008204 AuthorizationSet out_params;
8205 ErrorCode result;
8206 size_t i;
8207
8208 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008209 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008210 if (ErrorCode::OK != result) {
8211 break;
8212 }
8213 }
8214 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8215 // Try again just in case there's a weird overflow bug
8216 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008217 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008218 for (size_t j = 0; j < i; j++) {
8219 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8220 << "Aboort failed for i = " << j << std::endl;
8221 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008222 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008223 AbortIfNeeded();
8224}
8225
8226INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8227
8228typedef KeyMintAidlTestBase TransportLimitTest;
8229
8230/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008231 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008232 *
8233 * Verifies that passing input data to finish succeeds as expected.
8234 */
8235TEST_P(TransportLimitTest, LargeFinishInput) {
8236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8237 .Authorization(TAG_NO_AUTH_REQUIRED)
8238 .AesEncryptionKey(128)
8239 .BlockMode(BlockMode::ECB)
8240 .Padding(PaddingMode::NONE)));
8241
8242 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008243 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008244 auto cipher_params =
8245 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8246
8247 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008248 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008249
8250 string plain_message = std::string(1 << msg_size, 'x');
8251 string encrypted_message;
8252 auto rc = Finish(plain_message, &encrypted_message);
8253
8254 EXPECT_EQ(ErrorCode::OK, rc);
8255 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8256 << "Encrypt finish returned OK, but did not consume all of the given input";
8257 cipher_params.push_back(out_params);
8258
David Drysdale7fc26b92022-05-13 09:54:24 +01008259 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008260
8261 string decrypted_message;
8262 rc = Finish(encrypted_message, &decrypted_message);
8263 EXPECT_EQ(ErrorCode::OK, rc);
8264 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8265 << "Decrypt finish returned OK, did not consume all of the given input";
8266 }
8267}
8268
8269INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8270
Seth Moored79a0ec2021-12-13 20:03:33 +00008271static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008272 switch (curve) {
8273 case EcCurve::P_224:
8274 return NID_secp224r1;
8275 case EcCurve::P_256:
8276 return NID_X9_62_prime256v1;
8277 case EcCurve::P_384:
8278 return NID_secp384r1;
8279 case EcCurve::P_521:
8280 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008281 case EcCurve::CURVE_25519:
8282 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008283 }
8284}
8285
David Drysdale42fe1892021-10-14 14:43:46 +01008286class KeyAgreementTest : public KeyMintAidlTestBase {
8287 protected:
8288 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8289 std::vector<uint8_t>* localPublicKey) {
8290 // Generate EC key locally (with access to private key material)
8291 if (localCurve == EcCurve::CURVE_25519) {
8292 uint8_t privKeyData[32];
8293 uint8_t pubKeyData[32];
8294 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008295 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8296 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8297 } else {
8298 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8299 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8300 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8301 ASSERT_NE(group, nullptr);
8302 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8303 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8304 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8305 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008306 }
David Drysdalea410b772022-05-09 16:44:13 +01008307
8308 // Get encoded form of the public part of the locally generated key...
8309 unsigned char* p = nullptr;
8310 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8311 ASSERT_GT(localPublicKeySize, 0);
8312 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8313 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8314 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008315 }
8316
8317 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8318 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008319 auto builder = AuthorizationSetBuilder()
8320 .Authorization(TAG_NO_AUTH_REQUIRED)
8321 .Authorization(TAG_EC_CURVE, curve)
8322 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8323 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8324 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8325 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8326 .SetDefaultValidity();
8327 ErrorCode result = GenerateKey(builder);
8328
8329 if (SecLevel() == SecurityLevel::STRONGBOX) {
8330 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8331 result = GenerateKeyWithSelfSignedAttestKey(
8332 AuthorizationSetBuilder()
8333 .EcdsaKey(EcCurve::P_256)
8334 .AttestKey()
8335 .SetDefaultValidity(), /* attest key params */
8336 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8337 }
8338 }
David Drysdale42fe1892021-10-14 14:43:46 +01008339 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8340 ASSERT_GT(cert_chain_.size(), 0);
8341 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8342 ASSERT_NE(kmKeyCert, nullptr);
8343 // Check that keyAgreement (bit 4) is set in KeyUsage
8344 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8345 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8346 ASSERT_NE(*kmPubKey, nullptr);
8347 if (dump_Attestations) {
8348 for (size_t n = 0; n < cert_chain_.size(); n++) {
8349 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8350 }
8351 }
8352 }
8353
8354 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8355 const std::vector<uint8_t>& localPublicKey) {
8356 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8357 string ZabFromKeyMintStr;
8358 ASSERT_EQ(ErrorCode::OK,
8359 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8360 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8361 vector<uint8_t> ZabFromTest;
8362
8363 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8364 size_t kmPubKeySize = 32;
8365 uint8_t kmPubKeyData[32];
8366 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8367 ASSERT_EQ(kmPubKeySize, 32);
8368
8369 uint8_t localPrivKeyData[32];
8370 size_t localPrivKeySize = 32;
8371 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8372 &localPrivKeySize));
8373 ASSERT_EQ(localPrivKeySize, 32);
8374
8375 uint8_t sharedKey[32];
8376 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8377 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8378 } else {
8379 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8380 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8381 ASSERT_NE(ctx, nullptr);
8382 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8383 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8384 size_t ZabFromTestLen = 0;
8385 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8386 ZabFromTest.resize(ZabFromTestLen);
8387 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8388 }
8389 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8390 }
8391};
8392
David Zeuthene0c40892021-01-08 12:54:11 -05008393/*
8394 * KeyAgreementTest.Ecdh
8395 *
David Drysdale42fe1892021-10-14 14:43:46 +01008396 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008397 */
8398TEST_P(KeyAgreementTest, Ecdh) {
8399 // Because it's possible to use this API with keys on different curves, we
8400 // check all N^2 combinations where N is the number of supported
8401 // curves.
8402 //
8403 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8404 // lot more curves we can be smart about things and just pick |otherCurve| so
8405 // it's not |curve| and that way we end up with only 2*N runs
8406 //
8407 for (auto curve : ValidCurves()) {
8408 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008409 SCOPED_TRACE(testing::Message()
8410 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8411
David Zeuthene0c40892021-01-08 12:54:11 -05008412 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008413 EVP_PKEY_Ptr localPrivKey;
8414 vector<uint8_t> localPublicKey;
8415 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008416
8417 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008418 EVP_PKEY_Ptr kmPubKey;
8419 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008420
8421 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8422 if (curve != localCurve) {
8423 // If the keys are using different curves KeyMint should fail with
8424 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008425 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008426 string ZabFromKeyMintStr;
8427 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008428 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008429 &ZabFromKeyMintStr));
8430
8431 } else {
8432 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008433 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008434 }
8435
8436 CheckedDeleteKey();
8437 }
8438 }
8439}
8440
David Drysdale42fe1892021-10-14 14:43:46 +01008441/*
8442 * KeyAgreementTest.EcdhCurve25519
8443 *
8444 * Verifies that ECDH works for curve25519. This is also covered by the general
8445 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8446 * KeyMint 1.0.
8447 */
8448TEST_P(KeyAgreementTest, EcdhCurve25519) {
8449 if (!Curve25519Supported()) {
8450 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8451 }
8452
8453 // Generate EC key in KeyMint (only access to public key material)
8454 EcCurve curve = EcCurve::CURVE_25519;
8455 EVP_PKEY_Ptr kmPubKey = nullptr;
8456 GenerateKeyMintEcKey(curve, &kmPubKey);
8457
8458 // Generate EC key on same curve locally (with access to private key material).
8459 EVP_PKEY_Ptr privKey;
8460 vector<uint8_t> encodedPublicKey;
8461 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8462
8463 // Agree on a key between local and KeyMint and check it.
8464 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8465
8466 CheckedDeleteKey();
8467}
8468
8469/*
8470 * KeyAgreementTest.EcdhCurve25519Imported
8471 *
8472 * Verifies that ECDH works for an imported curve25519 key.
8473 */
8474TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8475 if (!Curve25519Supported()) {
8476 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8477 }
8478
8479 // Import x25519 key into KeyMint.
8480 EcCurve curve = EcCurve::CURVE_25519;
8481 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8482 .Authorization(TAG_NO_AUTH_REQUIRED)
8483 .EcdsaKey(EcCurve::CURVE_25519)
8484 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8485 .SetDefaultValidity(),
8486 KeyFormat::PKCS8, x25519_pkcs8_key));
8487 ASSERT_GT(cert_chain_.size(), 0);
8488 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8489 ASSERT_NE(kmKeyCert, nullptr);
8490 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8491 ASSERT_NE(kmPubKey.get(), nullptr);
8492
8493 // Expect the import to emit corresponding public key data.
8494 size_t kmPubKeySize = 32;
8495 uint8_t kmPubKeyData[32];
8496 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8497 ASSERT_EQ(kmPubKeySize, 32);
8498 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8499 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8500
8501 // Generate EC key on same curve locally (with access to private key material).
8502 EVP_PKEY_Ptr privKey;
8503 vector<uint8_t> encodedPublicKey;
8504 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8505
8506 // Agree on a key between local and KeyMint and check it.
8507 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8508
8509 CheckedDeleteKey();
8510}
8511
8512/*
8513 * KeyAgreementTest.EcdhCurve25519InvalidSize
8514 *
8515 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8516 */
8517TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8518 if (!Curve25519Supported()) {
8519 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8520 }
8521
8522 // Generate EC key in KeyMint (only access to public key material)
8523 EcCurve curve = EcCurve::CURVE_25519;
8524 EVP_PKEY_Ptr kmPubKey = nullptr;
8525 GenerateKeyMintEcKey(curve, &kmPubKey);
8526
8527 // Generate EC key on same curve locally (with access to private key material).
8528 EVP_PKEY_Ptr privKey;
8529 vector<uint8_t> encodedPublicKey;
8530 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8531
8532 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8533 string ZabFromKeyMintStr;
8534 // Send in an incomplete public key.
8535 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8536 &ZabFromKeyMintStr));
8537
8538 CheckedDeleteKey();
8539}
8540
8541/*
8542 * KeyAgreementTest.EcdhCurve25519Mismatch
8543 *
8544 * Verifies that ECDH fails between curve25519 and other curves.
8545 */
8546TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8547 if (!Curve25519Supported()) {
8548 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8549 }
8550
8551 // Generate EC key in KeyMint (only access to public key material)
8552 EcCurve curve = EcCurve::CURVE_25519;
8553 EVP_PKEY_Ptr kmPubKey = nullptr;
8554 GenerateKeyMintEcKey(curve, &kmPubKey);
8555
8556 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008557 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008558 if (localCurve == curve) {
8559 continue;
8560 }
8561 // Generate EC key on a different curve locally (with access to private key material).
8562 EVP_PKEY_Ptr privKey;
8563 vector<uint8_t> encodedPublicKey;
8564 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8565
David Drysdale7fc26b92022-05-13 09:54:24 +01008566 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008567 string ZabFromKeyMintStr;
8568 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8569 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8570 &ZabFromKeyMintStr));
8571 }
8572
8573 CheckedDeleteKey();
8574}
8575
David Zeuthene0c40892021-01-08 12:54:11 -05008576INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8577
David Drysdaled2cc8c22021-04-15 13:29:45 +01008578using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8579
8580// This is a problematic test, as it can render the device under test permanently unusable.
8581// Re-enable and run at your own risk.
8582TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8583 auto result = DestroyAttestationIds();
8584 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8585}
8586
8587INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8588
Shawn Willdend659c7c2021-02-19 14:51:51 -07008589using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008590
David Drysdaledb0dcf52021-05-18 11:43:31 +01008591/*
8592 * EarlyBootKeyTest.CreateEarlyBootKeys
8593 *
8594 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8595 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008596TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008597 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008598 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8599 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008600 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8601 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8602 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8603 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008604
David Drysdaleadfe6112021-05-27 12:00:53 +01008605 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8606 ASSERT_GT(keyData.blob.size(), 0U);
8607 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8608 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8609 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008610}
8611
David Drysdaledb0dcf52021-05-18 11:43:31 +01008612/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008613 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8614 *
8615 * Verifies that creating an early boot key with attestation succeeds.
8616 */
8617TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8618 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8619 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8620 builder->AttestationChallenge("challenge");
8621 builder->AttestationApplicationId("app_id");
8622 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008623 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8624 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8625 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8626 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008627
8628 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008629 // Strongbox may not support factory attestation. Key creation might fail with
8630 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8631 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8632 continue;
8633 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008634 ASSERT_GT(keyData.blob.size(), 0U);
8635 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8636 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8637 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008638}
8639
8640/*
8641 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008642 *
8643 * Verifies that using early boot keys at a later stage fails.
8644 */
8645TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8646 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8647 .Authorization(TAG_NO_AUTH_REQUIRED)
8648 .Authorization(TAG_EARLY_BOOT_ONLY)
8649 .HmacKey(128)
8650 .Digest(Digest::SHA_2_256)
8651 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8652 AuthorizationSet output_params;
8653 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8654 AuthorizationSetBuilder()
8655 .Digest(Digest::SHA_2_256)
8656 .Authorization(TAG_MAC_LENGTH, 256),
8657 &output_params));
8658}
8659
8660/*
8661 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8662 *
8663 * Verifies that importing early boot keys fails.
8664 */
8665TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8666 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8667 .Authorization(TAG_NO_AUTH_REQUIRED)
8668 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008669 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008670 .Digest(Digest::SHA_2_256)
8671 .SetDefaultValidity(),
8672 KeyFormat::PKCS8, ec_256_key));
8673}
8674
David Drysdaled2cc8c22021-04-15 13:29:45 +01008675// 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 +00008676// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8677// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8678// early boot, so you'll have to reboot between runs.
8679TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8680 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8681 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008682 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8683 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8684 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8685 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8686
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008687 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8688 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8689 EXPECT_TRUE(
8690 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8691 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8692 EXPECT_TRUE(
8693 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8694
8695 // Should be able to use keys, since early boot has not ended
8696 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8697 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8698 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8699 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8700
8701 // End early boot
8702 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8703 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8704
8705 // Should not be able to use already-created keys.
8706 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8707 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8708 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8709 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8710
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008711 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008712 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008713 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008714 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8715 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8716 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8717 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008718}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008719
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008720INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8721
Shawn Willdend659c7c2021-02-19 14:51:51 -07008722using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008723
8724// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8725// between runs... and on most test devices there are no enrolled credentials so it can't be
8726// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8727// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8728// a manual test process, which includes unlocking between runs, which is why it's included here.
8729// Well, that and the fact that it's the only test we can do without also making calls into the
8730// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8731// implications might be, so that may or may not be a solution.
8732TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8733 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8734 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008735 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8736 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8737 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8738 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008739
8740 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8741 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8742 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8743 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8744
8745 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008746 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008747 ASSERT_EQ(ErrorCode::OK, rc);
8748 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8749 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8750 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8751 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008752}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008753
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008754INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8755
Shawn Willden22fb9c12022-06-02 14:04:33 -06008756using VsrRequirementTest = KeyMintAidlTestBase;
8757
8758TEST_P(VsrRequirementTest, Vsr13Test) {
8759 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008760 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008761 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8762 }
8763 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8764}
8765
Eran Messerib9346f52022-12-15 14:58:34 +00008766TEST_P(VsrRequirementTest, Vsr14Test) {
8767 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008768 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008769 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8770 }
8771 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8772}
8773
Shawn Willden22fb9c12022-06-02 14:04:33 -06008774INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8775
Janis Danisevskis24c04702020-12-16 18:28:39 -08008776} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008777
8778int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008779 std::cout << "Testing ";
8780 auto halInstances =
8781 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8782 std::cout << "HAL instances:\n";
8783 for (auto& entry : halInstances) {
8784 std::cout << " " << entry << '\n';
8785 }
8786
Selene Huang31ab4042020-04-29 04:22:39 -07008787 ::testing::InitGoogleTest(&argc, argv);
8788 for (int i = 1; i < argc; ++i) {
8789 if (argv[i][0] == '-') {
8790 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008791 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8792 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008793 }
8794 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008795 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8796 dump_Attestations = true;
8797 } else {
8798 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008799 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008800 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8801 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8802 // be run in emulated environments that don't have the normal bootloader
8803 // interactions.
8804 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8805 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008806 if (std::string(argv[i]) == "--keyblob_dir") {
8807 if (i + 1 >= argc) {
8808 std::cerr << "Missing argument for --keyblob_dir\n";
8809 return 1;
8810 }
8811 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8812 std::string(argv[i + 1]);
8813 ++i;
8814 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008815 if (std::string(argv[i]) == "--expect_upgrade") {
8816 if (i + 1 >= argc) {
8817 std::cerr << "Missing argument for --expect_upgrade\n";
8818 return 1;
8819 }
8820 std::string arg = argv[i + 1];
8821 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8822 expect_upgrade =
8823 arg == "yes"
8824 ? true
8825 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
8826 ++i;
8827 }
Selene Huang31ab4042020-04-29 04:22:39 -07008828 }
8829 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008830 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008831}