blob: 051ace4d867b68ae0e1f77385aeda85617af11ee [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 }
2073 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01002074 }
2075}
2076
2077/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002078 * NewKeyGenerationTest.EcdsaAttestationIdTags
2079 *
2080 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2081 * attestation extension.
2082 */
2083TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002084 if (is_gsi_image()) {
2085 // GSI sets up a standard set of device identifiers that may not match
2086 // the device identifiers held by the device.
2087 GTEST_SKIP() << "Test not applicable under GSI";
2088 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002089 auto challenge = "hello";
2090 auto app_id = "foo";
2091 auto subject = "cert subj 2";
2092 vector<uint8_t> subject_der(make_name_from_str(subject));
2093 uint64_t serial_int = 0x1010;
2094 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2095 const AuthorizationSetBuilder base_builder =
2096 AuthorizationSetBuilder()
2097 .Authorization(TAG_NO_AUTH_REQUIRED)
2098 .EcdsaSigningKey(EcCurve::P_256)
2099 .Digest(Digest::NONE)
2100 .AttestationChallenge(challenge)
2101 .AttestationApplicationId(app_id)
2102 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2103 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2104 .SetDefaultValidity();
2105
2106 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2107 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil8d779bf2022-09-28 16:09:29 +01002108 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2109 // to ro.product.brand
2110 std::string prop_value =
2111 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2112 if (!prop_value.empty()) {
2113 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2114 "ro.product.brand_for_attestation");
2115 } else {
2116 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2117 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002118 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002119 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2120 // to ro.product.name
2121 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2122 if (!prop_value.empty()) {
2123 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2124 "ro.product.name_for_attestation");
2125 } else {
2126 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2127 }
Tri Vo799e4352022-11-07 17:23:50 -08002128 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002129 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002130 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2131 // to ro.product.model
2132 prop_value =
2133 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2134 if (!prop_value.empty()) {
2135 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2136 "ro.product.model_for_attestation");
2137 } else {
2138 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2139 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002140
2141 for (const KeyParameter& tag : extra_tags) {
2142 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2143 vector<uint8_t> key_blob;
2144 vector<KeyCharacteristics> key_characteristics;
2145 AuthorizationSetBuilder builder = base_builder;
2146 builder.push_back(tag);
2147 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002148 // Strongbox may not support factory provisioned attestation key.
2149 if (SecLevel() == SecurityLevel::STRONGBOX) {
2150 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2151 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002152 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2153 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002154 continue;
2155 }
2156 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002157 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002158 ASSERT_GT(key_blob.size(), 0U);
2159
2160 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2161 ASSERT_GT(cert_chain_.size(), 0);
2162 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2163
2164 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2165 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2166
2167 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2168 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2169 // attestation extension should contain them, so make sure the extra tag is added.
2170 hw_enforced.push_back(tag);
2171
2172 // Verifying the attestation record will check for the specific tag because
2173 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002174 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2175 hw_enforced, SecLevel(),
2176 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002177 }
2178}
2179
2180/*
David Drysdale565ccc72021-10-11 12:49:50 +01002181 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2182 *
2183 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2184 */
2185TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2186 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002187 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002188 auto challenge = "hello";
2189 auto subject = "cert subj 2";
2190 vector<uint8_t> subject_der(make_name_from_str(subject));
2191 uint64_t serial_int = 0x1010;
2192 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002193 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002194 AuthorizationSetBuilder()
2195 .Authorization(TAG_NO_AUTH_REQUIRED)
2196 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2197 .EcdsaSigningKey(EcCurve::P_256)
2198 .Digest(Digest::NONE)
2199 .AttestationChallenge(challenge)
2200 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2201 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2202 .AttestationApplicationId(app_id)
2203 .Authorization(TAG_CREATION_DATETIME, datetime)
2204 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002205 if (reset) {
2206 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2207 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002208 auto result = GenerateKey(builder);
2209 if (SecLevel() == SecurityLevel::STRONGBOX) {
2210 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2211 result = GenerateKeyWithSelfSignedAttestKey(
2212 AuthorizationSetBuilder()
2213 .EcdsaKey(EcCurve::P_256)
2214 .AttestKey()
2215 .SetDefaultValidity(), /* attest key params */
2216 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2217 }
2218 }
2219 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002220 ASSERT_GT(key_blob_.size(), 0U);
2221
2222 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2223 ASSERT_GT(cert_chain_.size(), 0);
2224 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2225
2226 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2227 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2228
2229 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002230 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2231 hw_enforced, SecLevel(),
2232 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002233 EXPECT_GT(unique_id->size(), 0);
2234 CheckedDeleteKey();
2235 };
2236
2237 // Generate unique ID
2238 auto app_id = "foo";
2239 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2240 vector<uint8_t> unique_id;
2241 get_unique_id(app_id, cert_date, &unique_id);
2242
2243 // Generating a new key with the same parameters should give the same unique ID.
2244 vector<uint8_t> unique_id2;
2245 get_unique_id(app_id, cert_date, &unique_id2);
2246 EXPECT_EQ(unique_id, unique_id2);
2247
2248 // Generating a new key with a slightly different date should give the same unique ID.
2249 uint64_t rounded_date = cert_date / 2592000000LLU;
2250 uint64_t min_date = rounded_date * 2592000000LLU;
2251 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2252
2253 vector<uint8_t> unique_id3;
2254 get_unique_id(app_id, min_date, &unique_id3);
2255 EXPECT_EQ(unique_id, unique_id3);
2256
2257 vector<uint8_t> unique_id4;
2258 get_unique_id(app_id, max_date, &unique_id4);
2259 EXPECT_EQ(unique_id, unique_id4);
2260
2261 // A different attestation application ID should yield a different unique ID.
2262 auto app_id2 = "different_foo";
2263 vector<uint8_t> unique_id5;
2264 get_unique_id(app_id2, cert_date, &unique_id5);
2265 EXPECT_NE(unique_id, unique_id5);
2266
2267 // A radically different date should yield a different unique ID.
2268 vector<uint8_t> unique_id6;
2269 get_unique_id(app_id, 1611621648000, &unique_id6);
2270 EXPECT_NE(unique_id, unique_id6);
2271
2272 vector<uint8_t> unique_id7;
2273 get_unique_id(app_id, max_date + 1, &unique_id7);
2274 EXPECT_NE(unique_id, unique_id7);
2275
2276 vector<uint8_t> unique_id8;
2277 get_unique_id(app_id, min_date - 1, &unique_id8);
2278 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002279
2280 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2281 vector<uint8_t> unique_id9;
2282 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2283 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002284}
2285
2286/*
David Drysdale37af4b32021-05-14 16:46:59 +01002287 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2288 *
2289 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2290 */
2291TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2292 auto challenge = "hello";
2293 auto attest_app_id = "foo";
2294 auto subject = "cert subj 2";
2295 vector<uint8_t> subject_der(make_name_from_str(subject));
2296 uint64_t serial_int = 0x1010;
2297 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2298
2299 // Earlier versions of the attestation extension schema included a slot:
2300 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2301 // This should never have been included, and should never be filled in.
2302 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2303 // to confirm that this field never makes it into the attestation extension.
2304 vector<uint8_t> key_blob;
2305 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002306 auto builder = AuthorizationSetBuilder()
2307 .Authorization(TAG_NO_AUTH_REQUIRED)
2308 .EcdsaSigningKey(EcCurve::P_256)
2309 .Digest(Digest::NONE)
2310 .AttestationChallenge(challenge)
2311 .AttestationApplicationId(attest_app_id)
2312 .Authorization(TAG_APPLICATION_ID, "client_id")
2313 .Authorization(TAG_APPLICATION_DATA, "appdata")
2314 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2315 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2316 .SetDefaultValidity();
2317
2318 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002319 // Strongbox may not support factory provisioned attestation key.
2320 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002321 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2322 result = GenerateKeyWithSelfSignedAttestKey(
2323 AuthorizationSetBuilder()
2324 .EcdsaKey(EcCurve::P_256)
2325 .AttestKey()
2326 .SetDefaultValidity(), /* attest key params */
2327 builder, &key_blob, &key_characteristics);
2328 }
subrahmanyaman05642492022-02-05 07:10:56 +00002329 }
David Drysdale37af4b32021-05-14 16:46:59 +01002330 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002331 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002332 ASSERT_GT(key_blob.size(), 0U);
2333
2334 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2335 ASSERT_GT(cert_chain_.size(), 0);
2336 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2337
2338 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2339 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002340 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2341 hw_enforced, SecLevel(),
2342 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002343
2344 // Check that the app id is not in the cert.
2345 string app_id = "clientid";
2346 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2347 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2348 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2349 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2350 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002351}
2352
2353/*
Selene Huang4f64c222021-04-13 19:54:36 -07002354 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2355 *
2356 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2357 * the key will generate a self signed attestation.
2358 */
2359TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002360 auto subject = "cert subj 2";
2361 vector<uint8_t> subject_der(make_name_from_str(subject));
2362
2363 uint64_t serial_int = 0x123456FFF1234;
2364 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2365
David Drysdaledf09e542021-06-08 15:46:11 +01002366 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002367 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002368 vector<uint8_t> key_blob;
2369 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002370 ASSERT_EQ(ErrorCode::OK,
2371 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002372 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002373 .Digest(Digest::NONE)
2374 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2375 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2376 .SetDefaultValidity(),
2377 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002378 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002379 ASSERT_GT(key_blob.size(), 0U);
2380 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002381 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002382
2383 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2384
2385 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002386 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002387
2388 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2389 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002390 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002391
2392 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2393 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002394 }
2395}
2396
2397/*
2398 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2399 *
2400 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2401 * app id must also be provided or else it will fail.
2402 */
2403TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2404 auto challenge = "hello";
2405 vector<uint8_t> key_blob;
2406 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002407 auto builder = AuthorizationSetBuilder()
2408 .EcdsaSigningKey(EcCurve::P_256)
2409 .Digest(Digest::NONE)
2410 .AttestationChallenge(challenge)
2411 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002412
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002413 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002414 // Strongbox may not support factory provisioned attestation key.
2415 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002416 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2417 result = GenerateKeyWithSelfSignedAttestKey(
2418 AuthorizationSetBuilder()
2419 .EcdsaKey(EcCurve::P_256)
2420 .AttestKey()
2421 .SetDefaultValidity(), /* attest key params */
2422 builder, &key_blob, &key_characteristics);
2423 }
subrahmanyaman05642492022-02-05 07:10:56 +00002424 }
2425 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002426}
2427
2428/*
2429 * NewKeyGenerationTest.EcdsaIgnoreAppId
2430 *
2431 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2432 * any appid will be ignored, and keymint will generate a self sign certificate.
2433 */
2434TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2435 auto app_id = "foo";
2436
David Drysdaledf09e542021-06-08 15:46:11 +01002437 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002438 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002439 vector<uint8_t> key_blob;
2440 vector<KeyCharacteristics> key_characteristics;
2441 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002442 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002443 .Digest(Digest::NONE)
2444 .AttestationApplicationId(app_id)
2445 .SetDefaultValidity(),
2446 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002447 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002448
2449 ASSERT_GT(key_blob.size(), 0U);
2450 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002451 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002452
2453 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2454
2455 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002456 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002457
2458 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2459 ASSERT_EQ(cert_chain_.size(), 1);
2460
2461 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2462 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002463 }
2464}
2465
2466/*
2467 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2468 *
2469 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2470 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2471 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2472 * to specify how many following bytes will be used to encode the length.
2473 */
2474TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2475 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002476 std::vector<uint32_t> app_id_lengths{143, 258};
2477
2478 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002479 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002480 const string app_id(length, 'a');
2481 vector<uint8_t> key_blob;
2482 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002483 auto builder = AuthorizationSetBuilder()
2484 .Authorization(TAG_NO_AUTH_REQUIRED)
2485 .EcdsaSigningKey(EcCurve::P_256)
2486 .Digest(Digest::NONE)
2487 .AttestationChallenge(challenge)
2488 .AttestationApplicationId(app_id)
2489 .SetDefaultValidity();
2490
2491 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002492 // Strongbox may not support factory provisioned attestation key.
2493 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002494 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2495 result = GenerateKeyWithSelfSignedAttestKey(
2496 AuthorizationSetBuilder()
2497 .EcdsaKey(EcCurve::P_256)
2498 .AttestKey()
2499 .SetDefaultValidity(), /* attest key params */
2500 builder, &key_blob, &key_characteristics);
2501 }
subrahmanyaman05642492022-02-05 07:10:56 +00002502 }
2503 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002504 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002505 ASSERT_GT(key_blob.size(), 0U);
2506 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002507 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002508
2509 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2510
2511 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002512 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002513
2514 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2515 ASSERT_GT(cert_chain_.size(), 0);
2516
2517 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2518 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002519 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002520 sw_enforced, hw_enforced, SecLevel(),
2521 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002522 }
2523}
2524
2525/*
Qi Wud22ec842020-11-26 13:27:53 +08002526 * NewKeyGenerationTest.LimitedUsageEcdsa
2527 *
2528 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2529 * resulting keys have correct characteristics.
2530 */
2531TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002532 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002533 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002534 vector<uint8_t> key_blob;
2535 vector<KeyCharacteristics> key_characteristics;
2536 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002537 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002538 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002539 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2540 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002541 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002542 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002543
2544 ASSERT_GT(key_blob.size(), 0U);
2545 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002546 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002547
2548 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2549
2550 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002551 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002552
2553 // Check the usage count limit tag appears in the authorizations.
2554 AuthorizationSet auths;
2555 for (auto& entry : key_characteristics) {
2556 auths.push_back(AuthorizationSet(entry.authorizations));
2557 }
2558 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2559 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002560 }
2561}
2562
2563/*
Selene Huang31ab4042020-04-29 04:22:39 -07002564 * NewKeyGenerationTest.EcdsaDefaultSize
2565 *
David Drysdaledf09e542021-06-08 15:46:11 +01002566 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002567 * UNSUPPORTED_KEY_SIZE.
2568 */
2569TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2570 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2571 GenerateKey(AuthorizationSetBuilder()
2572 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2573 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002574 .Digest(Digest::NONE)
2575 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002576}
2577
2578/*
David Drysdale42fe1892021-10-14 14:43:46 +01002579 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002580 *
David Drysdale42fe1892021-10-14 14:43:46 +01002581 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002582 * UNSUPPORTED_KEY_SIZE.
2583 */
David Drysdale42fe1892021-10-14 14:43:46 +01002584TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002585 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002586 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002587 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002588 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002589 auto result = GenerateKey(AuthorizationSetBuilder()
2590 .EcdsaSigningKey(curve)
2591 .Digest(Digest::NONE)
2592 .SetDefaultValidity(),
2593 &key_blob, &key_characteristics);
2594 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2595 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002596 }
2597
David Drysdaledf09e542021-06-08 15:46:11 +01002598 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2599 GenerateKey(AuthorizationSetBuilder()
2600 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2601 .Authorization(TAG_KEY_SIZE, 190)
2602 .SigningKey()
2603 .Digest(Digest::NONE)
2604 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002605}
2606
2607/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002608 * NewKeyGenerationTest.EcdsaMissingCurve
2609 *
2610 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2611 */
2612TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2613 if (AidlVersion() < 2) {
2614 /*
2615 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2616 * However, this was not checked at the time so we can only be strict about checking this
2617 * for implementations of KeyMint version 2 and above.
2618 */
2619 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2620 }
2621 /* If EC_CURVE not provided, generateKey
2622 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2623 */
2624 auto result = GenerateKey(
2625 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2626 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2627 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2628}
2629
2630/*
Selene Huang31ab4042020-04-29 04:22:39 -07002631 * NewKeyGenerationTest.EcdsaMismatchKeySize
2632 *
2633 * Verifies that specifying mismatched key size and curve for EC key generation returns
2634 * INVALID_ARGUMENT.
2635 */
2636TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002637 if (SecLevel() == SecurityLevel::STRONGBOX) {
2638 GTEST_SKIP() << "Test not applicable to StrongBox device";
2639 }
Selene Huang31ab4042020-04-29 04:22:39 -07002640
David Drysdaledf09e542021-06-08 15:46:11 +01002641 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002642 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002643 .Authorization(TAG_KEY_SIZE, 224)
2644 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002645 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002646 .Digest(Digest::NONE)
2647 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002648 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002649}
2650
2651/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002652 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002653 *
2654 * Verifies that keymint does not support any curve designated as unsupported.
2655 */
2656TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2657 Digest digest;
2658 if (SecLevel() == SecurityLevel::STRONGBOX) {
2659 digest = Digest::SHA_2_256;
2660 } else {
2661 digest = Digest::SHA_2_512;
2662 }
2663 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002664 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002665 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2666 .EcdsaSigningKey(curve)
2667 .Digest(digest)
2668 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002669 << "Failed to generate key on curve: " << curve;
2670 CheckedDeleteKey();
2671 }
2672}
2673
2674/*
2675 * NewKeyGenerationTest.Hmac
2676 *
2677 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2678 * characteristics.
2679 */
2680TEST_P(NewKeyGenerationTest, Hmac) {
2681 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002682 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002683 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002684 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002685 constexpr size_t key_size = 128;
2686 ASSERT_EQ(ErrorCode::OK,
2687 GenerateKey(
2688 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2689 TAG_MIN_MAC_LENGTH, 128),
2690 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002691 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002692
2693 ASSERT_GT(key_blob.size(), 0U);
2694 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002695 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002696
Shawn Willden7f424372021-01-10 18:06:50 -07002697 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2698 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2699 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2700 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002701 }
2702}
2703
2704/*
Selene Huang4f64c222021-04-13 19:54:36 -07002705 * NewKeyGenerationTest.HmacNoAttestation
2706 *
2707 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2708 * and app id are provided.
2709 */
2710TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2711 auto challenge = "hello";
2712 auto app_id = "foo";
2713
2714 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002715 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002716 vector<uint8_t> key_blob;
2717 vector<KeyCharacteristics> key_characteristics;
2718 constexpr size_t key_size = 128;
2719 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2720 .HmacKey(key_size)
2721 .Digest(digest)
2722 .AttestationChallenge(challenge)
2723 .AttestationApplicationId(app_id)
2724 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2725 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002726 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002727
2728 ASSERT_GT(key_blob.size(), 0U);
2729 ASSERT_EQ(cert_chain_.size(), 0);
2730 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002731 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002732
2733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2734 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2735 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2736 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002737 }
2738}
2739
2740/*
Qi Wud22ec842020-11-26 13:27:53 +08002741 * NewKeyGenerationTest.LimitedUsageHmac
2742 *
2743 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2744 * resulting keys have correct characteristics.
2745 */
2746TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2747 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002748 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002749 vector<uint8_t> key_blob;
2750 vector<KeyCharacteristics> key_characteristics;
2751 constexpr size_t key_size = 128;
2752 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2753 .HmacKey(key_size)
2754 .Digest(digest)
2755 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2756 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2757 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002758 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002759
2760 ASSERT_GT(key_blob.size(), 0U);
2761 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002762 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002763
2764 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2765 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2766 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2767 << "Key size " << key_size << "missing";
2768
2769 // Check the usage count limit tag appears in the authorizations.
2770 AuthorizationSet auths;
2771 for (auto& entry : key_characteristics) {
2772 auths.push_back(AuthorizationSet(entry.authorizations));
2773 }
2774 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2775 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002776 }
2777}
2778
2779/*
Selene Huang31ab4042020-04-29 04:22:39 -07002780 * NewKeyGenerationTest.HmacCheckKeySizes
2781 *
2782 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2783 */
2784TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2785 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002786 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002787 if (key_size < 64 || key_size % 8 != 0) {
2788 // To keep this test from being very slow, we only test a random fraction of
2789 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2790 // them, we expect to run ~40 of them in each run.
2791 if (key_size % 8 == 0 || random() % 10 == 0) {
2792 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2793 GenerateKey(AuthorizationSetBuilder()
2794 .HmacKey(key_size)
2795 .Digest(Digest::SHA_2_256)
2796 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2797 << "HMAC key size " << key_size << " invalid";
2798 }
2799 } else {
2800 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2801 .HmacKey(key_size)
2802 .Digest(Digest::SHA_2_256)
2803 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2804 << "Failed to generate HMAC key of size " << key_size;
2805 CheckedDeleteKey();
2806 }
2807 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002808 if (SecLevel() == SecurityLevel::STRONGBOX) {
2809 // STRONGBOX devices must not support keys larger than 512 bits.
2810 size_t key_size = 520;
2811 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2812 GenerateKey(AuthorizationSetBuilder()
2813 .HmacKey(key_size)
2814 .Digest(Digest::SHA_2_256)
2815 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2816 << "HMAC key size " << key_size << " unexpectedly valid";
2817 }
Selene Huang31ab4042020-04-29 04:22:39 -07002818}
2819
2820/*
2821 * NewKeyGenerationTest.HmacCheckMinMacLengths
2822 *
2823 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2824 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2825 * specific MAC length that failed, so reproducing a failed run will be easy.
2826 */
2827TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2828 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002829 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002830 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2831 // To keep this test from being very long, we only test a random fraction of
2832 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2833 // we expect to run ~17 of them in each run.
2834 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2835 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2836 GenerateKey(AuthorizationSetBuilder()
2837 .HmacKey(128)
2838 .Digest(Digest::SHA_2_256)
2839 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2840 << "HMAC min mac length " << min_mac_length << " invalid.";
2841 }
2842 } else {
2843 EXPECT_EQ(ErrorCode::OK,
2844 GenerateKey(AuthorizationSetBuilder()
2845 .HmacKey(128)
2846 .Digest(Digest::SHA_2_256)
2847 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2848 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2849 CheckedDeleteKey();
2850 }
2851 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002852
2853 // Minimum MAC length must be no more than 512 bits.
2854 size_t min_mac_length = 520;
2855 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2856 GenerateKey(AuthorizationSetBuilder()
2857 .HmacKey(128)
2858 .Digest(Digest::SHA_2_256)
2859 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2860 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002861}
2862
2863/*
2864 * NewKeyGenerationTest.HmacMultipleDigests
2865 *
2866 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2867 */
2868TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002869 if (SecLevel() == SecurityLevel::STRONGBOX) {
2870 GTEST_SKIP() << "Test not applicable to StrongBox device";
2871 }
Selene Huang31ab4042020-04-29 04:22:39 -07002872
2873 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2874 GenerateKey(AuthorizationSetBuilder()
2875 .HmacKey(128)
2876 .Digest(Digest::SHA1)
2877 .Digest(Digest::SHA_2_256)
2878 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2879}
2880
2881/*
2882 * NewKeyGenerationTest.HmacDigestNone
2883 *
2884 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2885 */
2886TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2887 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2888 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2889 128)));
2890
2891 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2892 GenerateKey(AuthorizationSetBuilder()
2893 .HmacKey(128)
2894 .Digest(Digest::NONE)
2895 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2896}
2897
Selene Huang4f64c222021-04-13 19:54:36 -07002898/*
2899 * NewKeyGenerationTest.AesNoAttestation
2900 *
2901 * Verifies that attestation parameters to AES keys are ignored and generateKey
2902 * will succeed.
2903 */
2904TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2905 auto challenge = "hello";
2906 auto app_id = "foo";
2907
2908 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2909 .Authorization(TAG_NO_AUTH_REQUIRED)
2910 .AesEncryptionKey(128)
2911 .EcbMode()
2912 .Padding(PaddingMode::PKCS7)
2913 .AttestationChallenge(challenge)
2914 .AttestationApplicationId(app_id)));
2915
2916 ASSERT_EQ(cert_chain_.size(), 0);
2917}
2918
2919/*
2920 * NewKeyGenerationTest.TripleDesNoAttestation
2921 *
2922 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2923 * will be successful. No attestation should be generated.
2924 */
2925TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2926 auto challenge = "hello";
2927 auto app_id = "foo";
2928
2929 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2930 .TripleDesEncryptionKey(168)
2931 .BlockMode(BlockMode::ECB)
2932 .Authorization(TAG_NO_AUTH_REQUIRED)
2933 .Padding(PaddingMode::NONE)
2934 .AttestationChallenge(challenge)
2935 .AttestationApplicationId(app_id)));
2936 ASSERT_EQ(cert_chain_.size(), 0);
2937}
2938
Selene Huang31ab4042020-04-29 04:22:39 -07002939INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2940
2941typedef KeyMintAidlTestBase SigningOperationsTest;
2942
2943/*
2944 * SigningOperationsTest.RsaSuccess
2945 *
2946 * Verifies that raw RSA signature operations succeed.
2947 */
2948TEST_P(SigningOperationsTest, RsaSuccess) {
2949 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2950 .RsaSigningKey(2048, 65537)
2951 .Digest(Digest::NONE)
2952 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002953 .Authorization(TAG_NO_AUTH_REQUIRED)
2954 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002955 string message = "12345678901234567890123456789012";
2956 string signature = SignMessage(
2957 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002958 LocalVerifyMessage(message, signature,
2959 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2960}
2961
2962/*
2963 * SigningOperationsTest.RsaAllPaddingsAndDigests
2964 *
2965 * Verifies RSA signature/verification for all padding modes and digests.
2966 */
2967TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2968 auto authorizations = AuthorizationSetBuilder()
2969 .Authorization(TAG_NO_AUTH_REQUIRED)
2970 .RsaSigningKey(2048, 65537)
2971 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2972 .Padding(PaddingMode::NONE)
2973 .Padding(PaddingMode::RSA_PSS)
2974 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2975 .SetDefaultValidity();
2976
2977 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2978
2979 string message(128, 'a');
2980 string corrupt_message(message);
2981 ++corrupt_message[corrupt_message.size() / 2];
2982
2983 for (auto padding :
2984 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2985 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002986 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002987 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2988 // Digesting only makes sense with padding.
2989 continue;
2990 }
2991
2992 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2993 // PSS requires digesting.
2994 continue;
2995 }
2996
2997 string signature =
2998 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2999 LocalVerifyMessage(message, signature,
3000 AuthorizationSetBuilder().Digest(digest).Padding(padding));
3001 }
3002 }
Selene Huang31ab4042020-04-29 04:22:39 -07003003}
3004
3005/*
3006 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3007 *
Shawn Willden7f424372021-01-10 18:06:50 -07003008 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003009 */
3010TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3011 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3012 .Authorization(TAG_NO_AUTH_REQUIRED)
3013 .RsaSigningKey(2048, 65537)
3014 .Digest(Digest::NONE)
3015 .Padding(PaddingMode::NONE)
3016 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003017 .Authorization(TAG_APPLICATION_DATA, "appdata")
3018 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003019
3020 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3021
Selene Huang31ab4042020-04-29 04:22:39 -07003022 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3023 Begin(KeyPurpose::SIGN,
3024 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3025 AbortIfNeeded();
3026 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3027 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3028 .Digest(Digest::NONE)
3029 .Padding(PaddingMode::NONE)
3030 .Authorization(TAG_APPLICATION_ID, "clientid")));
3031 AbortIfNeeded();
3032 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3033 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3034 .Digest(Digest::NONE)
3035 .Padding(PaddingMode::NONE)
3036 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3037 AbortIfNeeded();
3038 EXPECT_EQ(ErrorCode::OK,
3039 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3040 .Digest(Digest::NONE)
3041 .Padding(PaddingMode::NONE)
3042 .Authorization(TAG_APPLICATION_DATA, "appdata")
3043 .Authorization(TAG_APPLICATION_ID, "clientid")));
3044 AbortIfNeeded();
3045}
3046
3047/*
3048 * SigningOperationsTest.RsaPssSha256Success
3049 *
3050 * Verifies that RSA-PSS signature operations succeed.
3051 */
3052TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3053 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3054 .RsaSigningKey(2048, 65537)
3055 .Digest(Digest::SHA_2_256)
3056 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003057 .Authorization(TAG_NO_AUTH_REQUIRED)
3058 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003059 // Use large message, which won't work without digesting.
3060 string message(1024, 'a');
3061 string signature = SignMessage(
3062 message,
3063 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3064}
3065
3066/*
3067 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3068 *
3069 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3070 * supports only unpadded operations.
3071 */
3072TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3073 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3074 .RsaSigningKey(2048, 65537)
3075 .Digest(Digest::NONE)
3076 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003077 .Padding(PaddingMode::NONE)
3078 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003079 string message = "12345678901234567890123456789012";
3080 string signature;
3081
3082 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3083 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3084 .Digest(Digest::NONE)
3085 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3086}
3087
3088/*
3089 * SigningOperationsTest.NoUserConfirmation
3090 *
3091 * Verifies that keymint rejects signing operations for keys with
3092 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3093 * presented.
3094 */
3095TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003097 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003098 .Digest(Digest::NONE)
3099 .Padding(PaddingMode::NONE)
3100 .Authorization(TAG_NO_AUTH_REQUIRED)
3101 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3102 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003103
3104 const string message = "12345678901234567890123456789012";
3105 EXPECT_EQ(ErrorCode::OK,
3106 Begin(KeyPurpose::SIGN,
3107 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3108 string signature;
3109 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3110}
3111
3112/*
3113 * SigningOperationsTest.RsaPkcs1Sha256Success
3114 *
3115 * Verifies that digested RSA-PKCS1 signature operations succeed.
3116 */
3117TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3118 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3119 .RsaSigningKey(2048, 65537)
3120 .Digest(Digest::SHA_2_256)
3121 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003122 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3123 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003124 string message(1024, 'a');
3125 string signature = SignMessage(message, AuthorizationSetBuilder()
3126 .Digest(Digest::SHA_2_256)
3127 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3128}
3129
3130/*
3131 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3132 *
3133 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3134 */
3135TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3136 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3137 .RsaSigningKey(2048, 65537)
3138 .Digest(Digest::NONE)
3139 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003140 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3141 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003142 string message(53, 'a');
3143 string signature = SignMessage(message, AuthorizationSetBuilder()
3144 .Digest(Digest::NONE)
3145 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3146}
3147
3148/*
3149 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3150 *
3151 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3152 * given a too-long message.
3153 */
3154TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3156 .RsaSigningKey(2048, 65537)
3157 .Digest(Digest::NONE)
3158 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003159 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3160 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003161 string message(257, 'a');
3162
3163 EXPECT_EQ(ErrorCode::OK,
3164 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3165 .Digest(Digest::NONE)
3166 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3167 string signature;
3168 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3169}
3170
3171/*
3172 * SigningOperationsTest.RsaPssSha512TooSmallKey
3173 *
3174 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3175 * used with a key that is too small for the message.
3176 *
3177 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3178 * keymint specification requires that salt_size == digest_size, so the message will be
3179 * digest_size * 2 +
3180 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3181 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3182 * for a 1024-bit key.
3183 */
3184TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003185 if (SecLevel() == SecurityLevel::STRONGBOX) {
3186 GTEST_SKIP() << "Test not applicable to StrongBox device";
3187 }
Selene Huang31ab4042020-04-29 04:22:39 -07003188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3189 .RsaSigningKey(1024, 65537)
3190 .Digest(Digest::SHA_2_512)
3191 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003192 .Padding(PaddingMode::RSA_PSS)
3193 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003194 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3195 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3196 .Digest(Digest::SHA_2_512)
3197 .Padding(PaddingMode::RSA_PSS)));
3198}
3199
3200/*
3201 * SigningOperationsTest.RsaNoPaddingTooLong
3202 *
3203 * Verifies that raw RSA signature operations fail with the correct error code when
3204 * given a too-long message.
3205 */
3206TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3207 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3208 .RsaSigningKey(2048, 65537)
3209 .Digest(Digest::NONE)
3210 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003211 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3212 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003213 // One byte too long
3214 string message(2048 / 8 + 1, 'a');
3215 ASSERT_EQ(ErrorCode::OK,
3216 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3217 .Digest(Digest::NONE)
3218 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3219 string result;
3220 ErrorCode finish_error_code = Finish(message, &result);
3221 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3222 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3223
3224 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3225 message = string(128 * 1024, 'a');
3226 ASSERT_EQ(ErrorCode::OK,
3227 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3228 .Digest(Digest::NONE)
3229 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3230 finish_error_code = Finish(message, &result);
3231 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3232 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3233}
3234
3235/*
3236 * SigningOperationsTest.RsaAbort
3237 *
3238 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3239 * test, but the behavior should be algorithm and purpose-independent.
3240 */
3241TEST_P(SigningOperationsTest, RsaAbort) {
3242 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3243 .RsaSigningKey(2048, 65537)
3244 .Digest(Digest::NONE)
3245 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003246 .Padding(PaddingMode::NONE)
3247 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003248
3249 ASSERT_EQ(ErrorCode::OK,
3250 Begin(KeyPurpose::SIGN,
3251 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3252 EXPECT_EQ(ErrorCode::OK, Abort());
3253
3254 // Another abort should fail
3255 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3256
3257 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003258 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003259}
3260
3261/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003262 * SigningOperationsTest.RsaNonUniqueParams
3263 *
3264 * Verifies that an operation with multiple padding modes is rejected.
3265 */
3266TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3267 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3268 .RsaSigningKey(2048, 65537)
3269 .Digest(Digest::NONE)
3270 .Digest(Digest::SHA1)
3271 .Authorization(TAG_NO_AUTH_REQUIRED)
3272 .Padding(PaddingMode::NONE)
3273 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3274 .SetDefaultValidity()));
3275
3276 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3277 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3278 .Digest(Digest::NONE)
3279 .Padding(PaddingMode::NONE)
3280 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3281
Tommy Chiuc93c4392021-05-11 18:36:50 +08003282 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3283 .Digest(Digest::NONE)
3284 .Digest(Digest::SHA1)
3285 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3286 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003287
3288 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3289 Begin(KeyPurpose::SIGN,
3290 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3291}
3292
3293/*
Selene Huang31ab4042020-04-29 04:22:39 -07003294 * SigningOperationsTest.RsaUnsupportedPadding
3295 *
3296 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3297 * with a padding mode inappropriate for RSA.
3298 */
3299TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3300 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3301 .RsaSigningKey(2048, 65537)
3302 .Authorization(TAG_NO_AUTH_REQUIRED)
3303 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003304 .Padding(PaddingMode::PKCS7)
3305 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003306 ASSERT_EQ(
3307 ErrorCode::UNSUPPORTED_PADDING_MODE,
3308 Begin(KeyPurpose::SIGN,
3309 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003310 CheckedDeleteKey();
3311
3312 ASSERT_EQ(ErrorCode::OK,
3313 GenerateKey(
3314 AuthorizationSetBuilder()
3315 .RsaSigningKey(2048, 65537)
3316 .Authorization(TAG_NO_AUTH_REQUIRED)
3317 .Digest(Digest::SHA_2_256 /* supported digest */)
3318 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3319 .SetDefaultValidity()));
3320 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3321 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3322 .Digest(Digest::SHA_2_256)
3323 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003324}
3325
3326/*
3327 * SigningOperationsTest.RsaPssNoDigest
3328 *
3329 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3330 */
3331TEST_P(SigningOperationsTest, RsaNoDigest) {
3332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3333 .RsaSigningKey(2048, 65537)
3334 .Authorization(TAG_NO_AUTH_REQUIRED)
3335 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003336 .Padding(PaddingMode::RSA_PSS)
3337 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003338 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3339 Begin(KeyPurpose::SIGN,
3340 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3341
3342 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3343 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3344}
3345
3346/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003347 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003348 *
3349 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3350 * supported in some cases (as validated in other tests), but a mode must be specified.
3351 */
3352TEST_P(SigningOperationsTest, RsaNoPadding) {
3353 // Padding must be specified
3354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3355 .RsaKey(2048, 65537)
3356 .Authorization(TAG_NO_AUTH_REQUIRED)
3357 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003358 .Digest(Digest::NONE)
3359 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003360 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3361 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3362}
3363
3364/*
3365 * SigningOperationsTest.RsaShortMessage
3366 *
3367 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3368 */
3369TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3371 .Authorization(TAG_NO_AUTH_REQUIRED)
3372 .RsaSigningKey(2048, 65537)
3373 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003374 .Padding(PaddingMode::NONE)
3375 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003376
3377 // Barely shorter
3378 string message(2048 / 8 - 1, 'a');
3379 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3380
3381 // Much shorter
3382 message = "a";
3383 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3384}
3385
3386/*
3387 * SigningOperationsTest.RsaSignWithEncryptionKey
3388 *
3389 * Verifies that RSA encryption keys cannot be used to sign.
3390 */
3391TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3393 .Authorization(TAG_NO_AUTH_REQUIRED)
3394 .RsaEncryptionKey(2048, 65537)
3395 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003396 .Padding(PaddingMode::NONE)
3397 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003398 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3399 Begin(KeyPurpose::SIGN,
3400 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3401}
3402
3403/*
3404 * SigningOperationsTest.RsaSignTooLargeMessage
3405 *
3406 * Verifies that attempting a raw signature of a message which is the same length as the key,
3407 * but numerically larger than the public modulus, fails with the correct error.
3408 */
3409TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3410 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3411 .Authorization(TAG_NO_AUTH_REQUIRED)
3412 .RsaSigningKey(2048, 65537)
3413 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003414 .Padding(PaddingMode::NONE)
3415 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003416
3417 // Largest possible message will always be larger than the public modulus.
3418 string message(2048 / 8, static_cast<char>(0xff));
3419 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3420 .Authorization(TAG_NO_AUTH_REQUIRED)
3421 .Digest(Digest::NONE)
3422 .Padding(PaddingMode::NONE)));
3423 string signature;
3424 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3425}
3426
3427/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003428 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3429 *
David Drysdale42fe1892021-10-14 14:43:46 +01003430 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003431 */
3432TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003433 string message = "1234567890";
3434 string corrupt_message = "2234567890";
3435 for (auto curve : ValidCurves()) {
3436 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003437 // Ed25519 only allows Digest::NONE.
3438 auto digests = (curve == EcCurve::CURVE_25519)
3439 ? std::vector<Digest>(1, Digest::NONE)
3440 : ValidDigests(true /* withNone */, false /* withMD5 */);
3441
David Drysdaledf8f52e2021-05-06 08:10:58 +01003442 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3443 .Authorization(TAG_NO_AUTH_REQUIRED)
3444 .EcdsaSigningKey(curve)
3445 .Digest(digests)
3446 .SetDefaultValidity());
3447 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3448 if (error != ErrorCode::OK) {
3449 continue;
3450 }
3451
3452 for (auto digest : digests) {
3453 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3454 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3455 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3456 }
3457
3458 auto rc = DeleteKey();
3459 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3460 }
3461}
3462
3463/*
Selene Huang31ab4042020-04-29 04:22:39 -07003464 * SigningOperationsTest.EcdsaAllCurves
3465 *
David Drysdale42fe1892021-10-14 14:43:46 +01003466 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003467 */
3468TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3469 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003470 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3471 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003472 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3473 .Authorization(TAG_NO_AUTH_REQUIRED)
3474 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003475 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003476 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003477 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3478 if (error != ErrorCode::OK) continue;
3479
3480 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003481 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003482 CheckedDeleteKey();
3483 }
3484}
3485
3486/*
David Drysdale42fe1892021-10-14 14:43:46 +01003487 * SigningOperationsTest.EcdsaCurve25519
3488 *
3489 * Verifies that ECDSA operations succeed with curve25519.
3490 */
3491TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3492 if (!Curve25519Supported()) {
3493 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3494 }
3495
3496 EcCurve curve = EcCurve::CURVE_25519;
3497 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3498 .Authorization(TAG_NO_AUTH_REQUIRED)
3499 .EcdsaSigningKey(curve)
3500 .Digest(Digest::NONE)
3501 .SetDefaultValidity());
3502 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3503
3504 string message(1024, 'a');
3505 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3506 CheckedDeleteKey();
3507}
3508
3509/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003510 * SigningOperationsTest.EcdsaCurve25519MaxSize
3511 *
3512 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3513 */
3514TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3515 if (!Curve25519Supported()) {
3516 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3517 }
3518
3519 EcCurve curve = EcCurve::CURVE_25519;
3520 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3521 .Authorization(TAG_NO_AUTH_REQUIRED)
3522 .EcdsaSigningKey(curve)
3523 .Digest(Digest::NONE)
3524 .SetDefaultValidity());
3525 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3526
3527 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3528
3529 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3530 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3531 string message(msg_size, 'a');
3532
3533 // Attempt to sign via Begin+Finish.
3534 AuthorizationSet out_params;
3535 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3536 EXPECT_TRUE(out_params.empty());
3537 string signature;
3538 auto result = Finish(message, &signature);
3539 EXPECT_EQ(result, ErrorCode::OK);
3540 LocalVerifyMessage(message, signature, params);
3541
3542 // Attempt to sign via Begin+Update+Finish
3543 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3544 EXPECT_TRUE(out_params.empty());
3545 string output;
3546 result = Update(message, &output);
3547 EXPECT_EQ(result, ErrorCode::OK);
3548 EXPECT_EQ(output.size(), 0);
3549 string signature2;
3550 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3551 LocalVerifyMessage(message, signature2, params);
3552 }
3553
3554 CheckedDeleteKey();
3555}
3556
3557/*
3558 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3559 *
3560 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3561 */
3562TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3563 if (!Curve25519Supported()) {
3564 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3565 }
3566
3567 EcCurve curve = EcCurve::CURVE_25519;
3568 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3569 .Authorization(TAG_NO_AUTH_REQUIRED)
3570 .EcdsaSigningKey(curve)
3571 .Digest(Digest::NONE)
3572 .SetDefaultValidity());
3573 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3574
3575 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3576
3577 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3578 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3579 string message(msg_size, 'a');
3580
3581 // Attempt to sign via Begin+Finish.
3582 AuthorizationSet out_params;
3583 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3584 EXPECT_TRUE(out_params.empty());
3585 string signature;
3586 auto result = Finish(message, &signature);
3587 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3588
3589 // Attempt to sign via Begin+Update (but never get to Finish)
3590 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3591 EXPECT_TRUE(out_params.empty());
3592 string output;
3593 result = Update(message, &output);
3594 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3595 }
3596
3597 CheckedDeleteKey();
3598}
3599
3600/*
Selene Huang31ab4042020-04-29 04:22:39 -07003601 * SigningOperationsTest.EcdsaNoDigestHugeData
3602 *
3603 * Verifies that ECDSA operations support very large messages, even without digesting. This
3604 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3605 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3606 * the framework.
3607 */
3608TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3610 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003611 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003612 .Digest(Digest::NONE)
3613 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003614 string message(1 * 1024, 'a');
3615 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3616}
3617
3618/*
3619 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3620 *
3621 * Verifies that using an EC key requires the correct app ID/data.
3622 */
3623TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3624 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3625 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003626 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003627 .Digest(Digest::NONE)
3628 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003629 .Authorization(TAG_APPLICATION_DATA, "appdata")
3630 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003631
3632 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3633
Selene Huang31ab4042020-04-29 04:22:39 -07003634 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3635 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3636 AbortIfNeeded();
3637 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3638 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3639 .Digest(Digest::NONE)
3640 .Authorization(TAG_APPLICATION_ID, "clientid")));
3641 AbortIfNeeded();
3642 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3643 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3644 .Digest(Digest::NONE)
3645 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3646 AbortIfNeeded();
3647 EXPECT_EQ(ErrorCode::OK,
3648 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3649 .Digest(Digest::NONE)
3650 .Authorization(TAG_APPLICATION_DATA, "appdata")
3651 .Authorization(TAG_APPLICATION_ID, "clientid")));
3652 AbortIfNeeded();
3653}
3654
3655/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003656 * SigningOperationsTest.EcdsaIncompatibleDigest
3657 *
3658 * Verifies that using an EC key requires compatible digest.
3659 */
3660TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3662 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003663 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003664 .Digest(Digest::NONE)
3665 .Digest(Digest::SHA1)
3666 .SetDefaultValidity()));
3667 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3668 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3669 AbortIfNeeded();
3670}
3671
3672/*
Selene Huang31ab4042020-04-29 04:22:39 -07003673 * SigningOperationsTest.AesEcbSign
3674 *
3675 * Verifies that attempts to use AES keys to sign fail in the correct way.
3676 */
3677TEST_P(SigningOperationsTest, AesEcbSign) {
3678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3679 .Authorization(TAG_NO_AUTH_REQUIRED)
3680 .SigningKey()
3681 .AesEncryptionKey(128)
3682 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3683
3684 AuthorizationSet out_params;
3685 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3686 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3687 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3688 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3689}
3690
3691/*
3692 * SigningOperationsTest.HmacAllDigests
3693 *
3694 * Verifies that HMAC works with all digests.
3695 */
3696TEST_P(SigningOperationsTest, HmacAllDigests) {
3697 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003698 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003699 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3700 .Authorization(TAG_NO_AUTH_REQUIRED)
3701 .HmacKey(128)
3702 .Digest(digest)
3703 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3704 << "Failed to create HMAC key with digest " << digest;
3705 string message = "12345678901234567890123456789012";
3706 string signature = MacMessage(message, digest, 160);
3707 EXPECT_EQ(160U / 8U, signature.size())
3708 << "Failed to sign with HMAC key with digest " << digest;
3709 CheckedDeleteKey();
3710 }
3711}
3712
3713/*
3714 * SigningOperationsTest.HmacSha256TooLargeMacLength
3715 *
3716 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3717 * digest size.
3718 */
3719TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3720 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3721 .Authorization(TAG_NO_AUTH_REQUIRED)
3722 .HmacKey(128)
3723 .Digest(Digest::SHA_2_256)
3724 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3725 AuthorizationSet output_params;
3726 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3727 AuthorizationSetBuilder()
3728 .Digest(Digest::SHA_2_256)
3729 .Authorization(TAG_MAC_LENGTH, 264),
3730 &output_params));
3731}
3732
3733/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003734 * SigningOperationsTest.HmacSha256InvalidMacLength
3735 *
3736 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3737 * not a multiple of 8.
3738 */
3739TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3741 .Authorization(TAG_NO_AUTH_REQUIRED)
3742 .HmacKey(128)
3743 .Digest(Digest::SHA_2_256)
3744 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3745 AuthorizationSet output_params;
3746 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3747 AuthorizationSetBuilder()
3748 .Digest(Digest::SHA_2_256)
3749 .Authorization(TAG_MAC_LENGTH, 161),
3750 &output_params));
3751}
3752
3753/*
Selene Huang31ab4042020-04-29 04:22:39 -07003754 * SigningOperationsTest.HmacSha256TooSmallMacLength
3755 *
3756 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3757 * specified minimum MAC length.
3758 */
3759TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3761 .Authorization(TAG_NO_AUTH_REQUIRED)
3762 .HmacKey(128)
3763 .Digest(Digest::SHA_2_256)
3764 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3765 AuthorizationSet output_params;
3766 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3767 AuthorizationSetBuilder()
3768 .Digest(Digest::SHA_2_256)
3769 .Authorization(TAG_MAC_LENGTH, 120),
3770 &output_params));
3771}
3772
3773/*
3774 * SigningOperationsTest.HmacRfc4231TestCase3
3775 *
3776 * Validates against the test vectors from RFC 4231 test case 3.
3777 */
3778TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3779 string key(20, 0xaa);
3780 string message(50, 0xdd);
3781 uint8_t sha_224_expected[] = {
3782 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3783 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3784 };
3785 uint8_t sha_256_expected[] = {
3786 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3787 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3788 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3789 };
3790 uint8_t sha_384_expected[] = {
3791 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3792 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3793 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3794 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3795 };
3796 uint8_t sha_512_expected[] = {
3797 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3798 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3799 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3800 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3801 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3802 };
3803
3804 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3805 if (SecLevel() != SecurityLevel::STRONGBOX) {
3806 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3807 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3808 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3809 }
3810}
3811
3812/*
3813 * SigningOperationsTest.HmacRfc4231TestCase5
3814 *
3815 * Validates against the test vectors from RFC 4231 test case 5.
3816 */
3817TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3818 string key(20, 0x0c);
3819 string message = "Test With Truncation";
3820
3821 uint8_t sha_224_expected[] = {
3822 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3823 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3824 };
3825 uint8_t sha_256_expected[] = {
3826 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3827 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3828 };
3829 uint8_t sha_384_expected[] = {
3830 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3831 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3832 };
3833 uint8_t sha_512_expected[] = {
3834 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3835 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3836 };
3837
3838 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3839 if (SecLevel() != SecurityLevel::STRONGBOX) {
3840 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3841 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3842 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3843 }
3844}
3845
3846INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3847
3848typedef KeyMintAidlTestBase VerificationOperationsTest;
3849
3850/*
Selene Huang31ab4042020-04-29 04:22:39 -07003851 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3852 *
3853 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3854 */
3855TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3856 string key_material = "HelloThisIsAKey";
3857
3858 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003859 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003860 EXPECT_EQ(ErrorCode::OK,
3861 ImportKey(AuthorizationSetBuilder()
3862 .Authorization(TAG_NO_AUTH_REQUIRED)
3863 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3864 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3865 .Digest(Digest::SHA_2_256)
3866 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3867 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003868 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003869 EXPECT_EQ(ErrorCode::OK,
3870 ImportKey(AuthorizationSetBuilder()
3871 .Authorization(TAG_NO_AUTH_REQUIRED)
3872 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3873 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3874 .Digest(Digest::SHA_2_256)
3875 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3876 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003877 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003878
3879 string message = "This is a message.";
3880 string signature = SignMessage(
3881 signing_key, message,
3882 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3883
3884 // Signing key should not work.
3885 AuthorizationSet out_params;
3886 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3887 Begin(KeyPurpose::VERIFY, signing_key,
3888 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3889
3890 // Verification key should work.
3891 VerifyMessage(verification_key, message, signature,
3892 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003893}
3894
Prashant Patildec9fdc2021-12-08 15:25:47 +00003895/*
3896 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3897 *
3898 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3899 */
3900TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3901 string key_material = "HelloThisIsAKey";
3902
3903 vector<uint8_t> signing_key, verification_key;
3904 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3905 EXPECT_EQ(ErrorCode::OK,
3906 ImportKey(AuthorizationSetBuilder()
3907 .Authorization(TAG_NO_AUTH_REQUIRED)
3908 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3909 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3910 .Digest(Digest::SHA_2_256)
3911 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3912 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003913 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003914 EXPECT_EQ(ErrorCode::OK,
3915 ImportKey(AuthorizationSetBuilder()
3916 .Authorization(TAG_NO_AUTH_REQUIRED)
3917 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3918 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3919 .Digest(Digest::SHA_2_256)
3920 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3921 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003922 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003923
3924 string message = "This is a message.";
3925 string signature = SignMessage(
3926 signing_key, message,
3927 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3928
3929 AuthorizationSet begin_out_params;
3930 ASSERT_EQ(ErrorCode::OK,
3931 Begin(KeyPurpose::VERIFY, verification_key,
3932 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3933
3934 string corruptMessage = "This is b message."; // Corrupted message
3935 string output;
3936 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3937
3938 ASSERT_EQ(ErrorCode::OK,
3939 Begin(KeyPurpose::VERIFY, verification_key,
3940 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3941
3942 signature[0] += 1; // Corrupt a signature
3943 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003944}
3945
Selene Huang31ab4042020-04-29 04:22:39 -07003946INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3947
3948typedef KeyMintAidlTestBase ExportKeyTest;
3949
3950/*
3951 * ExportKeyTest.RsaUnsupportedKeyFormat
3952 *
3953 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3954 */
3955// TODO(seleneh) add ExportKey to GenerateKey
3956// check result
3957
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003958class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003959 public:
3960 template <TagType tag_type, Tag tag, typename ValueT>
3961 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3962 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003963 for (auto& entry : key_characteristics_) {
3964 if (entry.securityLevel == SecLevel()) {
3965 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3966 << "Tag " << tag << " with value " << expected
3967 << " not found at security level" << entry.securityLevel;
3968 } else {
3969 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3970 << "Tag " << tag << " found at security level " << entry.securityLevel;
3971 }
Selene Huang31ab4042020-04-29 04:22:39 -07003972 }
3973 }
3974
3975 void CheckOrigin() {
3976 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003977 // Origin isn't a crypto param, but it always lives with them.
3978 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003979 }
3980};
3981
3982/*
3983 * ImportKeyTest.RsaSuccess
3984 *
3985 * Verifies that importing and using an RSA key pair works correctly.
3986 */
3987TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003988 uint32_t key_size;
3989 string key;
3990
3991 if (SecLevel() == SecurityLevel::STRONGBOX) {
3992 key_size = 2048;
3993 key = rsa_2048_key;
3994 } else {
3995 key_size = 1024;
3996 key = rsa_key;
3997 }
3998
Selene Huang31ab4042020-04-29 04:22:39 -07003999 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4000 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004001 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004002 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004003 .Padding(PaddingMode::RSA_PSS)
4004 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004005 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004006
4007 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004008 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004009 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4010 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4011 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4012 CheckOrigin();
4013
4014 string message(1024 / 8, 'a');
4015 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4016 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004017 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004018}
4019
4020/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004021 * ImportKeyTest.RsaSuccessWithoutParams
4022 *
4023 * Verifies that importing and using an RSA key pair without specifying parameters
4024 * works correctly.
4025 */
4026TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4027 uint32_t key_size;
4028 string key;
4029
4030 if (SecLevel() == SecurityLevel::STRONGBOX) {
4031 key_size = 2048;
4032 key = rsa_2048_key;
4033 } else {
4034 key_size = 1024;
4035 key = rsa_key;
4036 }
4037
4038 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4039 .Authorization(TAG_NO_AUTH_REQUIRED)
4040 .SigningKey()
4041 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4042 .Digest(Digest::SHA_2_256)
4043 .Padding(PaddingMode::RSA_PSS)
4044 .SetDefaultValidity(),
4045 KeyFormat::PKCS8, key));
4046
4047 // Key size and public exponent are determined from the imported key material.
4048 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4049 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4050
4051 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4052 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4053 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4054 CheckOrigin();
4055
4056 string message(1024 / 8, 'a');
4057 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4058 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004059 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004060}
4061
4062/*
Selene Huang31ab4042020-04-29 04:22:39 -07004063 * ImportKeyTest.RsaKeySizeMismatch
4064 *
4065 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4066 * correct way.
4067 */
4068TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4069 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4070 ImportKey(AuthorizationSetBuilder()
4071 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4072 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004073 .Padding(PaddingMode::NONE)
4074 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004075 KeyFormat::PKCS8, rsa_key));
4076}
4077
4078/*
4079 * ImportKeyTest.RsaPublicExponentMismatch
4080 *
4081 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4082 * fails in the correct way.
4083 */
4084TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4085 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4086 ImportKey(AuthorizationSetBuilder()
4087 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4088 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004089 .Padding(PaddingMode::NONE)
4090 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004091 KeyFormat::PKCS8, rsa_key));
4092}
4093
4094/*
David Drysdalee60248c2021-10-04 12:54:13 +01004095 * ImportKeyTest.RsaAttestMultiPurposeFail
4096 *
4097 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4098 */
4099TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004100 if (AidlVersion() < 2) {
4101 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4102 // with other key purposes. However, this was not checked at the time
4103 // so we can only be strict about checking this for implementations of KeyMint
4104 // version 2 and above.
4105 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4106 }
David Drysdalee60248c2021-10-04 12:54:13 +01004107 uint32_t key_size = 2048;
4108 string key = rsa_2048_key;
4109
4110 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4111 ImportKey(AuthorizationSetBuilder()
4112 .Authorization(TAG_NO_AUTH_REQUIRED)
4113 .RsaSigningKey(key_size, 65537)
4114 .AttestKey()
4115 .Digest(Digest::SHA_2_256)
4116 .Padding(PaddingMode::RSA_PSS)
4117 .SetDefaultValidity(),
4118 KeyFormat::PKCS8, key));
4119}
4120
4121/*
Selene Huang31ab4042020-04-29 04:22:39 -07004122 * ImportKeyTest.EcdsaSuccess
4123 *
4124 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4125 */
4126TEST_P(ImportKeyTest, EcdsaSuccess) {
4127 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4128 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004129 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004130 .Digest(Digest::SHA_2_256)
4131 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004132 KeyFormat::PKCS8, ec_256_key));
4133
4134 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004135 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4136 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4137
4138 CheckOrigin();
4139
4140 string message(32, 'a');
4141 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4142 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004143 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004144}
4145
4146/*
4147 * ImportKeyTest.EcdsaP256RFC5915Success
4148 *
4149 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4150 * correctly.
4151 */
4152TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4153 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4154 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004155 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004156 .Digest(Digest::SHA_2_256)
4157 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004158 KeyFormat::PKCS8, ec_256_key_rfc5915));
4159
4160 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004161 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4162 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4163
4164 CheckOrigin();
4165
4166 string message(32, 'a');
4167 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4168 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004169 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004170}
4171
4172/*
4173 * ImportKeyTest.EcdsaP256SEC1Success
4174 *
4175 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4176 */
4177TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4178 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4179 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004180 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004181 .Digest(Digest::SHA_2_256)
4182 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004183 KeyFormat::PKCS8, ec_256_key_sec1));
4184
4185 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004186 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4187 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4188
4189 CheckOrigin();
4190
4191 string message(32, 'a');
4192 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4193 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004194 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004195}
4196
4197/*
4198 * ImportKeyTest.Ecdsa521Success
4199 *
4200 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4201 */
4202TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004203 if (SecLevel() == SecurityLevel::STRONGBOX) {
4204 GTEST_SKIP() << "Test not applicable to StrongBox device";
4205 }
Selene Huang31ab4042020-04-29 04:22:39 -07004206 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4207 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004208 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004209 .Digest(Digest::SHA_2_256)
4210 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004211 KeyFormat::PKCS8, ec_521_key));
4212
4213 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004214 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4215 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4216 CheckOrigin();
4217
4218 string message(32, 'a');
4219 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4220 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004221 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004222}
4223
4224/*
Selene Huang31ab4042020-04-29 04:22:39 -07004225 * ImportKeyTest.EcdsaCurveMismatch
4226 *
4227 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4228 * the correct way.
4229 */
4230TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4231 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4232 ImportKey(AuthorizationSetBuilder()
4233 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004234 .Digest(Digest::NONE)
4235 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004236 KeyFormat::PKCS8, ec_256_key));
4237}
4238
4239/*
David Drysdalee60248c2021-10-04 12:54:13 +01004240 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4241 *
4242 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4243 */
4244TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004245 if (AidlVersion() < 2) {
4246 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4247 // with other key purposes. However, this was not checked at the time
4248 // so we can only be strict about checking this for implementations of KeyMint
4249 // version 2 and above.
4250 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4251 }
David Drysdalee60248c2021-10-04 12:54:13 +01004252 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4253 ImportKey(AuthorizationSetBuilder()
4254 .Authorization(TAG_NO_AUTH_REQUIRED)
4255 .EcdsaSigningKey(EcCurve::P_256)
4256 .AttestKey()
4257 .Digest(Digest::SHA_2_256)
4258 .SetDefaultValidity(),
4259 KeyFormat::PKCS8, ec_256_key));
4260}
4261
4262/*
David Drysdale42fe1892021-10-14 14:43:46 +01004263 * ImportKeyTest.Ed25519RawSuccess
4264 *
4265 * Verifies that importing and using a raw Ed25519 private key works correctly.
4266 */
4267TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4268 if (!Curve25519Supported()) {
4269 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4270 }
4271
4272 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4273 .Authorization(TAG_NO_AUTH_REQUIRED)
4274 .EcdsaSigningKey(EcCurve::CURVE_25519)
4275 .Digest(Digest::NONE)
4276 .SetDefaultValidity(),
4277 KeyFormat::RAW, ed25519_key));
4278 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4279 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4280 CheckOrigin();
4281
4282 // The returned cert should hold the correct public key.
4283 ASSERT_GT(cert_chain_.size(), 0);
4284 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4285 ASSERT_NE(kmKeyCert, nullptr);
4286 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4287 ASSERT_NE(kmPubKey.get(), nullptr);
4288 size_t kmPubKeySize = 32;
4289 uint8_t kmPubKeyData[32];
4290 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4291 ASSERT_EQ(kmPubKeySize, 32);
4292 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4293
4294 string message(32, 'a');
4295 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4296 string signature = SignMessage(message, params);
4297 LocalVerifyMessage(message, signature, params);
4298}
4299
4300/*
4301 * ImportKeyTest.Ed25519Pkcs8Success
4302 *
4303 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4304 */
4305TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4306 if (!Curve25519Supported()) {
4307 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4308 }
4309
4310 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4311 .Authorization(TAG_NO_AUTH_REQUIRED)
4312 .EcdsaSigningKey(EcCurve::CURVE_25519)
4313 .Digest(Digest::NONE)
4314 .SetDefaultValidity(),
4315 KeyFormat::PKCS8, ed25519_pkcs8_key));
4316 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4317 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4318 CheckOrigin();
4319
4320 // The returned cert should hold the correct public key.
4321 ASSERT_GT(cert_chain_.size(), 0);
4322 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4323 ASSERT_NE(kmKeyCert, nullptr);
4324 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4325 ASSERT_NE(kmPubKey.get(), nullptr);
4326 size_t kmPubKeySize = 32;
4327 uint8_t kmPubKeyData[32];
4328 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4329 ASSERT_EQ(kmPubKeySize, 32);
4330 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4331
4332 string message(32, 'a');
4333 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4334 string signature = SignMessage(message, params);
4335 LocalVerifyMessage(message, signature, params);
4336}
4337
4338/*
4339 * ImportKeyTest.Ed25519CurveMismatch
4340 *
4341 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4342 * the correct way.
4343 */
4344TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4345 if (!Curve25519Supported()) {
4346 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4347 }
4348
4349 ASSERT_NE(ErrorCode::OK,
4350 ImportKey(AuthorizationSetBuilder()
4351 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4352 .Digest(Digest::NONE)
4353 .SetDefaultValidity(),
4354 KeyFormat::RAW, ed25519_key));
4355}
4356
4357/*
4358 * ImportKeyTest.Ed25519FormatMismatch
4359 *
4360 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4361 */
4362TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4363 if (!Curve25519Supported()) {
4364 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4365 }
4366
4367 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4368 .EcdsaSigningKey(EcCurve::CURVE_25519)
4369 .Digest(Digest::NONE)
4370 .SetDefaultValidity(),
4371 KeyFormat::PKCS8, ed25519_key));
4372 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4373 .EcdsaSigningKey(EcCurve::CURVE_25519)
4374 .Digest(Digest::NONE)
4375 .SetDefaultValidity(),
4376 KeyFormat::RAW, ed25519_pkcs8_key));
4377}
4378
4379/*
4380 * ImportKeyTest.Ed25519PurposeMismatch
4381 *
4382 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4383 */
4384TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4385 if (!Curve25519Supported()) {
4386 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4387 }
4388
4389 // Can't have both SIGN and ATTEST_KEY
4390 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4391 .EcdsaSigningKey(EcCurve::CURVE_25519)
4392 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4393 .Digest(Digest::NONE)
4394 .SetDefaultValidity(),
4395 KeyFormat::RAW, ed25519_key));
4396 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4397 // PKCS#8 format and so includes an OID).
4398 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4399 .EcdsaKey(EcCurve::CURVE_25519)
4400 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4401 .Digest(Digest::NONE)
4402 .SetDefaultValidity(),
4403 KeyFormat::PKCS8, ed25519_pkcs8_key));
4404}
4405
4406/*
4407 * ImportKeyTest.X25519RawSuccess
4408 *
4409 * Verifies that importing and using a raw X25519 private key works correctly.
4410 */
4411TEST_P(ImportKeyTest, X25519RawSuccess) {
4412 if (!Curve25519Supported()) {
4413 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4414 }
4415
4416 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4417 .Authorization(TAG_NO_AUTH_REQUIRED)
4418 .EcdsaKey(EcCurve::CURVE_25519)
4419 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4420 .SetDefaultValidity(),
4421 KeyFormat::RAW, x25519_key));
4422
4423 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4424 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4425 CheckOrigin();
4426}
4427
4428/*
4429 * ImportKeyTest.X25519Pkcs8Success
4430 *
4431 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4432 */
4433TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4434 if (!Curve25519Supported()) {
4435 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4436 }
4437
4438 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4439 .Authorization(TAG_NO_AUTH_REQUIRED)
4440 .EcdsaKey(EcCurve::CURVE_25519)
4441 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4442 .SetDefaultValidity(),
4443 KeyFormat::PKCS8, x25519_pkcs8_key));
4444
4445 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4446 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4447 CheckOrigin();
4448}
4449
4450/*
4451 * ImportKeyTest.X25519CurveMismatch
4452 *
4453 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4454 * the correct way.
4455 */
4456TEST_P(ImportKeyTest, X25519CurveMismatch) {
4457 if (!Curve25519Supported()) {
4458 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4459 }
4460
4461 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4462 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4463 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4464 .SetDefaultValidity(),
4465 KeyFormat::RAW, x25519_key));
4466}
4467
4468/*
4469 * ImportKeyTest.X25519FormatMismatch
4470 *
4471 * Verifies that importing an X25519 key with an invalid format fails.
4472 */
4473TEST_P(ImportKeyTest, X25519FormatMismatch) {
4474 if (!Curve25519Supported()) {
4475 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4476 }
4477
4478 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4479 .EcdsaKey(EcCurve::CURVE_25519)
4480 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4481 .SetDefaultValidity(),
4482 KeyFormat::PKCS8, x25519_key));
4483 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4484 .EcdsaKey(EcCurve::CURVE_25519)
4485 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4486 .SetDefaultValidity(),
4487 KeyFormat::RAW, x25519_pkcs8_key));
4488}
4489
4490/*
4491 * ImportKeyTest.X25519PurposeMismatch
4492 *
4493 * Verifies that importing an X25519 key pair with an invalid format fails.
4494 */
4495TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4496 if (!Curve25519Supported()) {
4497 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4498 }
4499
4500 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4501 .EcdsaKey(EcCurve::CURVE_25519)
4502 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4503 .SetDefaultValidity(),
4504 KeyFormat::PKCS8, x25519_pkcs8_key));
4505 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4506 .EcdsaSigningKey(EcCurve::CURVE_25519)
4507 .SetDefaultValidity(),
4508 KeyFormat::PKCS8, x25519_pkcs8_key));
4509}
4510
4511/*
Selene Huang31ab4042020-04-29 04:22:39 -07004512 * ImportKeyTest.AesSuccess
4513 *
4514 * Verifies that importing and using an AES key works.
4515 */
4516TEST_P(ImportKeyTest, AesSuccess) {
4517 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4518 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4519 .Authorization(TAG_NO_AUTH_REQUIRED)
4520 .AesEncryptionKey(key.size() * 8)
4521 .EcbMode()
4522 .Padding(PaddingMode::PKCS7),
4523 KeyFormat::RAW, key));
4524
4525 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4526 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4527 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4528 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4529 CheckOrigin();
4530
4531 string message = "Hello World!";
4532 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4533 string ciphertext = EncryptMessage(message, params);
4534 string plaintext = DecryptMessage(ciphertext, params);
4535 EXPECT_EQ(message, plaintext);
4536}
4537
4538/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004539 * ImportKeyTest.AesFailure
4540 *
4541 * Verifies that importing an invalid AES key fails.
4542 */
4543TEST_P(ImportKeyTest, AesFailure) {
4544 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4545 uint32_t bitlen = key.size() * 8;
4546 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004547 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004548 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004549 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004550 .Authorization(TAG_NO_AUTH_REQUIRED)
4551 .AesEncryptionKey(key_size)
4552 .EcbMode()
4553 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004554 KeyFormat::RAW, key);
4555 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004556 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4557 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004558 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004559
4560 // Explicit key size matches that of the provided key, but it's not a valid size.
4561 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4562 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4563 ImportKey(AuthorizationSetBuilder()
4564 .Authorization(TAG_NO_AUTH_REQUIRED)
4565 .AesEncryptionKey(long_key.size() * 8)
4566 .EcbMode()
4567 .Padding(PaddingMode::PKCS7),
4568 KeyFormat::RAW, long_key));
4569 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4570 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4571 ImportKey(AuthorizationSetBuilder()
4572 .Authorization(TAG_NO_AUTH_REQUIRED)
4573 .AesEncryptionKey(short_key.size() * 8)
4574 .EcbMode()
4575 .Padding(PaddingMode::PKCS7),
4576 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004577}
4578
4579/*
4580 * ImportKeyTest.TripleDesSuccess
4581 *
4582 * Verifies that importing and using a 3DES key works.
4583 */
4584TEST_P(ImportKeyTest, TripleDesSuccess) {
4585 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4586 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4587 .Authorization(TAG_NO_AUTH_REQUIRED)
4588 .TripleDesEncryptionKey(168)
4589 .EcbMode()
4590 .Padding(PaddingMode::PKCS7),
4591 KeyFormat::RAW, key));
4592
4593 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4594 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4595 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4596 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4597 CheckOrigin();
4598
4599 string message = "Hello World!";
4600 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4601 string ciphertext = EncryptMessage(message, params);
4602 string plaintext = DecryptMessage(ciphertext, params);
4603 EXPECT_EQ(message, plaintext);
4604}
4605
4606/*
4607 * ImportKeyTest.TripleDesFailure
4608 *
4609 * Verifies that importing an invalid 3DES key fails.
4610 */
4611TEST_P(ImportKeyTest, TripleDesFailure) {
4612 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004613 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004614 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004615 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004616 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004617 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004618 .Authorization(TAG_NO_AUTH_REQUIRED)
4619 .TripleDesEncryptionKey(key_size)
4620 .EcbMode()
4621 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004622 KeyFormat::RAW, key);
4623 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004624 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4625 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004626 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004627 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004628 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004629 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4630 ImportKey(AuthorizationSetBuilder()
4631 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004632 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004633 .EcbMode()
4634 .Padding(PaddingMode::PKCS7),
4635 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004636 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004637 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4638 ImportKey(AuthorizationSetBuilder()
4639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004640 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004641 .EcbMode()
4642 .Padding(PaddingMode::PKCS7),
4643 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004644}
4645
4646/*
4647 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004648 *
4649 * Verifies that importing and using an HMAC key works.
4650 */
4651TEST_P(ImportKeyTest, HmacKeySuccess) {
4652 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4653 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4654 .Authorization(TAG_NO_AUTH_REQUIRED)
4655 .HmacKey(key.size() * 8)
4656 .Digest(Digest::SHA_2_256)
4657 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4658 KeyFormat::RAW, key));
4659
4660 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4661 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4662 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4663 CheckOrigin();
4664
4665 string message = "Hello World!";
4666 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4667 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4668}
4669
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004670/*
4671 * ImportKeyTest.GetKeyCharacteristics
4672 *
4673 * Verifies that imported keys have the correct characteristics.
4674 */
4675TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4676 vector<uint8_t> key_blob;
4677 vector<KeyCharacteristics> key_characteristics;
4678 auto base_builder = AuthorizationSetBuilder()
4679 .Padding(PaddingMode::NONE)
4680 .Authorization(TAG_NO_AUTH_REQUIRED)
4681 .SetDefaultValidity();
4682 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4683 Algorithm::TRIPLE_DES};
4684 ErrorCode result;
4685 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4686 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4687 for (auto alg : algorithms) {
4688 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4689 AuthorizationSetBuilder builder(base_builder);
4690 switch (alg) {
4691 case Algorithm::RSA:
4692 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4693
4694 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4695 &key_characteristics);
4696 break;
4697 case Algorithm::EC:
4698 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4699 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4700 &key_characteristics);
4701 break;
4702 case Algorithm::HMAC:
4703 builder.HmacKey(128)
4704 .Digest(Digest::SHA_2_256)
4705 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4706 result =
4707 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4708 break;
4709 case Algorithm::AES:
4710 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4711 result =
4712 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4713 break;
4714 case Algorithm::TRIPLE_DES:
4715 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4716 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4717 &key_characteristics);
4718 break;
4719 default:
4720 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4721 continue;
4722 }
4723 ASSERT_EQ(ErrorCode::OK, result);
4724 CheckCharacteristics(key_blob, key_characteristics);
4725 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4726 }
4727}
4728
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004729/*
4730 * ImportKeyTest.RsaOaepMGFDigestSuccess
4731 *
4732 * Include MGF-Digest explicitly in import key authorization list.
4733 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4734 * should have the correct characteristics.
4735 */
4736TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
4737 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4738 size_t key_size = 2048;
4739
4740 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4741 .OaepMGFDigest(mgf_digests)
4742 .Authorization(TAG_NO_AUTH_REQUIRED)
4743 .RsaEncryptionKey(key_size, 65537)
4744 .Digest(Digest::SHA_2_256)
4745 .Padding(PaddingMode::RSA_OAEP)
4746 .SetDefaultValidity(),
4747 KeyFormat::PKCS8, rsa_2048_key));
4748
4749 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4750 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4751 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4752 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4753 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4754 CheckOrigin();
4755
4756 // Make sure explicitly specified mgf-digests exist in key characteristics.
4757 assert_mgf_digests_present_in_key_characteristics(key_characteristics_, mgf_digests);
4758
4759 string message = "Hello";
4760
4761 for (auto digest : mgf_digests) {
4762 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4763 auto params = AuthorizationSetBuilder()
4764 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4765 .Digest(Digest::SHA_2_256)
4766 .Padding(PaddingMode::RSA_OAEP);
4767 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4768 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4769 EXPECT_EQ(key_size / 8, ciphertext1.size());
4770
4771 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4772 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4773 EXPECT_EQ(key_size / 8, ciphertext2.size());
4774
4775 // OAEP randomizes padding so every result should be different (with astronomically high
4776 // probability).
4777 EXPECT_NE(ciphertext1, ciphertext2);
4778
4779 string plaintext1 = DecryptMessage(ciphertext1, params);
4780 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4781 string plaintext2 = DecryptMessage(ciphertext2, params);
4782 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4783
4784 // Decrypting corrupted ciphertext should fail.
4785 size_t offset_to_corrupt = ciphertext1.size() - 1;
4786 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4787 ciphertext1[offset_to_corrupt] = corrupt_byte;
4788
4789 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4790 string result;
4791 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4792 EXPECT_EQ(0U, result.size());
4793 }
4794}
4795
4796/*
4797 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4798 *
4799 * Don't specify MGF-Digest explicitly in import key authorization list.
4800 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4801 * verify that imported key should have the correct characteristics. Default
4802 * mgf-digest shouldn't be included in key charecteristics.
4803 */
4804TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4805 size_t key_size = 2048;
4806 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4807 .Authorization(TAG_NO_AUTH_REQUIRED)
4808 .RsaEncryptionKey(key_size, 65537)
4809 .Digest(Digest::SHA_2_256)
4810 .Padding(PaddingMode::RSA_OAEP)
4811 .SetDefaultValidity(),
4812 KeyFormat::PKCS8, rsa_2048_key));
4813
4814 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4815 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4816 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4817 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4818 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4819 CheckOrigin();
4820
4821 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
4822 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
4823}
4824
Selene Huang31ab4042020-04-29 04:22:39 -07004825INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4826
4827auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004828 // IKeyMintDevice.aidl
4829 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4830 "020100" // INTEGER length 1 value 0x00 (version)
4831 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4832 "934bf94e2aa28a3f83c9f79297250262"
4833 "fbe3276b5a1c91159bbfa3ef8957aac8"
4834 "4b59b30b455a79c2973480823d8b3863"
4835 "c3deef4a8e243590268d80e18751a0e1"
4836 "30f67ce6a1ace9f79b95e097474febc9"
4837 "81195b1d13a69086c0863f66a7b7fdb4"
4838 "8792227b1ac5e2489febdf087ab54864"
4839 "83033a6f001ca5d1ec1e27f5c30f4cec"
4840 "2642074a39ae68aee552e196627a8e3d"
4841 "867e67a8c01b11e75f13cca0a97ab668"
4842 "b50cda07a8ecb7cd8e3dd7009c963653"
4843 "4f6f239cffe1fc8daa466f78b676c711"
4844 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4845 "99b801597d5220e307eaa5bee507fb94"
4846 "d1fa69f9e519b2de315bac92c36f2ea1"
4847 "fa1df4478c0ddedeae8c70e0233cd098"
4848 "040c" // OCTET STRING length 0x0c (initializationVector)
4849 "d796b02c370f1fa4cc0124f1"
4850 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4851 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4852 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4853 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4854 "3106" // SET length 0x06
4855 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4856 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4857 // } end SET
4858 // } end [1]
4859 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4860 "020120" // INTEGER length 1 value 0x20 (AES)
4861 // } end [2]
4862 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4863 "02020100" // INTEGER length 2 value 0x100
4864 // } end [3]
4865 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4866 "3103" // SET length 0x03 {
4867 "020101" // INTEGER length 1 value 0x01 (ECB)
4868 // } end SET
4869 // } end [4]
4870 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4871 "3103" // SET length 0x03 {
4872 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4873 // } end SET
4874 // } end [5]
4875 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4876 // (noAuthRequired)
4877 "0500" // NULL
4878 // } end [503]
4879 // } end SEQUENCE (AuthorizationList)
4880 // } end SEQUENCE (KeyDescription)
4881 "0420" // OCTET STRING length 0x20 (encryptedKey)
4882 "ccd540855f833a5e1480bfd2d36faf3a"
4883 "eee15df5beabe2691bc82dde2a7aa910"
4884 "0410" // OCTET STRING length 0x10 (tag)
4885 "64c9f689c60ff6223ab6e6999e0eb6e5"
4886 // } SEQUENCE (SecureKeyWrapper)
4887);
Selene Huang31ab4042020-04-29 04:22:39 -07004888
4889auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004890 // IKeyMintDevice.aidl
4891 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4892 "020100" // INTEGER length 1 value 0x00 (version)
4893 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4894 "aad93ed5924f283b4bb5526fbe7a1412"
4895 "f9d9749ec30db9062b29e574a8546f33"
4896 "c88732452f5b8e6a391ee76c39ed1712"
4897 "c61d8df6213dec1cffbc17a8c6d04c7b"
4898 "30893d8daa9b2015213e219468215532"
4899 "07f8f9931c4caba23ed3bee28b36947e"
4900 "47f10e0a5c3dc51c988a628daad3e5e1"
4901 "f4005e79c2d5a96c284b4b8d7e4948f3"
4902 "31e5b85dd5a236f85579f3ea1d1b8484"
4903 "87470bdb0ab4f81a12bee42c99fe0df4"
4904 "bee3759453e69ad1d68a809ce06b949f"
4905 "7694a990429b2fe81e066ff43e56a216"
4906 "02db70757922a4bcc23ab89f1e35da77"
4907 "586775f423e519c2ea394caf48a28d0c"
4908 "8020f1dcf6b3a68ec246f615ae96dae9"
4909 "a079b1f6eb959033c1af5c125fd94168"
4910 "040c" // OCTET STRING length 0x0c (initializationVector)
4911 "6d9721d08589581ab49204a3"
4912 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4913 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4914 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4915 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4916 "3106" // SET length 0x06
4917 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4918 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4919 // } end SET
4920 // } end [1]
4921 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4922 "020120" // INTEGER length 1 value 0x20 (AES)
4923 // } end [2]
4924 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4925 "02020100" // INTEGER length 2 value 0x100
4926 // } end [3]
4927 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4928 "3103" // SET length 0x03 {
4929 "020101" // INTEGER length 1 value 0x01 (ECB)
4930 // } end SET
4931 // } end [4]
4932 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4933 "3103" // SET length 0x03 {
4934 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4935 // } end SET
4936 // } end [5]
4937 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4938 // (noAuthRequired)
4939 "0500" // NULL
4940 // } end [503]
4941 // } end SEQUENCE (AuthorizationList)
4942 // } end SEQUENCE (KeyDescription)
4943 "0420" // OCTET STRING length 0x20 (encryptedKey)
4944 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4945 "c20d1f99a9a024a76f35c8e2cab9b68d"
4946 "0410" // OCTET STRING length 0x10 (tag)
4947 "2560c70109ae67c030f00b98b512a670"
4948 // } SEQUENCE (SecureKeyWrapper)
4949);
Selene Huang31ab4042020-04-29 04:22:39 -07004950
4951auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004952 // RFC 5208 s5
4953 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4954 "020100" // INTEGER length 1 value 0x00 (version)
4955 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4956 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4957 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4958 "0500" // NULL (parameters)
4959 // } SEQUENCE (AlgorithmIdentifier)
4960 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4961 // RFC 8017 A.1.2
4962 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4963 "020100" // INTEGER length 1 value 0x00 (version)
4964 "02820101" // INTEGER length 0x0101 (modulus) value...
4965 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4966 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4967 "7b06e673a837313d56b1c725150a3fef" // 0x30
4968 "86acbddc41bb759c2854eae32d35841e" // 0x40
4969 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4970 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4971 "312d7bd5921ffaea1347c157406fef71" // 0x70
4972 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4973 "f4645c11f5c1374c3886427411c44979" // 0x90
4974 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4975 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4976 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4977 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4978 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4979 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4980 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4981 "55" // 0x101
4982 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4983 "02820100" // INTEGER length 0x100 (privateExponent) value...
4984 "431447b6251908112b1ee76f99f3711a" // 0x10
4985 "52b6630960046c2de70de188d833f8b8" // 0x20
4986 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4987 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4988 "e710b630a03adc683b5d2c43080e52be" // 0x50
4989 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4990 "822bccff087d63c940ba8a45f670feb2" // 0x70
4991 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4992 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4993 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4994 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4995 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4996 "52659d5a5ba05b663737a8696281865b" // 0xd0
4997 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4998 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4999 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5000 "028181" // INTEGER length 0x81 (prime1) value...
5001 "00de392e18d682c829266cc3454e1d61" // 0x10
5002 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5003 "ff841be5bac82a164c5970007047b8c5" // 0x30
5004 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5005 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5006 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5007 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5008 "9e91346130748a6e3c124f9149d71c74" // 0x80
5009 "35"
5010 "028181" // INTEGER length 0x81 (prime2) value...
5011 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5012 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5013 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5014 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5015 "9ed39a2d934c880440aed8832f984316" // 0x50
5016 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5017 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5018 "b880677c068e1be936e81288815252a8" // 0x80
5019 "a1"
5020 "028180" // INTEGER length 0x80 (exponent1) value...
5021 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5022 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5023 "5a063212a4f105a3764743e53281988a" // 0x30
5024 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5025 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5026 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5027 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5028 "4719d6e2b9439823719cd08bcd031781" // 0x80
5029 "028181" // INTEGER length 0x81 (exponent2) value...
5030 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5031 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5032 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5033 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5034 "1254186af30b22c10582a8a43e34fe94" // 0x50
5035 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5036 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5037 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5038 "61"
5039 "028181" // INTEGER length 0x81 (coefficient) value...
5040 "00c931617c77829dfb1270502be9195c" // 0x10
5041 "8f2830885f57dba869536811e6864236" // 0x20
5042 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5043 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5044 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5045 "959356210723287b0affcc9f727044d4" // 0x60
5046 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5047 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5048 "22"
5049 // } SEQUENCE
5050 // } SEQUENCE ()
5051);
Selene Huang31ab4042020-04-29 04:22:39 -07005052
5053string zero_masking_key =
5054 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5055string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5056
5057class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5058
5059TEST_P(ImportWrappedKeyTest, Success) {
5060 auto wrapping_key_desc = AuthorizationSetBuilder()
5061 .RsaEncryptionKey(2048, 65537)
5062 .Digest(Digest::SHA_2_256)
5063 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005064 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5065 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005066
5067 ASSERT_EQ(ErrorCode::OK,
5068 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5069 AuthorizationSetBuilder()
5070 .Digest(Digest::SHA_2_256)
5071 .Padding(PaddingMode::RSA_OAEP)));
5072
5073 string message = "Hello World!";
5074 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5075 string ciphertext = EncryptMessage(message, params);
5076 string plaintext = DecryptMessage(ciphertext, params);
5077 EXPECT_EQ(message, plaintext);
5078}
5079
David Drysdaled2cc8c22021-04-15 13:29:45 +01005080/*
5081 * ImportWrappedKeyTest.SuccessSidsIgnored
5082 *
5083 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5084 * include Tag:USER_SECURE_ID.
5085 */
5086TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5087 auto wrapping_key_desc = AuthorizationSetBuilder()
5088 .RsaEncryptionKey(2048, 65537)
5089 .Digest(Digest::SHA_2_256)
5090 .Padding(PaddingMode::RSA_OAEP)
5091 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5092 .SetDefaultValidity();
5093
5094 int64_t password_sid = 42;
5095 int64_t biometric_sid = 24;
5096 ASSERT_EQ(ErrorCode::OK,
5097 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5098 AuthorizationSetBuilder()
5099 .Digest(Digest::SHA_2_256)
5100 .Padding(PaddingMode::RSA_OAEP),
5101 password_sid, biometric_sid));
5102
5103 string message = "Hello World!";
5104 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5105 string ciphertext = EncryptMessage(message, params);
5106 string plaintext = DecryptMessage(ciphertext, params);
5107 EXPECT_EQ(message, plaintext);
5108}
5109
Selene Huang31ab4042020-04-29 04:22:39 -07005110TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5111 auto wrapping_key_desc = AuthorizationSetBuilder()
5112 .RsaEncryptionKey(2048, 65537)
5113 .Digest(Digest::SHA_2_256)
5114 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005115 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5116 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005117
5118 ASSERT_EQ(ErrorCode::OK,
5119 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5120 AuthorizationSetBuilder()
5121 .Digest(Digest::SHA_2_256)
5122 .Padding(PaddingMode::RSA_OAEP)));
5123}
5124
5125TEST_P(ImportWrappedKeyTest, WrongMask) {
5126 auto wrapping_key_desc = AuthorizationSetBuilder()
5127 .RsaEncryptionKey(2048, 65537)
5128 .Digest(Digest::SHA_2_256)
5129 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005130 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5131 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005132
5133 ASSERT_EQ(
5134 ErrorCode::VERIFICATION_FAILED,
5135 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5136 AuthorizationSetBuilder()
5137 .Digest(Digest::SHA_2_256)
5138 .Padding(PaddingMode::RSA_OAEP)));
5139}
5140
5141TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5142 auto wrapping_key_desc = AuthorizationSetBuilder()
5143 .RsaEncryptionKey(2048, 65537)
5144 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005145 .Padding(PaddingMode::RSA_OAEP)
5146 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005147
5148 ASSERT_EQ(
5149 ErrorCode::INCOMPATIBLE_PURPOSE,
5150 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5151 AuthorizationSetBuilder()
5152 .Digest(Digest::SHA_2_256)
5153 .Padding(PaddingMode::RSA_OAEP)));
5154}
5155
David Drysdaled2cc8c22021-04-15 13:29:45 +01005156TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5157 auto wrapping_key_desc = AuthorizationSetBuilder()
5158 .RsaEncryptionKey(2048, 65537)
5159 .Digest(Digest::SHA_2_256)
5160 .Padding(PaddingMode::RSA_PSS)
5161 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5162 .SetDefaultValidity();
5163
5164 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5165 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5166 AuthorizationSetBuilder()
5167 .Digest(Digest::SHA_2_256)
5168 .Padding(PaddingMode::RSA_OAEP)));
5169}
5170
5171TEST_P(ImportWrappedKeyTest, WrongDigest) {
5172 auto wrapping_key_desc = AuthorizationSetBuilder()
5173 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005174 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005175 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005176 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5177 .SetDefaultValidity();
5178
5179 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5180 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5181 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005182 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005183 .Padding(PaddingMode::RSA_OAEP)));
5184}
5185
Selene Huang31ab4042020-04-29 04:22:39 -07005186INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5187
5188typedef KeyMintAidlTestBase EncryptionOperationsTest;
5189
5190/*
5191 * EncryptionOperationsTest.RsaNoPaddingSuccess
5192 *
David Drysdale59cae642021-05-12 13:52:03 +01005193 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005194 */
5195TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005196 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005197 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005198 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5199 .Authorization(TAG_NO_AUTH_REQUIRED)
5200 .RsaEncryptionKey(2048, exponent)
5201 .Padding(PaddingMode::NONE)
5202 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005203
David Drysdaled2cc8c22021-04-15 13:29:45 +01005204 string message = string(2048 / 8, 'a');
5205 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005206 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005207 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005208
David Drysdale59cae642021-05-12 13:52:03 +01005209 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005210 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005211
David Drysdaled2cc8c22021-04-15 13:29:45 +01005212 // Unpadded RSA is deterministic
5213 EXPECT_EQ(ciphertext1, ciphertext2);
5214
5215 CheckedDeleteKey();
5216 }
Selene Huang31ab4042020-04-29 04:22:39 -07005217}
5218
5219/*
5220 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5221 *
David Drysdale59cae642021-05-12 13:52:03 +01005222 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005223 */
5224TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5226 .Authorization(TAG_NO_AUTH_REQUIRED)
5227 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005228 .Padding(PaddingMode::NONE)
5229 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005230
5231 string message = "1";
5232 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5233
David Drysdale59cae642021-05-12 13:52:03 +01005234 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005235 EXPECT_EQ(2048U / 8, ciphertext.size());
5236
5237 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5238 string plaintext = DecryptMessage(ciphertext, params);
5239
5240 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005241}
5242
5243/*
Selene Huang31ab4042020-04-29 04:22:39 -07005244 * EncryptionOperationsTest.RsaOaepSuccess
5245 *
David Drysdale59cae642021-05-12 13:52:03 +01005246 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005247 */
5248TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5249 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005250 auto mgf_digest = Digest::SHA1;
Selene Huang31ab4042020-04-29 04:22:39 -07005251
5252 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005253 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5254 .Authorization(TAG_NO_AUTH_REQUIRED)
5255 .RsaEncryptionKey(key_size, 65537)
5256 .Padding(PaddingMode::RSA_OAEP)
5257 .Digest(digests)
5258 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5259 .SetDefaultValidity()));
5260
5261 // Make sure explicitly specified mgf-digest exist in key characteristics.
5262 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
Selene Huang31ab4042020-04-29 04:22:39 -07005263
5264 string message = "Hello";
5265
5266 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005267 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5268
5269 auto params = AuthorizationSetBuilder()
5270 .Digest(digest)
5271 .Padding(PaddingMode::RSA_OAEP)
5272 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5273 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005274 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5275 EXPECT_EQ(key_size / 8, ciphertext1.size());
5276
David Drysdale59cae642021-05-12 13:52:03 +01005277 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005278 EXPECT_EQ(key_size / 8, ciphertext2.size());
5279
5280 // OAEP randomizes padding so every result should be different (with astronomically high
5281 // probability).
5282 EXPECT_NE(ciphertext1, ciphertext2);
5283
5284 string plaintext1 = DecryptMessage(ciphertext1, params);
5285 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5286 string plaintext2 = DecryptMessage(ciphertext2, params);
5287 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5288
5289 // Decrypting corrupted ciphertext should fail.
5290 size_t offset_to_corrupt = random() % ciphertext1.size();
5291 char corrupt_byte;
5292 do {
5293 corrupt_byte = static_cast<char>(random() % 256);
5294 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5295 ciphertext1[offset_to_corrupt] = corrupt_byte;
5296
5297 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5298 string result;
5299 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5300 EXPECT_EQ(0U, result.size());
5301 }
5302}
5303
5304/*
5305 * EncryptionOperationsTest.RsaOaepInvalidDigest
5306 *
David Drysdale59cae642021-05-12 13:52:03 +01005307 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005308 * without a digest.
5309 */
5310TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5311 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5312 .Authorization(TAG_NO_AUTH_REQUIRED)
5313 .RsaEncryptionKey(2048, 65537)
5314 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005315 .Digest(Digest::NONE)
5316 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005317
5318 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005319 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005320}
5321
5322/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005323 * EncryptionOperationsTest.RsaOaepInvalidPadding
5324 *
David Drysdale59cae642021-05-12 13:52:03 +01005325 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005326 * with a padding value that is only suitable for signing/verifying.
5327 */
5328TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5329 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5330 .Authorization(TAG_NO_AUTH_REQUIRED)
5331 .RsaEncryptionKey(2048, 65537)
5332 .Padding(PaddingMode::RSA_PSS)
5333 .Digest(Digest::NONE)
5334 .SetDefaultValidity()));
5335
5336 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005337 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005338}
5339
5340/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005341 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005342 *
David Drysdale59cae642021-05-12 13:52:03 +01005343 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005344 * with a different digest than was used to encrypt.
5345 */
5346TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005347 if (SecLevel() == SecurityLevel::STRONGBOX) {
5348 GTEST_SKIP() << "Test not applicable to StrongBox device";
5349 }
Selene Huang31ab4042020-04-29 04:22:39 -07005350
5351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5352 .Authorization(TAG_NO_AUTH_REQUIRED)
5353 .RsaEncryptionKey(1024, 65537)
5354 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005355 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5356 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005357 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005358 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005359 message,
5360 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5361
5362 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5363 .Digest(Digest::SHA_2_256)
5364 .Padding(PaddingMode::RSA_OAEP)));
5365 string result;
5366 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5367 EXPECT_EQ(0U, result.size());
5368}
5369
5370/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005371 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5372 *
David Drysdale59cae642021-05-12 13:52:03 +01005373 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005374 * digests.
5375 */
5376TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5377 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5378
5379 size_t key_size = 2048; // Need largish key for SHA-512 test.
5380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5381 .OaepMGFDigest(digests)
5382 .Authorization(TAG_NO_AUTH_REQUIRED)
5383 .RsaEncryptionKey(key_size, 65537)
5384 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005385 .Digest(Digest::SHA_2_256)
5386 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005387
Shawn Willden20732262023-04-21 16:36:00 -06005388 std::vector<Digest> mgf1DigestsInAuths;
5389 mgf1DigestsInAuths.reserve(digests.size());
5390 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5391 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5392 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5393 KeyParameterValue value = param.value;
5394 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5395 }
5396 });
5397
5398 std::sort(digests.begin(), digests.end());
5399 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5400 EXPECT_EQ(digests, mgf1DigestsInAuths);
5401
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005402 string message = "Hello";
5403
5404 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005405 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005406 auto params = AuthorizationSetBuilder()
5407 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5408 .Digest(Digest::SHA_2_256)
5409 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005410 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005411 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5412 EXPECT_EQ(key_size / 8, ciphertext1.size());
5413
David Drysdale59cae642021-05-12 13:52:03 +01005414 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005415 EXPECT_EQ(key_size / 8, ciphertext2.size());
5416
5417 // OAEP randomizes padding so every result should be different (with astronomically high
5418 // probability).
5419 EXPECT_NE(ciphertext1, ciphertext2);
5420
5421 string plaintext1 = DecryptMessage(ciphertext1, params);
5422 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5423 string plaintext2 = DecryptMessage(ciphertext2, params);
5424 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5425
5426 // Decrypting corrupted ciphertext should fail.
5427 size_t offset_to_corrupt = random() % ciphertext1.size();
5428 char corrupt_byte;
5429 do {
5430 corrupt_byte = static_cast<char>(random() % 256);
5431 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5432 ciphertext1[offset_to_corrupt] = corrupt_byte;
5433
5434 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5435 string result;
5436 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5437 EXPECT_EQ(0U, result.size());
5438 }
5439}
5440
5441/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005442 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5443 *
5444 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5445 * specified, defaulting to SHA-1.
5446 */
5447TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5448 size_t key_size = 2048;
5449 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5450 .Authorization(TAG_NO_AUTH_REQUIRED)
5451 .RsaEncryptionKey(key_size, 65537)
5452 .Padding(PaddingMode::RSA_OAEP)
5453 .Digest(Digest::SHA_2_256)
5454 .SetDefaultValidity()));
5455
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005456 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
5457 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
5458
David Drysdaleae3727b2021-11-11 09:00:14 +00005459 // Do local RSA encryption using the default MGF digest of SHA-1.
5460 string message = "Hello";
5461 auto params =
5462 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5463 string ciphertext = LocalRsaEncryptMessage(message, params);
5464 EXPECT_EQ(key_size / 8, ciphertext.size());
5465
5466 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5467 string plaintext = DecryptMessage(ciphertext, params);
5468 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5469
5470 // Decrypting corrupted ciphertext should fail.
5471 size_t offset_to_corrupt = random() % ciphertext.size();
5472 char corrupt_byte;
5473 do {
5474 corrupt_byte = static_cast<char>(random() % 256);
5475 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5476 ciphertext[offset_to_corrupt] = corrupt_byte;
5477
5478 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5479 string result;
5480 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5481 EXPECT_EQ(0U, result.size());
5482}
5483
5484/*
5485 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5486 *
5487 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5488 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5489 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5490 */
5491TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5492 size_t key_size = 2048;
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005493 auto mgf_digest = Digest::SHA_2_256;
5494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5495 .Authorization(TAG_NO_AUTH_REQUIRED)
5496 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5497 .RsaEncryptionKey(key_size, 65537)
5498 .Padding(PaddingMode::RSA_OAEP)
5499 .Digest(Digest::SHA_2_256)
5500 .SetDefaultValidity()));
5501
5502 // Make sure explicitly specified mgf-digest exist in key characteristics.
5503 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5504 // Make sure default mgf-digest is not included in key characteristics.
5505 ASSERT_FALSE(is_mgf_digest_present(key_characteristics_, Digest::SHA1));
David Drysdaleae3727b2021-11-11 09:00:14 +00005506
5507 // Do local RSA encryption using the default MGF digest of SHA-1.
5508 string message = "Hello";
5509 auto params =
5510 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5511 string ciphertext = LocalRsaEncryptMessage(message, params);
5512 EXPECT_EQ(key_size / 8, ciphertext.size());
5513
5514 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5515 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5516 // is checked against those values, and found absent.
5517 auto result = Begin(KeyPurpose::DECRYPT, params);
5518 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5519 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5520}
5521
5522/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005523 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5524 *
David Drysdale59cae642021-05-12 13:52:03 +01005525 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005526 * with incompatible MGF digest.
5527 */
5528TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005529 auto mgf_digest = Digest::SHA_2_256;
5530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5531 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5532 .Authorization(TAG_NO_AUTH_REQUIRED)
5533 .RsaEncryptionKey(2048, 65537)
5534 .Padding(PaddingMode::RSA_OAEP)
5535 .Digest(Digest::SHA_2_256)
5536 .SetDefaultValidity()));
5537 // Make sure explicitly specified mgf-digest exist in key characteristics.
5538 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5539
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005540 string message = "Hello World!";
5541
5542 auto params = AuthorizationSetBuilder()
5543 .Padding(PaddingMode::RSA_OAEP)
5544 .Digest(Digest::SHA_2_256)
5545 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005546 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005547}
5548
5549/*
5550 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5551 *
5552 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5553 * with unsupported MGF digest.
5554 */
5555TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005556 auto mgf_digest = Digest::SHA_2_256;
5557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5558 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, mgf_digest)
5559 .Authorization(TAG_NO_AUTH_REQUIRED)
5560 .RsaEncryptionKey(2048, 65537)
5561 .Padding(PaddingMode::RSA_OAEP)
5562 .Digest(Digest::SHA_2_256)
5563 .SetDefaultValidity()));
5564 // Make sure explicitly specified mgf-digest exist in key characteristics.
5565 ASSERT_TRUE(is_mgf_digest_present(key_characteristics_, mgf_digest));
5566
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005567 string message = "Hello World!";
5568
5569 auto params = AuthorizationSetBuilder()
5570 .Padding(PaddingMode::RSA_OAEP)
5571 .Digest(Digest::SHA_2_256)
5572 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005573 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005574}
5575
5576/*
Selene Huang31ab4042020-04-29 04:22:39 -07005577 * EncryptionOperationsTest.RsaPkcs1Success
5578 *
5579 * Verifies that RSA PKCS encryption/decrypts works.
5580 */
5581TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5583 .Authorization(TAG_NO_AUTH_REQUIRED)
5584 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005585 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5586 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005587
5588 string message = "Hello World!";
5589 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005590 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005591 EXPECT_EQ(2048U / 8, ciphertext1.size());
5592
David Drysdale59cae642021-05-12 13:52:03 +01005593 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005594 EXPECT_EQ(2048U / 8, ciphertext2.size());
5595
5596 // PKCS1 v1.5 randomizes padding so every result should be different.
5597 EXPECT_NE(ciphertext1, ciphertext2);
5598
5599 string plaintext = DecryptMessage(ciphertext1, params);
5600 EXPECT_EQ(message, plaintext);
5601
5602 // Decrypting corrupted ciphertext should fail.
5603 size_t offset_to_corrupt = random() % ciphertext1.size();
5604 char corrupt_byte;
5605 do {
5606 corrupt_byte = static_cast<char>(random() % 256);
5607 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5608 ciphertext1[offset_to_corrupt] = corrupt_byte;
5609
5610 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5611 string result;
5612 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5613 EXPECT_EQ(0U, result.size());
5614}
5615
5616/*
Selene Huang31ab4042020-04-29 04:22:39 -07005617 * EncryptionOperationsTest.EcdsaEncrypt
5618 *
5619 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5620 */
5621TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5623 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005624 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005625 .Digest(Digest::NONE)
5626 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005627 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5628 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5629 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5630}
5631
5632/*
5633 * EncryptionOperationsTest.HmacEncrypt
5634 *
5635 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5636 */
5637TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5639 .Authorization(TAG_NO_AUTH_REQUIRED)
5640 .HmacKey(128)
5641 .Digest(Digest::SHA_2_256)
5642 .Padding(PaddingMode::NONE)
5643 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5644 auto params = AuthorizationSetBuilder()
5645 .Digest(Digest::SHA_2_256)
5646 .Padding(PaddingMode::NONE)
5647 .Authorization(TAG_MAC_LENGTH, 128);
5648 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5649 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5650}
5651
5652/*
5653 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5654 *
5655 * Verifies that AES ECB mode works.
5656 */
5657TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5659 .Authorization(TAG_NO_AUTH_REQUIRED)
5660 .AesEncryptionKey(128)
5661 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5662 .Padding(PaddingMode::NONE)));
5663
5664 ASSERT_GT(key_blob_.size(), 0U);
5665 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5666
5667 // Two-block message.
5668 string message = "12345678901234567890123456789012";
5669 string ciphertext1 = EncryptMessage(message, params);
5670 EXPECT_EQ(message.size(), ciphertext1.size());
5671
5672 string ciphertext2 = EncryptMessage(string(message), params);
5673 EXPECT_EQ(message.size(), ciphertext2.size());
5674
5675 // ECB is deterministic.
5676 EXPECT_EQ(ciphertext1, ciphertext2);
5677
5678 string plaintext = DecryptMessage(ciphertext1, params);
5679 EXPECT_EQ(message, plaintext);
5680}
5681
5682/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005683 * EncryptionOperationsTest.AesEcbUnknownTag
5684 *
5685 * Verifies that AES ECB operations ignore unknown tags.
5686 */
5687TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5688 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5689 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5690 KeyParameter unknown_param;
5691 unknown_param.tag = unknown_tag;
5692
5693 vector<KeyCharacteristics> key_characteristics;
5694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5695 .Authorization(TAG_NO_AUTH_REQUIRED)
5696 .AesEncryptionKey(128)
5697 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5698 .Padding(PaddingMode::NONE)
5699 .Authorization(unknown_param),
5700 &key_blob_, &key_characteristics));
5701 ASSERT_GT(key_blob_.size(), 0U);
5702
5703 // Unknown tags should not be returned in key characteristics.
5704 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5705 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5706 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5707 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5708
5709 // Encrypt without mentioning the unknown parameter.
5710 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5711 string message = "12345678901234567890123456789012";
5712 string ciphertext = EncryptMessage(message, params);
5713 EXPECT_EQ(message.size(), ciphertext.size());
5714
5715 // Decrypt including the unknown parameter.
5716 auto decrypt_params = AuthorizationSetBuilder()
5717 .BlockMode(BlockMode::ECB)
5718 .Padding(PaddingMode::NONE)
5719 .Authorization(unknown_param);
5720 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5721 EXPECT_EQ(message, plaintext);
5722}
5723
5724/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005725 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005726 *
5727 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5728 */
5729TEST_P(EncryptionOperationsTest, AesWrongMode) {
5730 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5731 .Authorization(TAG_NO_AUTH_REQUIRED)
5732 .AesEncryptionKey(128)
5733 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5734 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005735 ASSERT_GT(key_blob_.size(), 0U);
5736
Selene Huang31ab4042020-04-29 04:22:39 -07005737 EXPECT_EQ(
5738 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5739 Begin(KeyPurpose::ENCRYPT,
5740 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5741}
5742
5743/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005744 * EncryptionOperationsTest.AesWrongPadding
5745 *
5746 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5747 */
5748TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5749 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5750 .Authorization(TAG_NO_AUTH_REQUIRED)
5751 .AesEncryptionKey(128)
5752 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5753 .Padding(PaddingMode::NONE)));
5754 ASSERT_GT(key_blob_.size(), 0U);
5755
5756 EXPECT_EQ(
5757 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5758 Begin(KeyPurpose::ENCRYPT,
5759 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5760}
5761
5762/*
5763 * EncryptionOperationsTest.AesInvalidParams
5764 *
5765 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5766 */
5767TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5768 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5769 .Authorization(TAG_NO_AUTH_REQUIRED)
5770 .AesEncryptionKey(128)
5771 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5772 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5773 .Padding(PaddingMode::NONE)
5774 .Padding(PaddingMode::PKCS7)));
5775 ASSERT_GT(key_blob_.size(), 0U);
5776
5777 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5778 .BlockMode(BlockMode::CBC)
5779 .BlockMode(BlockMode::ECB)
5780 .Padding(PaddingMode::NONE));
5781 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5782 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5783
5784 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5785 .BlockMode(BlockMode::ECB)
5786 .Padding(PaddingMode::NONE)
5787 .Padding(PaddingMode::PKCS7));
5788 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5789 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5790}
5791
5792/*
Selene Huang31ab4042020-04-29 04:22:39 -07005793 * EncryptionOperationsTest.AesWrongPurpose
5794 *
5795 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5796 * specified.
5797 */
5798TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5799 auto err = GenerateKey(AuthorizationSetBuilder()
5800 .Authorization(TAG_NO_AUTH_REQUIRED)
5801 .AesKey(128)
5802 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5803 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5804 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5805 .Padding(PaddingMode::NONE));
5806 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5807 ASSERT_GT(key_blob_.size(), 0U);
5808
5809 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5810 .BlockMode(BlockMode::GCM)
5811 .Padding(PaddingMode::NONE)
5812 .Authorization(TAG_MAC_LENGTH, 128));
5813 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5814
5815 CheckedDeleteKey();
5816
5817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5818 .Authorization(TAG_NO_AUTH_REQUIRED)
5819 .AesKey(128)
5820 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5821 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5822 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5823 .Padding(PaddingMode::NONE)));
5824
5825 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5826 .BlockMode(BlockMode::GCM)
5827 .Padding(PaddingMode::NONE)
5828 .Authorization(TAG_MAC_LENGTH, 128));
5829 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5830}
5831
5832/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005833 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005834 *
5835 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5836 * multiple of the block size and no padding is specified.
5837 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005838TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5839 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005840 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005841 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5842 .Authorization(TAG_NO_AUTH_REQUIRED)
5843 .AesEncryptionKey(128)
5844 .Authorization(TAG_BLOCK_MODE, blockMode)
5845 .Padding(PaddingMode::NONE)));
5846 // Message is slightly shorter than two blocks.
5847 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005848
David Drysdaled2cc8c22021-04-15 13:29:45 +01005849 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5850 AuthorizationSet out_params;
5851 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5852 string ciphertext;
5853 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5854 EXPECT_EQ(0U, ciphertext.size());
5855
5856 CheckedDeleteKey();
5857 }
Selene Huang31ab4042020-04-29 04:22:39 -07005858}
5859
5860/*
5861 * EncryptionOperationsTest.AesEcbPkcs7Padding
5862 *
5863 * Verifies that AES PKCS7 padding works for any message length.
5864 */
5865TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5867 .Authorization(TAG_NO_AUTH_REQUIRED)
5868 .AesEncryptionKey(128)
5869 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5870 .Padding(PaddingMode::PKCS7)));
5871
5872 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5873
5874 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005875 for (size_t i = 0; i <= 48; i++) {
5876 SCOPED_TRACE(testing::Message() << "i = " << i);
5877 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5878 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005879 string ciphertext = EncryptMessage(message, params);
5880 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5881 string plaintext = DecryptMessage(ciphertext, params);
5882 EXPECT_EQ(message, plaintext);
5883 }
5884}
5885
5886/*
5887 * EncryptionOperationsTest.AesEcbWrongPadding
5888 *
5889 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5890 * specified.
5891 */
5892TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5894 .Authorization(TAG_NO_AUTH_REQUIRED)
5895 .AesEncryptionKey(128)
5896 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5897 .Padding(PaddingMode::NONE)));
5898
5899 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5900
5901 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005902 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005903 string message(i, 'a');
5904 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5905 }
5906}
5907
5908/*
5909 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5910 *
5911 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5912 */
5913TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5914 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5915 .Authorization(TAG_NO_AUTH_REQUIRED)
5916 .AesEncryptionKey(128)
5917 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5918 .Padding(PaddingMode::PKCS7)));
5919
5920 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5921
5922 string message = "a";
5923 string ciphertext = EncryptMessage(message, params);
5924 EXPECT_EQ(16U, ciphertext.size());
5925 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005926
Seth Moore7a55ae32021-06-23 14:28:11 -07005927 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5928 ++ciphertext[ciphertext.size() / 2];
5929
5930 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5931 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005932 ErrorCode error = Finish(ciphertext, &plaintext);
5933 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005934 // This is the expected error, we can exit the test now.
5935 return;
5936 } else {
5937 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005938 ASSERT_EQ(error, ErrorCode::OK)
5939 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005940 }
5941 }
5942 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005943}
5944
David Drysdaleb8093292022-04-08 12:22:35 +01005945/*
5946 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5947 *
5948 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5949 */
5950TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5951 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5952 .Authorization(TAG_NO_AUTH_REQUIRED)
5953 .AesEncryptionKey(128)
5954 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5955 .Padding(PaddingMode::PKCS7)));
5956
5957 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5958
5959 string message = "a";
5960 string ciphertext = EncryptMessage(message, params);
5961 EXPECT_EQ(16U, ciphertext.size());
5962 EXPECT_NE(ciphertext, message);
5963
5964 // Shorten the ciphertext.
5965 ciphertext.resize(ciphertext.size() - 1);
5966 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5967 string plaintext;
5968 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5969}
5970
Selene Huang31ab4042020-04-29 04:22:39 -07005971vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5972 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005973 EXPECT_TRUE(iv);
5974 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005975}
5976
5977/*
5978 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5979 *
5980 * Verifies that AES CTR mode works.
5981 */
5982TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5983 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5984 .Authorization(TAG_NO_AUTH_REQUIRED)
5985 .AesEncryptionKey(128)
5986 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5987 .Padding(PaddingMode::NONE)));
5988
5989 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5990
5991 string message = "123";
5992 AuthorizationSet out_params;
5993 string ciphertext1 = EncryptMessage(message, params, &out_params);
5994 vector<uint8_t> iv1 = CopyIv(out_params);
5995 EXPECT_EQ(16U, iv1.size());
5996
5997 EXPECT_EQ(message.size(), ciphertext1.size());
5998
5999 out_params.Clear();
6000 string ciphertext2 = EncryptMessage(message, params, &out_params);
6001 vector<uint8_t> iv2 = CopyIv(out_params);
6002 EXPECT_EQ(16U, iv2.size());
6003
6004 // IVs should be random, so ciphertexts should differ.
6005 EXPECT_NE(ciphertext1, ciphertext2);
6006
6007 auto params_iv1 =
6008 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6009 auto params_iv2 =
6010 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6011
6012 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6013 EXPECT_EQ(message, plaintext);
6014 plaintext = DecryptMessage(ciphertext2, params_iv2);
6015 EXPECT_EQ(message, plaintext);
6016
6017 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6018 plaintext = DecryptMessage(ciphertext1, params_iv2);
6019 EXPECT_NE(message, plaintext);
6020 plaintext = DecryptMessage(ciphertext2, params_iv1);
6021 EXPECT_NE(message, plaintext);
6022}
6023
6024/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306025 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006026 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306027 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006028 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306029TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6030 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6031}
Selene Huang31ab4042020-04-29 04:22:39 -07006032
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306033/*
6034 * EncryptionOperationsTest.AesCbcIncremental
6035 *
6036 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6037 */
6038TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6039 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6040}
Selene Huang31ab4042020-04-29 04:22:39 -07006041
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306042/*
6043 * EncryptionOperationsTest.AesCtrIncremental
6044 *
6045 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6046 */
6047TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6048 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6049}
Selene Huang31ab4042020-04-29 04:22:39 -07006050
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306051/*
6052 * EncryptionOperationsTest.AesGcmIncremental
6053 *
6054 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6055 */
6056TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6057 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006058}
6059
Prashant Patildd5f7f02022-07-06 18:58:07 +00006060/*
6061 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6062 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6063 */
6064TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6065 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6066 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6067 string kat_plaintext =
6068 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6069 "809FFF37081C22EF278F896AB213A2A631");
6070 string kat_ciphertext =
6071 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6072 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6073 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6074 kat_ciphertext);
6075}
6076
6077/*
6078 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6079 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6080 */
6081TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6082 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6083 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6084 string kat_plaintext =
6085 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6086 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6087 string kat_ciphertext =
6088 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6089 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6090 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6091 kat_plaintext, kat_ciphertext);
6092}
6093
6094/*
6095 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6096 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6097 */
6098TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6099 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6100 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6101 string kat_plaintext =
6102 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6103 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6104 string kat_ciphertext =
6105 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6106 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6107 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6108 kat_ciphertext);
6109}
6110
6111/*
6112 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6113 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6114 */
6115TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6116 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6117 string kat_plaintext =
6118 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6119 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6120 string kat_ciphertext =
6121 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6122 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6123 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6124 kat_ciphertext);
6125}
6126
6127/*
6128 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6129 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6130 */
6131TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6132 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6133 string kat_plaintext =
6134 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6135 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6136 string kat_ciphertext =
6137 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6138 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6139 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6140 kat_ciphertext);
6141}
6142
6143/*
6144 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6145 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6146 */
6147TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6148 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6149 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6150 string kat_plaintext =
6151 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6152 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6153 string kat_ciphertext =
6154 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6155 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6156 "bdfcc0cba0");
6157
6158 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6159 kat_ciphertext);
6160}
6161
6162/*
6163 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6164 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6165 */
6166TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6167 if (SecLevel() == SecurityLevel::STRONGBOX) {
6168 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6169 }
6170 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6171 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6172 string kat_plaintext =
6173 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6174 "167f2497c994bd496eb80bfb2ba2c9d5af");
6175 string kat_ciphertext =
6176 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6177 "72c134552f3a138e726fbe493b3a839598");
6178 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6179 kat_ciphertext);
6180}
6181
6182/*
6183 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6184 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6185 */
6186TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6187 if (SecLevel() == SecurityLevel::STRONGBOX) {
6188 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6189 }
6190 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6191 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6192 string kat_plaintext =
6193 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6194 "b170");
6195 string kat_ciphertext =
6196 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6197 "4e3884138ff403a41fd99818708ada301c");
6198 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6199 kat_plaintext, kat_ciphertext);
6200}
6201
6202/*
6203 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6204 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6205 */
6206TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6207 if (SecLevel() == SecurityLevel::STRONGBOX) {
6208 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6209 }
6210 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6211 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6212 string kat_plaintext =
6213 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6214 "28091e09cdbbd3b42b");
6215 string kat_ciphertext =
6216 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6217 "2ae0f90f0c19f42b4a");
6218 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6219 kat_ciphertext);
6220}
6221
6222/*
6223 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6224 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6225 */
6226TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6227 if (SecLevel() == SecurityLevel::STRONGBOX) {
6228 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6229 }
6230 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6231 string kat_plaintext =
6232 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6233 "44ab");
6234 string kat_ciphertext =
6235 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6236 "2453");
6237 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6238 kat_ciphertext);
6239}
6240
6241/*
6242 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6243 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6244 */
6245TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6246 if (SecLevel() == SecurityLevel::STRONGBOX) {
6247 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6248 }
6249 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6250 string kat_plaintext =
6251 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6252 "e2c7");
6253 string kat_ciphertext =
6254 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6255 "bb7e3a889dd4a9589098b44acf1056e7aa");
6256 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6257 kat_ciphertext);
6258}
6259
6260/*
6261 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6262 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6263 */
6264TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6265 if (SecLevel() == SecurityLevel::STRONGBOX) {
6266 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6267 }
6268 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6269 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6270 string kat_plaintext =
6271 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6272 "ff52");
6273 string kat_ciphertext =
6274 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6275 "1413ad70fb0e1970669095ad77ebb5974ae8");
6276
6277 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6278 kat_ciphertext);
6279}
6280
6281/*
6282 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6283 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6284 */
6285TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6286 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6287 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6288 string kat_plaintext =
6289 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6290 "494cb53caca353e4b637ba05687be20f8d");
6291 string kat_ciphertext =
6292 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6293 "6047da1e4fd7c4e1cf2656097f75ae8685");
6294 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6295 kat_ciphertext);
6296}
6297
6298/*
6299 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6300 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6301 */
6302TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6303 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6304 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6305 string kat_plaintext =
6306 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6307 "2545a82b73c48078b9dae62261c65909");
6308 string kat_ciphertext =
6309 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6310 "9403a71987b95124073d69f2a3cb95b0ab");
6311 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6312 kat_plaintext, kat_ciphertext);
6313}
6314
6315/*
6316 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6317 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6318 */
6319TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6320 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6321 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6322 string kat_plaintext =
6323 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6324 "1f6db3c884");
6325 string kat_ciphertext =
6326 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6327 "a7be30d4c3");
6328 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6329 kat_ciphertext);
6330}
6331
6332/*
6333 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6334 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6335 */
6336TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6337 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6338 string kat_plaintext =
6339 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6340 "31a476d6806b8116089c6ec50bb543200f");
6341 string kat_ciphertext =
6342 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6343 "c83e377faf246288931136bef2a07c0be4");
6344 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6345 kat_ciphertext);
6346}
6347
6348/*
6349 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6350 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6351 */
6352TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6353 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6354 string kat_plaintext =
6355 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6356 "6f");
6357 string kat_ciphertext =
6358 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6359 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6360 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6361 kat_ciphertext);
6362}
6363
6364/*
6365 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6366 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6367 */
6368TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6369 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6370 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6371 string kat_plaintext =
6372 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6373 "f0");
6374 string kat_ciphertext =
6375 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6376 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6377
6378 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6379 kat_ciphertext);
6380}
6381
Selene Huang31ab4042020-04-29 04:22:39 -07006382struct AesCtrSp80038aTestVector {
6383 const char* key;
6384 const char* nonce;
6385 const char* plaintext;
6386 const char* ciphertext;
6387};
6388
6389// These test vectors are taken from
6390// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6391static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6392 // AES-128
6393 {
6394 "2b7e151628aed2a6abf7158809cf4f3c",
6395 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6396 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6397 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6398 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6399 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6400 },
6401 // AES-192
6402 {
6403 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6404 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6405 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6406 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6407 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6408 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6409 },
6410 // AES-256
6411 {
6412 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6413 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6414 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6415 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6416 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6417 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6418 },
6419};
6420
6421/*
6422 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6423 *
6424 * Verifies AES CTR implementation against SP800-38A test vectors.
6425 */
6426TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6427 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6428 for (size_t i = 0; i < 3; i++) {
6429 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6430 const string key = hex2str(test.key);
6431 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6432 InvalidSizes.end())
6433 continue;
6434 const string nonce = hex2str(test.nonce);
6435 const string plaintext = hex2str(test.plaintext);
6436 const string ciphertext = hex2str(test.ciphertext);
6437 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6438 }
6439}
6440
6441/*
6442 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6443 *
6444 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6445 */
6446TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6447 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6448 .Authorization(TAG_NO_AUTH_REQUIRED)
6449 .AesEncryptionKey(128)
6450 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6451 .Padding(PaddingMode::PKCS7)));
6452 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6453 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6454}
6455
6456/*
6457 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6458 *
6459 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6460 */
6461TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6462 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6463 .Authorization(TAG_NO_AUTH_REQUIRED)
6464 .AesEncryptionKey(128)
6465 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6466 .Authorization(TAG_CALLER_NONCE)
6467 .Padding(PaddingMode::NONE)));
6468
6469 auto params = AuthorizationSetBuilder()
6470 .BlockMode(BlockMode::CTR)
6471 .Padding(PaddingMode::NONE)
6472 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6473 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6474
6475 params = AuthorizationSetBuilder()
6476 .BlockMode(BlockMode::CTR)
6477 .Padding(PaddingMode::NONE)
6478 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6479 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6480
6481 params = AuthorizationSetBuilder()
6482 .BlockMode(BlockMode::CTR)
6483 .Padding(PaddingMode::NONE)
6484 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6485 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6486}
6487
6488/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006489 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006490 *
6491 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6492 */
6493TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6495 .Authorization(TAG_NO_AUTH_REQUIRED)
6496 .AesEncryptionKey(128)
6497 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6498 .Padding(PaddingMode::NONE)));
6499 // Two-block message.
6500 string message = "12345678901234567890123456789012";
6501 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6502 AuthorizationSet out_params;
6503 string ciphertext1 = EncryptMessage(message, params, &out_params);
6504 vector<uint8_t> iv1 = CopyIv(out_params);
6505 EXPECT_EQ(message.size(), ciphertext1.size());
6506
6507 out_params.Clear();
6508
6509 string ciphertext2 = EncryptMessage(message, params, &out_params);
6510 vector<uint8_t> iv2 = CopyIv(out_params);
6511 EXPECT_EQ(message.size(), ciphertext2.size());
6512
6513 // IVs should be random, so ciphertexts should differ.
6514 EXPECT_NE(ciphertext1, ciphertext2);
6515
6516 params.push_back(TAG_NONCE, iv1);
6517 string plaintext = DecryptMessage(ciphertext1, params);
6518 EXPECT_EQ(message, plaintext);
6519}
6520
6521/*
Tommy Chiuee705692021-09-23 20:09:13 +08006522 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6523 *
6524 * Verifies that keymaster generates correct output on zero-input with
6525 * NonePadding mode
6526 */
6527TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6528 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6529 .Authorization(TAG_NO_AUTH_REQUIRED)
6530 .AesEncryptionKey(128)
6531 .BlockMode(BlockMode::CBC)
6532 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6533
6534 // Zero input message
6535 string message = "";
6536 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006537 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006538 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6539 AuthorizationSet out_params;
6540 string ciphertext1 = EncryptMessage(message, params, &out_params);
6541 vector<uint8_t> iv1 = CopyIv(out_params);
6542 if (padding == PaddingMode::NONE)
6543 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6544 else
6545 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6546
6547 out_params.Clear();
6548
6549 string ciphertext2 = EncryptMessage(message, params, &out_params);
6550 vector<uint8_t> iv2 = CopyIv(out_params);
6551 if (padding == PaddingMode::NONE)
6552 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6553 else
6554 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6555
6556 // IVs should be random
6557 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6558
6559 params.push_back(TAG_NONCE, iv1);
6560 string plaintext = DecryptMessage(ciphertext1, params);
6561 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6562 }
6563}
6564
6565/*
Selene Huang31ab4042020-04-29 04:22:39 -07006566 * EncryptionOperationsTest.AesCallerNonce
6567 *
6568 * Verifies that AES caller-provided nonces work correctly.
6569 */
6570TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6571 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6572 .Authorization(TAG_NO_AUTH_REQUIRED)
6573 .AesEncryptionKey(128)
6574 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6575 .Authorization(TAG_CALLER_NONCE)
6576 .Padding(PaddingMode::NONE)));
6577
6578 string message = "12345678901234567890123456789012";
6579
6580 // Don't specify nonce, should get a random one.
6581 AuthorizationSetBuilder params =
6582 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6583 AuthorizationSet out_params;
6584 string ciphertext = EncryptMessage(message, params, &out_params);
6585 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006586 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006587
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006588 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006589 string plaintext = DecryptMessage(ciphertext, params);
6590 EXPECT_EQ(message, plaintext);
6591
6592 // Now specify a nonce, should also work.
6593 params = AuthorizationSetBuilder()
6594 .BlockMode(BlockMode::CBC)
6595 .Padding(PaddingMode::NONE)
6596 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6597 out_params.Clear();
6598 ciphertext = EncryptMessage(message, params, &out_params);
6599
6600 // Decrypt with correct nonce.
6601 plaintext = DecryptMessage(ciphertext, params);
6602 EXPECT_EQ(message, plaintext);
6603
6604 // Try with wrong nonce.
6605 params = AuthorizationSetBuilder()
6606 .BlockMode(BlockMode::CBC)
6607 .Padding(PaddingMode::NONE)
6608 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6609 plaintext = DecryptMessage(ciphertext, params);
6610 EXPECT_NE(message, plaintext);
6611}
6612
6613/*
6614 * EncryptionOperationsTest.AesCallerNonceProhibited
6615 *
6616 * Verifies that caller-provided nonces are not permitted when not specified in the key
6617 * authorizations.
6618 */
6619TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6621 .Authorization(TAG_NO_AUTH_REQUIRED)
6622 .AesEncryptionKey(128)
6623 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6624 .Padding(PaddingMode::NONE)));
6625
6626 string message = "12345678901234567890123456789012";
6627
6628 // Don't specify nonce, should get a random one.
6629 AuthorizationSetBuilder params =
6630 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6631 AuthorizationSet out_params;
6632 string ciphertext = EncryptMessage(message, params, &out_params);
6633 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006634 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006635
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006636 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006637 string plaintext = DecryptMessage(ciphertext, params);
6638 EXPECT_EQ(message, plaintext);
6639
6640 // Now specify a nonce, should fail
6641 params = AuthorizationSetBuilder()
6642 .BlockMode(BlockMode::CBC)
6643 .Padding(PaddingMode::NONE)
6644 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6645 out_params.Clear();
6646 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6647}
6648
6649/*
6650 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6651 *
6652 * Verifies that AES GCM mode works.
6653 */
6654TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6655 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6656 .Authorization(TAG_NO_AUTH_REQUIRED)
6657 .AesEncryptionKey(128)
6658 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6659 .Padding(PaddingMode::NONE)
6660 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6661
6662 string aad = "foobar";
6663 string message = "123456789012345678901234567890123456";
6664
6665 auto begin_params = AuthorizationSetBuilder()
6666 .BlockMode(BlockMode::GCM)
6667 .Padding(PaddingMode::NONE)
6668 .Authorization(TAG_MAC_LENGTH, 128);
6669
Selene Huang31ab4042020-04-29 04:22:39 -07006670 // Encrypt
6671 AuthorizationSet begin_out_params;
6672 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6673 << "Begin encrypt";
6674 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006675 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6676 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006677 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6678
6679 // Grab nonce
6680 begin_params.push_back(begin_out_params);
6681
6682 // Decrypt.
6683 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006684 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006685 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006686 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006687 EXPECT_EQ(message.length(), plaintext.length());
6688 EXPECT_EQ(message, plaintext);
6689}
6690
6691/*
6692 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6693 *
6694 * Verifies that AES GCM mode works, even when there's a long delay
6695 * between operations.
6696 */
6697TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6699 .Authorization(TAG_NO_AUTH_REQUIRED)
6700 .AesEncryptionKey(128)
6701 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6702 .Padding(PaddingMode::NONE)
6703 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6704
6705 string aad = "foobar";
6706 string message = "123456789012345678901234567890123456";
6707
6708 auto begin_params = AuthorizationSetBuilder()
6709 .BlockMode(BlockMode::GCM)
6710 .Padding(PaddingMode::NONE)
6711 .Authorization(TAG_MAC_LENGTH, 128);
6712
Selene Huang31ab4042020-04-29 04:22:39 -07006713 // Encrypt
6714 AuthorizationSet begin_out_params;
6715 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6716 << "Begin encrypt";
6717 string ciphertext;
6718 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006719 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006720 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006721 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006722
6723 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6724
6725 // Grab nonce
6726 begin_params.push_back(begin_out_params);
6727
6728 // Decrypt.
6729 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6730 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006731 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006732 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006733 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006734 sleep(5);
6735 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6736 EXPECT_EQ(message.length(), plaintext.length());
6737 EXPECT_EQ(message, plaintext);
6738}
6739
6740/*
6741 * EncryptionOperationsTest.AesGcmDifferentNonces
6742 *
6743 * Verifies that encrypting the same data with different nonces produces different outputs.
6744 */
6745TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6747 .Authorization(TAG_NO_AUTH_REQUIRED)
6748 .AesEncryptionKey(128)
6749 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6750 .Padding(PaddingMode::NONE)
6751 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6752 .Authorization(TAG_CALLER_NONCE)));
6753
6754 string aad = "foobar";
6755 string message = "123456789012345678901234567890123456";
6756 string nonce1 = "000000000000";
6757 string nonce2 = "111111111111";
6758 string nonce3 = "222222222222";
6759
6760 string ciphertext1 =
6761 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6762 string ciphertext2 =
6763 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6764 string ciphertext3 =
6765 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6766
6767 ASSERT_NE(ciphertext1, ciphertext2);
6768 ASSERT_NE(ciphertext1, ciphertext3);
6769 ASSERT_NE(ciphertext2, ciphertext3);
6770}
6771
6772/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006773 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6774 *
6775 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6776 */
6777TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6778 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6779 .Authorization(TAG_NO_AUTH_REQUIRED)
6780 .AesEncryptionKey(128)
6781 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6782 .Padding(PaddingMode::NONE)
6783 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6784
6785 string aad = "foobar";
6786 string message = "123456789012345678901234567890123456";
6787
6788 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6789 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6790 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6791
6792 ASSERT_NE(ciphertext1, ciphertext2);
6793 ASSERT_NE(ciphertext1, ciphertext3);
6794 ASSERT_NE(ciphertext2, ciphertext3);
6795}
6796
6797/*
Selene Huang31ab4042020-04-29 04:22:39 -07006798 * EncryptionOperationsTest.AesGcmTooShortTag
6799 *
6800 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6801 */
6802TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6804 .Authorization(TAG_NO_AUTH_REQUIRED)
6805 .AesEncryptionKey(128)
6806 .BlockMode(BlockMode::GCM)
6807 .Padding(PaddingMode::NONE)
6808 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6809 string message = "123456789012345678901234567890123456";
6810 auto params = AuthorizationSetBuilder()
6811 .BlockMode(BlockMode::GCM)
6812 .Padding(PaddingMode::NONE)
6813 .Authorization(TAG_MAC_LENGTH, 96);
6814
6815 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6816}
6817
6818/*
6819 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6820 *
6821 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6822 */
6823TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6824 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6825 .Authorization(TAG_NO_AUTH_REQUIRED)
6826 .AesEncryptionKey(128)
6827 .BlockMode(BlockMode::GCM)
6828 .Padding(PaddingMode::NONE)
6829 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6830 string aad = "foobar";
6831 string message = "123456789012345678901234567890123456";
6832 auto params = AuthorizationSetBuilder()
6833 .BlockMode(BlockMode::GCM)
6834 .Padding(PaddingMode::NONE)
6835 .Authorization(TAG_MAC_LENGTH, 128);
6836
Selene Huang31ab4042020-04-29 04:22:39 -07006837 // Encrypt
6838 AuthorizationSet begin_out_params;
6839 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6840 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006841 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006842
6843 AuthorizationSet finish_out_params;
6844 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006845 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6846 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006847
6848 params = AuthorizationSetBuilder()
6849 .Authorizations(begin_out_params)
6850 .BlockMode(BlockMode::GCM)
6851 .Padding(PaddingMode::NONE)
6852 .Authorization(TAG_MAC_LENGTH, 96);
6853
6854 // Decrypt.
6855 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6856}
6857
6858/*
6859 * EncryptionOperationsTest.AesGcmCorruptKey
6860 *
6861 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6862 */
6863TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6864 const uint8_t nonce_bytes[] = {
6865 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6866 };
6867 string nonce = make_string(nonce_bytes);
6868 const uint8_t ciphertext_bytes[] = {
6869 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6870 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6871 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6872 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6873 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6874 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6875 };
6876 string ciphertext = make_string(ciphertext_bytes);
6877
6878 auto params = AuthorizationSetBuilder()
6879 .BlockMode(BlockMode::GCM)
6880 .Padding(PaddingMode::NONE)
6881 .Authorization(TAG_MAC_LENGTH, 128)
6882 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6883
6884 auto import_params = AuthorizationSetBuilder()
6885 .Authorization(TAG_NO_AUTH_REQUIRED)
6886 .AesEncryptionKey(128)
6887 .BlockMode(BlockMode::GCM)
6888 .Padding(PaddingMode::NONE)
6889 .Authorization(TAG_CALLER_NONCE)
6890 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6891
6892 // Import correct key and decrypt
6893 const uint8_t key_bytes[] = {
6894 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6895 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6896 };
6897 string key = make_string(key_bytes);
6898 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6899 string plaintext = DecryptMessage(ciphertext, params);
6900 CheckedDeleteKey();
6901
6902 // Corrupt key and attempt to decrypt
6903 key[0] = 0;
6904 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6905 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6906 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6907 CheckedDeleteKey();
6908}
6909
6910/*
6911 * EncryptionOperationsTest.AesGcmAadNoData
6912 *
6913 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6914 * encrypt.
6915 */
6916TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6918 .Authorization(TAG_NO_AUTH_REQUIRED)
6919 .AesEncryptionKey(128)
6920 .BlockMode(BlockMode::GCM)
6921 .Padding(PaddingMode::NONE)
6922 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6923
6924 string aad = "1234567890123456";
6925 auto params = AuthorizationSetBuilder()
6926 .BlockMode(BlockMode::GCM)
6927 .Padding(PaddingMode::NONE)
6928 .Authorization(TAG_MAC_LENGTH, 128);
6929
Selene Huang31ab4042020-04-29 04:22:39 -07006930 // Encrypt
6931 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006932 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006933 string ciphertext;
6934 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006935 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6936 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006937 EXPECT_TRUE(finish_out_params.empty());
6938
6939 // Grab nonce
6940 params.push_back(begin_out_params);
6941
6942 // Decrypt.
6943 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006944 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006945 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006946 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006947
6948 EXPECT_TRUE(finish_out_params.empty());
6949
6950 EXPECT_EQ("", plaintext);
6951}
6952
6953/*
6954 * EncryptionOperationsTest.AesGcmMultiPartAad
6955 *
6956 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6957 * chunks.
6958 */
6959TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6960 const size_t tag_bits = 128;
6961 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6962 .Authorization(TAG_NO_AUTH_REQUIRED)
6963 .AesEncryptionKey(128)
6964 .BlockMode(BlockMode::GCM)
6965 .Padding(PaddingMode::NONE)
6966 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6967
6968 string message = "123456789012345678901234567890123456";
6969 auto begin_params = AuthorizationSetBuilder()
6970 .BlockMode(BlockMode::GCM)
6971 .Padding(PaddingMode::NONE)
6972 .Authorization(TAG_MAC_LENGTH, tag_bits);
6973 AuthorizationSet begin_out_params;
6974
David Drysdale7fc26b92022-05-13 09:54:24 +01006975 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006976
6977 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006978 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6979 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006980 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006981 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6982 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006983
Selene Huang31ab4042020-04-29 04:22:39 -07006984 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006985 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006986
6987 // Grab nonce.
6988 begin_params.push_back(begin_out_params);
6989
6990 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006991 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006992 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006993 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006994 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006995 EXPECT_EQ(message, plaintext);
6996}
6997
6998/*
6999 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7000 *
7001 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7002 */
7003TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7005 .Authorization(TAG_NO_AUTH_REQUIRED)
7006 .AesEncryptionKey(128)
7007 .BlockMode(BlockMode::GCM)
7008 .Padding(PaddingMode::NONE)
7009 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7010
7011 string message = "123456789012345678901234567890123456";
7012 auto begin_params = AuthorizationSetBuilder()
7013 .BlockMode(BlockMode::GCM)
7014 .Padding(PaddingMode::NONE)
7015 .Authorization(TAG_MAC_LENGTH, 128);
7016 AuthorizationSet begin_out_params;
7017
David Drysdale7fc26b92022-05-13 09:54:24 +01007018 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007019
Shawn Willden92d79c02021-02-19 07:31:55 -07007020 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007021 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007022 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7023 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007024
David Drysdaled2cc8c22021-04-15 13:29:45 +01007025 // The failure should have already cancelled the operation.
7026 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7027
Shawn Willden92d79c02021-02-19 07:31:55 -07007028 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007029}
7030
7031/*
7032 * EncryptionOperationsTest.AesGcmBadAad
7033 *
7034 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7035 */
7036TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7038 .Authorization(TAG_NO_AUTH_REQUIRED)
7039 .AesEncryptionKey(128)
7040 .BlockMode(BlockMode::GCM)
7041 .Padding(PaddingMode::NONE)
7042 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7043
7044 string message = "12345678901234567890123456789012";
7045 auto begin_params = AuthorizationSetBuilder()
7046 .BlockMode(BlockMode::GCM)
7047 .Padding(PaddingMode::NONE)
7048 .Authorization(TAG_MAC_LENGTH, 128);
7049
Selene Huang31ab4042020-04-29 04:22:39 -07007050 // Encrypt
7051 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007052 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007053 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007054 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007055 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007056
7057 // Grab nonce
7058 begin_params.push_back(begin_out_params);
7059
Selene Huang31ab4042020-04-29 04:22:39 -07007060 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007061 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007062 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007063 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007064 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007065}
7066
7067/*
7068 * EncryptionOperationsTest.AesGcmWrongNonce
7069 *
7070 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7071 */
7072TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7073 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7074 .Authorization(TAG_NO_AUTH_REQUIRED)
7075 .AesEncryptionKey(128)
7076 .BlockMode(BlockMode::GCM)
7077 .Padding(PaddingMode::NONE)
7078 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7079
7080 string message = "12345678901234567890123456789012";
7081 auto begin_params = AuthorizationSetBuilder()
7082 .BlockMode(BlockMode::GCM)
7083 .Padding(PaddingMode::NONE)
7084 .Authorization(TAG_MAC_LENGTH, 128);
7085
Selene Huang31ab4042020-04-29 04:22:39 -07007086 // Encrypt
7087 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007088 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007089 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007090 string ciphertext;
7091 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007092 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007093
7094 // Wrong nonce
7095 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7096
7097 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007098 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007099 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007100 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007101 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007102
7103 // With wrong nonce, should have gotten garbage plaintext (or none).
7104 EXPECT_NE(message, plaintext);
7105}
7106
7107/*
7108 * EncryptionOperationsTest.AesGcmCorruptTag
7109 *
7110 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7111 */
7112TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7114 .Authorization(TAG_NO_AUTH_REQUIRED)
7115 .AesEncryptionKey(128)
7116 .BlockMode(BlockMode::GCM)
7117 .Padding(PaddingMode::NONE)
7118 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7119
7120 string aad = "1234567890123456";
7121 string message = "123456789012345678901234567890123456";
7122
7123 auto params = AuthorizationSetBuilder()
7124 .BlockMode(BlockMode::GCM)
7125 .Padding(PaddingMode::NONE)
7126 .Authorization(TAG_MAC_LENGTH, 128);
7127
Selene Huang31ab4042020-04-29 04:22:39 -07007128 // Encrypt
7129 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007130 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007131 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007132 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007133 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007134
7135 // Corrupt tag
7136 ++(*ciphertext.rbegin());
7137
7138 // Grab nonce
7139 params.push_back(begin_out_params);
7140
7141 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007142 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007143 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007144 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007145 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007146}
7147
7148/*
7149 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7150 *
7151 * Verifies that 3DES is basically functional.
7152 */
7153TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7154 auto auths = AuthorizationSetBuilder()
7155 .TripleDesEncryptionKey(168)
7156 .BlockMode(BlockMode::ECB)
7157 .Authorization(TAG_NO_AUTH_REQUIRED)
7158 .Padding(PaddingMode::NONE);
7159
7160 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7161 // Two-block message.
7162 string message = "1234567890123456";
7163 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7164 string ciphertext1 = EncryptMessage(message, inParams);
7165 EXPECT_EQ(message.size(), ciphertext1.size());
7166
7167 string ciphertext2 = EncryptMessage(string(message), inParams);
7168 EXPECT_EQ(message.size(), ciphertext2.size());
7169
7170 // ECB is deterministic.
7171 EXPECT_EQ(ciphertext1, ciphertext2);
7172
7173 string plaintext = DecryptMessage(ciphertext1, inParams);
7174 EXPECT_EQ(message, plaintext);
7175}
7176
7177/*
7178 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7179 *
7180 * Verifies that CBC keys reject ECB usage.
7181 */
7182TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7183 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7184 .TripleDesEncryptionKey(168)
7185 .BlockMode(BlockMode::CBC)
7186 .Authorization(TAG_NO_AUTH_REQUIRED)
7187 .Padding(PaddingMode::NONE)));
7188
7189 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7190 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7191}
7192
7193/*
7194 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7195 *
7196 * Tests ECB mode with PKCS#7 padding, various message sizes.
7197 */
7198TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7199 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7200 .TripleDesEncryptionKey(168)
7201 .BlockMode(BlockMode::ECB)
7202 .Authorization(TAG_NO_AUTH_REQUIRED)
7203 .Padding(PaddingMode::PKCS7)));
7204
7205 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007206 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007207 string message(i, 'a');
7208 auto inParams =
7209 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7210 string ciphertext = EncryptMessage(message, inParams);
7211 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7212 string plaintext = DecryptMessage(ciphertext, inParams);
7213 EXPECT_EQ(message, plaintext);
7214 }
7215}
7216
7217/*
7218 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7219 *
7220 * Verifies that keys configured for no padding reject PKCS7 padding
7221 */
7222TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7224 .TripleDesEncryptionKey(168)
7225 .BlockMode(BlockMode::ECB)
7226 .Authorization(TAG_NO_AUTH_REQUIRED)
7227 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007228 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7229 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007230}
7231
7232/*
7233 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7234 *
7235 * Verifies that corrupted padding is detected.
7236 */
7237TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7239 .TripleDesEncryptionKey(168)
7240 .BlockMode(BlockMode::ECB)
7241 .Authorization(TAG_NO_AUTH_REQUIRED)
7242 .Padding(PaddingMode::PKCS7)));
7243
7244 string message = "a";
7245 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7246 EXPECT_EQ(8U, ciphertext.size());
7247 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007248
7249 AuthorizationSetBuilder begin_params;
7250 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7251 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007252
7253 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7254 ++ciphertext[ciphertext.size() / 2];
7255
David Drysdale7fc26b92022-05-13 09:54:24 +01007256 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007257 string plaintext;
7258 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7259 ErrorCode error = Finish(&plaintext);
7260 if (error == ErrorCode::INVALID_ARGUMENT) {
7261 // This is the expected error, we can exit the test now.
7262 return;
7263 } else {
7264 // Very small chance we got valid decryption, so try again.
7265 ASSERT_EQ(error, ErrorCode::OK);
7266 }
7267 }
7268 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007269}
7270
7271struct TripleDesTestVector {
7272 const char* name;
7273 const KeyPurpose purpose;
7274 const BlockMode block_mode;
7275 const PaddingMode padding_mode;
7276 const char* key;
7277 const char* iv;
7278 const char* input;
7279 const char* output;
7280};
7281
7282// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7283// of the NIST vectors are multiples of the block size.
7284static const TripleDesTestVector kTripleDesTestVectors[] = {
7285 {
7286 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7287 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7288 "", // IV
7289 "329d86bdf1bc5af4", // input
7290 "d946c2756d78633f", // output
7291 },
7292 {
7293 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7294 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7295 "", // IV
7296 "6b1540781b01ce1997adae102dbf3c5b", // input
7297 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7298 },
7299 {
7300 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7301 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7302 "", // IV
7303 "6daad94ce08acfe7", // input
7304 "660e7d32dcc90e79", // output
7305 },
7306 {
7307 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7308 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7309 "", // IV
7310 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7311 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7312 },
7313 {
7314 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7315 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7316 "43f791134c5647ba", // IV
7317 "dcc153cef81d6f24", // input
7318 "92538bd8af18d3ba", // output
7319 },
7320 {
7321 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7322 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7323 "c2e999cb6249023c", // IV
7324 "c689aee38a301bb316da75db36f110b5", // input
7325 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7326 },
7327 {
7328 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7329 PaddingMode::PKCS7,
7330 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7331 "c2e999cb6249023c", // IV
7332 "c689aee38a301bb316da75db36f110b500", // input
7333 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7334 },
7335 {
7336 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7337 PaddingMode::PKCS7,
7338 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7339 "c2e999cb6249023c", // IV
7340 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7341 "c689aee38a301bb316da75db36f110b500", // output
7342 },
7343 {
7344 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7345 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7346 "41746c7e442d3681", // IV
7347 "c53a7b0ec40600fe", // input
7348 "d4f00eb455de1034", // output
7349 },
7350 {
7351 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7352 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7353 "3982bc02c3727d45", // IV
7354 "6006f10adef52991fcc777a1238bbb65", // input
7355 "edae09288e9e3bc05746d872b48e3b29", // output
7356 },
7357};
7358
7359/*
7360 * EncryptionOperationsTest.TripleDesTestVector
7361 *
7362 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7363 */
7364TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7365 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7366 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7367 SCOPED_TRACE(test->name);
7368 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7369 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7370 hex2str(test->output));
7371 }
7372}
7373
7374/*
7375 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7376 *
7377 * Validates CBC mode functionality.
7378 */
7379TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7381 .TripleDesEncryptionKey(168)
7382 .BlockMode(BlockMode::CBC)
7383 .Authorization(TAG_NO_AUTH_REQUIRED)
7384 .Padding(PaddingMode::NONE)));
7385
7386 ASSERT_GT(key_blob_.size(), 0U);
7387
Brian J Murray734c8412022-01-13 14:55:30 -08007388 // Four-block message.
7389 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007390 vector<uint8_t> iv1;
7391 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7392 EXPECT_EQ(message.size(), ciphertext1.size());
7393
7394 vector<uint8_t> iv2;
7395 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7396 EXPECT_EQ(message.size(), ciphertext2.size());
7397
7398 // IVs should be random, so ciphertexts should differ.
7399 EXPECT_NE(iv1, iv2);
7400 EXPECT_NE(ciphertext1, ciphertext2);
7401
7402 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7403 EXPECT_EQ(message, plaintext);
7404}
7405
7406/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007407 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7408 *
7409 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7410 */
7411TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7413 .TripleDesEncryptionKey(168)
7414 .BlockMode(BlockMode::CBC)
7415 .Authorization(TAG_NO_AUTH_REQUIRED)
7416 .Authorization(TAG_CALLER_NONCE)
7417 .Padding(PaddingMode::NONE)));
7418 auto params = AuthorizationSetBuilder()
7419 .BlockMode(BlockMode::CBC)
7420 .Padding(PaddingMode::NONE)
7421 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7422 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7423}
7424
7425/*
Selene Huang31ab4042020-04-29 04:22:39 -07007426 * EncryptionOperationsTest.TripleDesCallerIv
7427 *
7428 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7429 */
7430TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7432 .TripleDesEncryptionKey(168)
7433 .BlockMode(BlockMode::CBC)
7434 .Authorization(TAG_NO_AUTH_REQUIRED)
7435 .Authorization(TAG_CALLER_NONCE)
7436 .Padding(PaddingMode::NONE)));
7437 string message = "1234567890123456";
7438 vector<uint8_t> iv;
7439 // Don't specify IV, should get a random one.
7440 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7441 EXPECT_EQ(message.size(), ciphertext1.size());
7442 EXPECT_EQ(8U, iv.size());
7443
7444 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7445 EXPECT_EQ(message, plaintext);
7446
7447 // Now specify an IV, should also work.
7448 iv = AidlBuf("abcdefgh");
7449 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7450
7451 // Decrypt with correct IV.
7452 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7453 EXPECT_EQ(message, plaintext);
7454
7455 // Now try with wrong IV.
7456 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7457 EXPECT_NE(message, plaintext);
7458}
7459
7460/*
7461 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7462 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007463 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007464 */
7465TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7467 .TripleDesEncryptionKey(168)
7468 .BlockMode(BlockMode::CBC)
7469 .Authorization(TAG_NO_AUTH_REQUIRED)
7470 .Padding(PaddingMode::NONE)));
7471
7472 string message = "12345678901234567890123456789012";
7473 vector<uint8_t> iv;
7474 // Don't specify nonce, should get a random one.
7475 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7476 EXPECT_EQ(message.size(), ciphertext1.size());
7477 EXPECT_EQ(8U, iv.size());
7478
7479 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7480 EXPECT_EQ(message, plaintext);
7481
7482 // Now specify a nonce, should fail.
7483 auto input_params = AuthorizationSetBuilder()
7484 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7485 .BlockMode(BlockMode::CBC)
7486 .Padding(PaddingMode::NONE);
7487 AuthorizationSet output_params;
7488 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7489 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7490}
7491
7492/*
7493 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7494 *
7495 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7496 */
7497TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7499 .TripleDesEncryptionKey(168)
7500 .BlockMode(BlockMode::ECB)
7501 .Authorization(TAG_NO_AUTH_REQUIRED)
7502 .Padding(PaddingMode::NONE)));
7503 // Two-block message.
7504 string message = "1234567890123456";
7505 auto begin_params =
7506 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7507 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7508}
7509
7510/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007511 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007512 *
7513 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7514 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007515TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7516 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007517 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007518 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7519 .TripleDesEncryptionKey(168)
7520 .BlockMode(blockMode)
7521 .Authorization(TAG_NO_AUTH_REQUIRED)
7522 .Padding(PaddingMode::NONE)));
7523 // Message is slightly shorter than two blocks.
7524 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007525
David Drysdaled2cc8c22021-04-15 13:29:45 +01007526 auto begin_params =
7527 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7528 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007529 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007530 string ciphertext;
7531 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7532
7533 CheckedDeleteKey();
7534 }
Selene Huang31ab4042020-04-29 04:22:39 -07007535}
7536
7537/*
7538 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7539 *
7540 * Verifies that PKCS7 padding works correctly in CBC mode.
7541 */
7542TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7544 .TripleDesEncryptionKey(168)
7545 .BlockMode(BlockMode::CBC)
7546 .Authorization(TAG_NO_AUTH_REQUIRED)
7547 .Padding(PaddingMode::PKCS7)));
7548
7549 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007550 for (size_t i = 0; i <= 32; i++) {
7551 SCOPED_TRACE(testing::Message() << "i = " << i);
7552 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7553 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007554 vector<uint8_t> iv;
7555 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7556 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7557 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7558 EXPECT_EQ(message, plaintext);
7559 }
7560}
7561
7562/*
7563 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7564 *
7565 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7566 */
7567TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7569 .TripleDesEncryptionKey(168)
7570 .BlockMode(BlockMode::CBC)
7571 .Authorization(TAG_NO_AUTH_REQUIRED)
7572 .Padding(PaddingMode::NONE)));
7573
7574 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007575 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007576 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007577 auto begin_params =
7578 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7579 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7580 }
7581}
7582
7583/*
7584 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7585 *
7586 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7587 */
7588TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7590 .TripleDesEncryptionKey(168)
7591 .BlockMode(BlockMode::CBC)
7592 .Authorization(TAG_NO_AUTH_REQUIRED)
7593 .Padding(PaddingMode::PKCS7)));
7594
7595 string message = "a";
7596 vector<uint8_t> iv;
7597 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7598 EXPECT_EQ(8U, ciphertext.size());
7599 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007600
7601 auto begin_params = AuthorizationSetBuilder()
7602 .BlockMode(BlockMode::CBC)
7603 .Padding(PaddingMode::PKCS7)
7604 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007605
7606 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007607 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007608 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007609 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007610 string plaintext;
7611 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7612 ErrorCode error = Finish(&plaintext);
7613 if (error == ErrorCode::INVALID_ARGUMENT) {
7614 // This is the expected error, we can exit the test now.
7615 return;
7616 } else {
7617 // Very small chance we got valid decryption, so try again.
7618 ASSERT_EQ(error, ErrorCode::OK);
7619 }
7620 }
7621 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007622}
7623
7624/*
7625 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7626 *
7627 * Verifies that 3DES CBC works with many different input sizes.
7628 */
7629TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7631 .TripleDesEncryptionKey(168)
7632 .BlockMode(BlockMode::CBC)
7633 .Authorization(TAG_NO_AUTH_REQUIRED)
7634 .Padding(PaddingMode::NONE)));
7635
7636 int increment = 7;
7637 string message(240, 'a');
7638 AuthorizationSet input_params =
7639 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7640 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007641 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007642
7643 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007644 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007645 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007646 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7647 EXPECT_EQ(message.size(), ciphertext.size());
7648
7649 // Move TAG_NONCE into input_params
7650 input_params = output_params;
7651 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7652 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7653 output_params.Clear();
7654
David Drysdale7fc26b92022-05-13 09:54:24 +01007655 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007656 string plaintext;
7657 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007658 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007659 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7660 EXPECT_EQ(ciphertext.size(), plaintext.size());
7661 EXPECT_EQ(message, plaintext);
7662}
7663
7664INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7665
7666typedef KeyMintAidlTestBase MaxOperationsTest;
7667
7668/*
7669 * MaxOperationsTest.TestLimitAes
7670 *
7671 * Verifies that the max uses per boot tag works correctly with AES keys.
7672 */
7673TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007674 if (SecLevel() == SecurityLevel::STRONGBOX) {
7675 GTEST_SKIP() << "Test not applicable to StrongBox device";
7676 }
Selene Huang31ab4042020-04-29 04:22:39 -07007677
7678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7679 .Authorization(TAG_NO_AUTH_REQUIRED)
7680 .AesEncryptionKey(128)
7681 .EcbMode()
7682 .Padding(PaddingMode::NONE)
7683 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7684
7685 string message = "1234567890123456";
7686
7687 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7688
7689 EncryptMessage(message, params);
7690 EncryptMessage(message, params);
7691 EncryptMessage(message, params);
7692
7693 // Fourth time should fail.
7694 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7695}
7696
7697/*
Qi Wud22ec842020-11-26 13:27:53 +08007698 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007699 *
7700 * Verifies that the max uses per boot tag works correctly with RSA keys.
7701 */
7702TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007703 if (SecLevel() == SecurityLevel::STRONGBOX) {
7704 GTEST_SKIP() << "Test not applicable to StrongBox device";
7705 }
Selene Huang31ab4042020-04-29 04:22:39 -07007706
7707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7708 .Authorization(TAG_NO_AUTH_REQUIRED)
7709 .RsaSigningKey(1024, 65537)
7710 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007711 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7712 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007713
7714 string message = "1234567890123456";
7715
7716 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7717
7718 SignMessage(message, params);
7719 SignMessage(message, params);
7720 SignMessage(message, params);
7721
7722 // Fourth time should fail.
7723 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7724}
7725
7726INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7727
Qi Wud22ec842020-11-26 13:27:53 +08007728typedef KeyMintAidlTestBase UsageCountLimitTest;
7729
7730/*
Qi Wubeefae42021-01-28 23:16:37 +08007731 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007732 *
Qi Wubeefae42021-01-28 23:16:37 +08007733 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007734 */
Qi Wubeefae42021-01-28 23:16:37 +08007735TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007736 if (SecLevel() == SecurityLevel::STRONGBOX) {
7737 GTEST_SKIP() << "Test not applicable to StrongBox device";
7738 }
Qi Wud22ec842020-11-26 13:27:53 +08007739
7740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7741 .Authorization(TAG_NO_AUTH_REQUIRED)
7742 .AesEncryptionKey(128)
7743 .EcbMode()
7744 .Padding(PaddingMode::NONE)
7745 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7746
7747 // Check the usage count limit tag appears in the authorizations.
7748 AuthorizationSet auths;
7749 for (auto& entry : key_characteristics_) {
7750 auths.push_back(AuthorizationSet(entry.authorizations));
7751 }
7752 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7753 << "key usage count limit " << 1U << " missing";
7754
7755 string message = "1234567890123456";
7756 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7757
Qi Wubeefae42021-01-28 23:16:37 +08007758 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7759 AuthorizationSet keystore_auths =
7760 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7761
Qi Wud22ec842020-11-26 13:27:53 +08007762 // First usage of AES key should work.
7763 EncryptMessage(message, params);
7764
Qi Wud22ec842020-11-26 13:27:53 +08007765 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7766 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7767 // must be invalidated from secure storage (such as RPMB partition).
7768 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7769 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007770 // Usage count limit tag is enforced by keystore, keymint does nothing.
7771 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007772 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007773 }
7774}
7775
7776/*
Qi Wubeefae42021-01-28 23:16:37 +08007777 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007778 *
Qi Wubeefae42021-01-28 23:16:37 +08007779 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007780 */
Qi Wubeefae42021-01-28 23:16:37 +08007781TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007782 if (SecLevel() == SecurityLevel::STRONGBOX) {
7783 GTEST_SKIP() << "Test not applicable to StrongBox device";
7784 }
Qi Wubeefae42021-01-28 23:16:37 +08007785
7786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7787 .Authorization(TAG_NO_AUTH_REQUIRED)
7788 .AesEncryptionKey(128)
7789 .EcbMode()
7790 .Padding(PaddingMode::NONE)
7791 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7792
7793 // Check the usage count limit tag appears in the authorizations.
7794 AuthorizationSet auths;
7795 for (auto& entry : key_characteristics_) {
7796 auths.push_back(AuthorizationSet(entry.authorizations));
7797 }
7798 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7799 << "key usage count limit " << 3U << " missing";
7800
7801 string message = "1234567890123456";
7802 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7803
7804 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7805 AuthorizationSet keystore_auths =
7806 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7807
7808 EncryptMessage(message, params);
7809 EncryptMessage(message, params);
7810 EncryptMessage(message, params);
7811
7812 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7813 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7814 // must be invalidated from secure storage (such as RPMB partition).
7815 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7816 } else {
7817 // Usage count limit tag is enforced by keystore, keymint does nothing.
7818 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007819 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007820 }
7821}
7822
7823/*
7824 * UsageCountLimitTest.TestSingleUseRsa
7825 *
7826 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7827 */
7828TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007829 if (SecLevel() == SecurityLevel::STRONGBOX) {
7830 GTEST_SKIP() << "Test not applicable to StrongBox device";
7831 }
Qi Wud22ec842020-11-26 13:27:53 +08007832
7833 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7834 .Authorization(TAG_NO_AUTH_REQUIRED)
7835 .RsaSigningKey(1024, 65537)
7836 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007837 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7838 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007839
7840 // Check the usage count limit tag appears in the authorizations.
7841 AuthorizationSet auths;
7842 for (auto& entry : key_characteristics_) {
7843 auths.push_back(AuthorizationSet(entry.authorizations));
7844 }
7845 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7846 << "key usage count limit " << 1U << " missing";
7847
7848 string message = "1234567890123456";
7849 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7850
Qi Wubeefae42021-01-28 23:16:37 +08007851 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7852 AuthorizationSet keystore_auths =
7853 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7854
Qi Wud22ec842020-11-26 13:27:53 +08007855 // First usage of RSA key should work.
7856 SignMessage(message, params);
7857
Qi Wud22ec842020-11-26 13:27:53 +08007858 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7859 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7860 // must be invalidated from secure storage (such as RPMB partition).
7861 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7862 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007863 // Usage count limit tag is enforced by keystore, keymint does nothing.
7864 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007865 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007866 }
7867}
7868
7869/*
7870 * UsageCountLimitTest.TestLimitUseRsa
7871 *
7872 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7873 */
7874TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007875 if (SecLevel() == SecurityLevel::STRONGBOX) {
7876 GTEST_SKIP() << "Test not applicable to StrongBox device";
7877 }
Qi Wubeefae42021-01-28 23:16:37 +08007878
7879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7880 .Authorization(TAG_NO_AUTH_REQUIRED)
7881 .RsaSigningKey(1024, 65537)
7882 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007883 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7884 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007885
7886 // Check the usage count limit tag appears in the authorizations.
7887 AuthorizationSet auths;
7888 for (auto& entry : key_characteristics_) {
7889 auths.push_back(AuthorizationSet(entry.authorizations));
7890 }
7891 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7892 << "key usage count limit " << 3U << " missing";
7893
7894 string message = "1234567890123456";
7895 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7896
7897 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7898 AuthorizationSet keystore_auths =
7899 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7900
7901 SignMessage(message, params);
7902 SignMessage(message, params);
7903 SignMessage(message, params);
7904
7905 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7906 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7907 // must be invalidated from secure storage (such as RPMB partition).
7908 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7909 } else {
7910 // Usage count limit tag is enforced by keystore, keymint does nothing.
7911 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007912 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007913 }
7914}
7915
Qi Wu8e727f72021-02-11 02:49:33 +08007916/*
7917 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7918 *
7919 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7920 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7921 * in hardware.
7922 */
7923TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007924 auto error = GenerateKey(AuthorizationSetBuilder()
7925 .RsaSigningKey(2048, 65537)
7926 .Digest(Digest::NONE)
7927 .Padding(PaddingMode::NONE)
7928 .Authorization(TAG_NO_AUTH_REQUIRED)
7929 .Authorization(TAG_ROLLBACK_RESISTANCE)
7930 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007931 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7932 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007933 }
David Drysdale513bf122021-10-06 11:53:13 +01007934
7935 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7936 ASSERT_EQ(ErrorCode::OK, error);
7937 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7938 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7939 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7940
7941 // The KeyMint should also enforce single use key in hardware when it supports rollback
7942 // resistance.
7943 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7944 .Authorization(TAG_NO_AUTH_REQUIRED)
7945 .RsaSigningKey(1024, 65537)
7946 .NoDigestOrPadding()
7947 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7948 .SetDefaultValidity()));
7949
7950 // Check the usage count limit tag appears in the hardware authorizations.
7951 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7952 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7953 << "key usage count limit " << 1U << " missing";
7954
7955 string message = "1234567890123456";
7956 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7957
7958 // First usage of RSA key should work.
7959 SignMessage(message, params);
7960
7961 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7962 // must be invalidated from secure storage (such as RPMB partition).
7963 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007964}
7965
Qi Wud22ec842020-11-26 13:27:53 +08007966INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7967
David Drysdale7de9feb2021-03-05 14:56:19 +00007968typedef KeyMintAidlTestBase GetHardwareInfoTest;
7969
7970TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7971 // Retrieving hardware info should give the same result each time.
7972 KeyMintHardwareInfo info;
7973 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7974 KeyMintHardwareInfo info2;
7975 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7976 EXPECT_EQ(info, info2);
7977}
7978
7979INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7980
Selene Huang31ab4042020-04-29 04:22:39 -07007981typedef KeyMintAidlTestBase AddEntropyTest;
7982
7983/*
7984 * AddEntropyTest.AddEntropy
7985 *
7986 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7987 * is actually added.
7988 */
7989TEST_P(AddEntropyTest, AddEntropy) {
7990 string data = "foo";
7991 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7992}
7993
7994/*
7995 * AddEntropyTest.AddEmptyEntropy
7996 *
7997 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7998 */
7999TEST_P(AddEntropyTest, AddEmptyEntropy) {
8000 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8001}
8002
8003/*
8004 * AddEntropyTest.AddLargeEntropy
8005 *
8006 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8007 */
8008TEST_P(AddEntropyTest, AddLargeEntropy) {
8009 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8010}
8011
David Drysdalebb3d85e2021-04-13 11:15:51 +01008012/*
8013 * AddEntropyTest.AddTooLargeEntropy
8014 *
8015 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8016 */
8017TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8018 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8019 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8020}
8021
Selene Huang31ab4042020-04-29 04:22:39 -07008022INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8023
Selene Huang31ab4042020-04-29 04:22:39 -07008024typedef KeyMintAidlTestBase KeyDeletionTest;
8025
8026/**
8027 * KeyDeletionTest.DeleteKey
8028 *
8029 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8030 * valid key blob.
8031 */
8032TEST_P(KeyDeletionTest, DeleteKey) {
8033 auto error = GenerateKey(AuthorizationSetBuilder()
8034 .RsaSigningKey(2048, 65537)
8035 .Digest(Digest::NONE)
8036 .Padding(PaddingMode::NONE)
8037 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008038 .Authorization(TAG_ROLLBACK_RESISTANCE)
8039 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008040 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8041 GTEST_SKIP() << "Rollback resistance not supported";
8042 }
Selene Huang31ab4042020-04-29 04:22:39 -07008043
8044 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008045 ASSERT_EQ(ErrorCode::OK, error);
8046 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8047 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008048
David Drysdale513bf122021-10-06 11:53:13 +01008049 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008050
David Drysdale513bf122021-10-06 11:53:13 +01008051 string message = "12345678901234567890123456789012";
8052 AuthorizationSet begin_out_params;
8053 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8054 Begin(KeyPurpose::SIGN, key_blob_,
8055 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8056 &begin_out_params));
8057 AbortIfNeeded();
8058 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008059}
8060
8061/**
8062 * KeyDeletionTest.DeleteInvalidKey
8063 *
8064 * This test checks that the HAL excepts invalid key blobs..
8065 */
8066TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8067 // Generate key just to check if rollback protection is implemented
8068 auto error = GenerateKey(AuthorizationSetBuilder()
8069 .RsaSigningKey(2048, 65537)
8070 .Digest(Digest::NONE)
8071 .Padding(PaddingMode::NONE)
8072 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008073 .Authorization(TAG_ROLLBACK_RESISTANCE)
8074 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008075 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8076 GTEST_SKIP() << "Rollback resistance not supported";
8077 }
Selene Huang31ab4042020-04-29 04:22:39 -07008078
8079 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008080 ASSERT_EQ(ErrorCode::OK, error);
8081 AuthorizationSet enforced(SecLevelAuthorizations());
8082 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008083
David Drysdale513bf122021-10-06 11:53:13 +01008084 // Delete the key we don't care about the result at this point.
8085 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008086
David Drysdale513bf122021-10-06 11:53:13 +01008087 // Now create an invalid key blob and delete it.
8088 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008089
David Drysdale513bf122021-10-06 11:53:13 +01008090 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008091}
8092
8093/**
8094 * KeyDeletionTest.DeleteAllKeys
8095 *
8096 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8097 *
8098 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8099 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8100 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8101 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8102 * credentials stored in Keystore/Keymint.
8103 */
8104TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008105 if (!arm_deleteAllKeys) {
8106 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8107 return;
8108 }
Selene Huang31ab4042020-04-29 04:22:39 -07008109 auto error = GenerateKey(AuthorizationSetBuilder()
8110 .RsaSigningKey(2048, 65537)
8111 .Digest(Digest::NONE)
8112 .Padding(PaddingMode::NONE)
8113 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008114 .Authorization(TAG_ROLLBACK_RESISTANCE)
8115 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008116 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8117 GTEST_SKIP() << "Rollback resistance not supported";
8118 }
Selene Huang31ab4042020-04-29 04:22:39 -07008119
8120 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008121 ASSERT_EQ(ErrorCode::OK, error);
8122 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8123 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008124
David Drysdale513bf122021-10-06 11:53:13 +01008125 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008126
David Drysdale513bf122021-10-06 11:53:13 +01008127 string message = "12345678901234567890123456789012";
8128 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008129
David Drysdale513bf122021-10-06 11:53:13 +01008130 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8131 Begin(KeyPurpose::SIGN, key_blob_,
8132 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8133 &begin_out_params));
8134 AbortIfNeeded();
8135 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008136}
8137
8138INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8139
David Drysdaled2cc8c22021-04-15 13:29:45 +01008140typedef KeyMintAidlTestBase KeyUpgradeTest;
8141
8142/**
8143 * KeyUpgradeTest.UpgradeInvalidKey
8144 *
8145 * This test checks that the HAL excepts invalid key blobs..
8146 */
8147TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8148 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8149
8150 std::vector<uint8_t> new_blob;
8151 Status result = keymint_->upgradeKey(key_blob,
8152 AuthorizationSetBuilder()
8153 .Authorization(TAG_APPLICATION_ID, "clientid")
8154 .Authorization(TAG_APPLICATION_DATA, "appdata")
8155 .vector_data(),
8156 &new_blob);
8157 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8158}
8159
8160INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8161
Selene Huang31ab4042020-04-29 04:22:39 -07008162using UpgradeKeyTest = KeyMintAidlTestBase;
8163
8164/*
8165 * UpgradeKeyTest.UpgradeKey
8166 *
8167 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8168 */
8169TEST_P(UpgradeKeyTest, UpgradeKey) {
8170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8171 .AesEncryptionKey(128)
8172 .Padding(PaddingMode::NONE)
8173 .Authorization(TAG_NO_AUTH_REQUIRED)));
8174
8175 auto result = UpgradeKey(key_blob_);
8176
8177 // Key doesn't need upgrading. Should get okay, but no new key blob.
8178 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8179}
8180
8181INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8182
8183using ClearOperationsTest = KeyMintAidlTestBase;
8184
8185/*
8186 * ClearSlotsTest.TooManyOperations
8187 *
8188 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8189 * operations are started without being finished or aborted. Also verifies
8190 * that aborting the operations clears the operations.
8191 *
8192 */
8193TEST_P(ClearOperationsTest, TooManyOperations) {
8194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8195 .Authorization(TAG_NO_AUTH_REQUIRED)
8196 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008197 .Padding(PaddingMode::NONE)
8198 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008199
8200 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8201 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008202 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008203 AuthorizationSet out_params;
8204 ErrorCode result;
8205 size_t i;
8206
8207 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008208 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008209 if (ErrorCode::OK != result) {
8210 break;
8211 }
8212 }
8213 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8214 // Try again just in case there's a weird overflow bug
8215 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008216 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008217 for (size_t j = 0; j < i; j++) {
8218 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8219 << "Aboort failed for i = " << j << std::endl;
8220 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008221 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008222 AbortIfNeeded();
8223}
8224
8225INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8226
8227typedef KeyMintAidlTestBase TransportLimitTest;
8228
8229/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008230 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008231 *
8232 * Verifies that passing input data to finish succeeds as expected.
8233 */
8234TEST_P(TransportLimitTest, LargeFinishInput) {
8235 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8236 .Authorization(TAG_NO_AUTH_REQUIRED)
8237 .AesEncryptionKey(128)
8238 .BlockMode(BlockMode::ECB)
8239 .Padding(PaddingMode::NONE)));
8240
8241 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008242 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008243 auto cipher_params =
8244 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8245
8246 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008247 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008248
8249 string plain_message = std::string(1 << msg_size, 'x');
8250 string encrypted_message;
8251 auto rc = Finish(plain_message, &encrypted_message);
8252
8253 EXPECT_EQ(ErrorCode::OK, rc);
8254 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8255 << "Encrypt finish returned OK, but did not consume all of the given input";
8256 cipher_params.push_back(out_params);
8257
David Drysdale7fc26b92022-05-13 09:54:24 +01008258 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008259
8260 string decrypted_message;
8261 rc = Finish(encrypted_message, &decrypted_message);
8262 EXPECT_EQ(ErrorCode::OK, rc);
8263 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8264 << "Decrypt finish returned OK, did not consume all of the given input";
8265 }
8266}
8267
8268INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8269
Seth Moored79a0ec2021-12-13 20:03:33 +00008270static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008271 switch (curve) {
8272 case EcCurve::P_224:
8273 return NID_secp224r1;
8274 case EcCurve::P_256:
8275 return NID_X9_62_prime256v1;
8276 case EcCurve::P_384:
8277 return NID_secp384r1;
8278 case EcCurve::P_521:
8279 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008280 case EcCurve::CURVE_25519:
8281 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008282 }
8283}
8284
David Drysdale42fe1892021-10-14 14:43:46 +01008285class KeyAgreementTest : public KeyMintAidlTestBase {
8286 protected:
8287 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8288 std::vector<uint8_t>* localPublicKey) {
8289 // Generate EC key locally (with access to private key material)
8290 if (localCurve == EcCurve::CURVE_25519) {
8291 uint8_t privKeyData[32];
8292 uint8_t pubKeyData[32];
8293 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008294 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8295 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8296 } else {
8297 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8298 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8299 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8300 ASSERT_NE(group, nullptr);
8301 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8302 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8303 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8304 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008305 }
David Drysdalea410b772022-05-09 16:44:13 +01008306
8307 // Get encoded form of the public part of the locally generated key...
8308 unsigned char* p = nullptr;
8309 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8310 ASSERT_GT(localPublicKeySize, 0);
8311 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8312 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8313 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008314 }
8315
8316 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8317 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008318 auto builder = AuthorizationSetBuilder()
8319 .Authorization(TAG_NO_AUTH_REQUIRED)
8320 .Authorization(TAG_EC_CURVE, curve)
8321 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8322 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8323 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8324 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8325 .SetDefaultValidity();
8326 ErrorCode result = GenerateKey(builder);
8327
8328 if (SecLevel() == SecurityLevel::STRONGBOX) {
8329 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8330 result = GenerateKeyWithSelfSignedAttestKey(
8331 AuthorizationSetBuilder()
8332 .EcdsaKey(EcCurve::P_256)
8333 .AttestKey()
8334 .SetDefaultValidity(), /* attest key params */
8335 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8336 }
8337 }
David Drysdale42fe1892021-10-14 14:43:46 +01008338 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8339 ASSERT_GT(cert_chain_.size(), 0);
8340 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8341 ASSERT_NE(kmKeyCert, nullptr);
8342 // Check that keyAgreement (bit 4) is set in KeyUsage
8343 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8344 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8345 ASSERT_NE(*kmPubKey, nullptr);
8346 if (dump_Attestations) {
8347 for (size_t n = 0; n < cert_chain_.size(); n++) {
8348 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8349 }
8350 }
8351 }
8352
8353 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8354 const std::vector<uint8_t>& localPublicKey) {
8355 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8356 string ZabFromKeyMintStr;
8357 ASSERT_EQ(ErrorCode::OK,
8358 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8359 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8360 vector<uint8_t> ZabFromTest;
8361
8362 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8363 size_t kmPubKeySize = 32;
8364 uint8_t kmPubKeyData[32];
8365 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8366 ASSERT_EQ(kmPubKeySize, 32);
8367
8368 uint8_t localPrivKeyData[32];
8369 size_t localPrivKeySize = 32;
8370 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8371 &localPrivKeySize));
8372 ASSERT_EQ(localPrivKeySize, 32);
8373
8374 uint8_t sharedKey[32];
8375 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8376 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8377 } else {
8378 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8379 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8380 ASSERT_NE(ctx, nullptr);
8381 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8382 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8383 size_t ZabFromTestLen = 0;
8384 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8385 ZabFromTest.resize(ZabFromTestLen);
8386 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8387 }
8388 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8389 }
8390};
8391
David Zeuthene0c40892021-01-08 12:54:11 -05008392/*
8393 * KeyAgreementTest.Ecdh
8394 *
David Drysdale42fe1892021-10-14 14:43:46 +01008395 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008396 */
8397TEST_P(KeyAgreementTest, Ecdh) {
8398 // Because it's possible to use this API with keys on different curves, we
8399 // check all N^2 combinations where N is the number of supported
8400 // curves.
8401 //
8402 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8403 // lot more curves we can be smart about things and just pick |otherCurve| so
8404 // it's not |curve| and that way we end up with only 2*N runs
8405 //
8406 for (auto curve : ValidCurves()) {
8407 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008408 SCOPED_TRACE(testing::Message()
8409 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8410
David Zeuthene0c40892021-01-08 12:54:11 -05008411 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008412 EVP_PKEY_Ptr localPrivKey;
8413 vector<uint8_t> localPublicKey;
8414 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008415
8416 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008417 EVP_PKEY_Ptr kmPubKey;
8418 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008419
8420 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8421 if (curve != localCurve) {
8422 // If the keys are using different curves KeyMint should fail with
8423 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008424 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008425 string ZabFromKeyMintStr;
8426 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008427 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008428 &ZabFromKeyMintStr));
8429
8430 } else {
8431 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008432 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008433 }
8434
8435 CheckedDeleteKey();
8436 }
8437 }
8438}
8439
David Drysdale42fe1892021-10-14 14:43:46 +01008440/*
8441 * KeyAgreementTest.EcdhCurve25519
8442 *
8443 * Verifies that ECDH works for curve25519. This is also covered by the general
8444 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8445 * KeyMint 1.0.
8446 */
8447TEST_P(KeyAgreementTest, EcdhCurve25519) {
8448 if (!Curve25519Supported()) {
8449 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8450 }
8451
8452 // Generate EC key in KeyMint (only access to public key material)
8453 EcCurve curve = EcCurve::CURVE_25519;
8454 EVP_PKEY_Ptr kmPubKey = nullptr;
8455 GenerateKeyMintEcKey(curve, &kmPubKey);
8456
8457 // Generate EC key on same curve locally (with access to private key material).
8458 EVP_PKEY_Ptr privKey;
8459 vector<uint8_t> encodedPublicKey;
8460 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8461
8462 // Agree on a key between local and KeyMint and check it.
8463 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8464
8465 CheckedDeleteKey();
8466}
8467
8468/*
8469 * KeyAgreementTest.EcdhCurve25519Imported
8470 *
8471 * Verifies that ECDH works for an imported curve25519 key.
8472 */
8473TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8474 if (!Curve25519Supported()) {
8475 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8476 }
8477
8478 // Import x25519 key into KeyMint.
8479 EcCurve curve = EcCurve::CURVE_25519;
8480 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8481 .Authorization(TAG_NO_AUTH_REQUIRED)
8482 .EcdsaKey(EcCurve::CURVE_25519)
8483 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8484 .SetDefaultValidity(),
8485 KeyFormat::PKCS8, x25519_pkcs8_key));
8486 ASSERT_GT(cert_chain_.size(), 0);
8487 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8488 ASSERT_NE(kmKeyCert, nullptr);
8489 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8490 ASSERT_NE(kmPubKey.get(), nullptr);
8491
8492 // Expect the import to emit corresponding public key data.
8493 size_t kmPubKeySize = 32;
8494 uint8_t kmPubKeyData[32];
8495 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8496 ASSERT_EQ(kmPubKeySize, 32);
8497 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8498 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8499
8500 // Generate EC key on same curve locally (with access to private key material).
8501 EVP_PKEY_Ptr privKey;
8502 vector<uint8_t> encodedPublicKey;
8503 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8504
8505 // Agree on a key between local and KeyMint and check it.
8506 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8507
8508 CheckedDeleteKey();
8509}
8510
8511/*
8512 * KeyAgreementTest.EcdhCurve25519InvalidSize
8513 *
8514 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8515 */
8516TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8517 if (!Curve25519Supported()) {
8518 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8519 }
8520
8521 // Generate EC key in KeyMint (only access to public key material)
8522 EcCurve curve = EcCurve::CURVE_25519;
8523 EVP_PKEY_Ptr kmPubKey = nullptr;
8524 GenerateKeyMintEcKey(curve, &kmPubKey);
8525
8526 // Generate EC key on same curve locally (with access to private key material).
8527 EVP_PKEY_Ptr privKey;
8528 vector<uint8_t> encodedPublicKey;
8529 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8530
8531 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8532 string ZabFromKeyMintStr;
8533 // Send in an incomplete public key.
8534 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8535 &ZabFromKeyMintStr));
8536
8537 CheckedDeleteKey();
8538}
8539
8540/*
8541 * KeyAgreementTest.EcdhCurve25519Mismatch
8542 *
8543 * Verifies that ECDH fails between curve25519 and other curves.
8544 */
8545TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8546 if (!Curve25519Supported()) {
8547 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8548 }
8549
8550 // Generate EC key in KeyMint (only access to public key material)
8551 EcCurve curve = EcCurve::CURVE_25519;
8552 EVP_PKEY_Ptr kmPubKey = nullptr;
8553 GenerateKeyMintEcKey(curve, &kmPubKey);
8554
8555 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008556 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008557 if (localCurve == curve) {
8558 continue;
8559 }
8560 // Generate EC key on a different curve locally (with access to private key material).
8561 EVP_PKEY_Ptr privKey;
8562 vector<uint8_t> encodedPublicKey;
8563 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8564
David Drysdale7fc26b92022-05-13 09:54:24 +01008565 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008566 string ZabFromKeyMintStr;
8567 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8568 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8569 &ZabFromKeyMintStr));
8570 }
8571
8572 CheckedDeleteKey();
8573}
8574
David Zeuthene0c40892021-01-08 12:54:11 -05008575INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8576
David Drysdaled2cc8c22021-04-15 13:29:45 +01008577using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8578
8579// This is a problematic test, as it can render the device under test permanently unusable.
8580// Re-enable and run at your own risk.
8581TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8582 auto result = DestroyAttestationIds();
8583 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8584}
8585
8586INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8587
Shawn Willdend659c7c2021-02-19 14:51:51 -07008588using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008589
David Drysdaledb0dcf52021-05-18 11:43:31 +01008590/*
8591 * EarlyBootKeyTest.CreateEarlyBootKeys
8592 *
8593 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8594 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008595TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008596 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008597 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8598 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008599 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8600 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8601 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8602 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008603
David Drysdaleadfe6112021-05-27 12:00:53 +01008604 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8605 ASSERT_GT(keyData.blob.size(), 0U);
8606 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8607 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8608 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008609}
8610
David Drysdaledb0dcf52021-05-18 11:43:31 +01008611/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008612 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8613 *
8614 * Verifies that creating an early boot key with attestation succeeds.
8615 */
8616TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8617 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8618 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8619 builder->AttestationChallenge("challenge");
8620 builder->AttestationApplicationId("app_id");
8621 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008622 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8623 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8624 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8625 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008626
8627 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008628 // Strongbox may not support factory attestation. Key creation might fail with
8629 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8630 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8631 continue;
8632 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008633 ASSERT_GT(keyData.blob.size(), 0U);
8634 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8635 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8636 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008637}
8638
8639/*
8640 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008641 *
8642 * Verifies that using early boot keys at a later stage fails.
8643 */
8644TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8646 .Authorization(TAG_NO_AUTH_REQUIRED)
8647 .Authorization(TAG_EARLY_BOOT_ONLY)
8648 .HmacKey(128)
8649 .Digest(Digest::SHA_2_256)
8650 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8651 AuthorizationSet output_params;
8652 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8653 AuthorizationSetBuilder()
8654 .Digest(Digest::SHA_2_256)
8655 .Authorization(TAG_MAC_LENGTH, 256),
8656 &output_params));
8657}
8658
8659/*
8660 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8661 *
8662 * Verifies that importing early boot keys fails.
8663 */
8664TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8665 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8666 .Authorization(TAG_NO_AUTH_REQUIRED)
8667 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008668 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008669 .Digest(Digest::SHA_2_256)
8670 .SetDefaultValidity(),
8671 KeyFormat::PKCS8, ec_256_key));
8672}
8673
David Drysdaled2cc8c22021-04-15 13:29:45 +01008674// 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 +00008675// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8676// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8677// early boot, so you'll have to reboot between runs.
8678TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8679 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8680 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008681 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8682 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8683 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8684 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8685
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008686 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8687 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8688 EXPECT_TRUE(
8689 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8690 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8691 EXPECT_TRUE(
8692 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8693
8694 // Should be able to use keys, since early boot has not ended
8695 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8696 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8697 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8698 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8699
8700 // End early boot
8701 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8702 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8703
8704 // Should not be able to use already-created keys.
8705 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8706 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8707 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8708 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8709
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008710 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008711 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008712 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008713 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8714 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8715 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8716 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008717}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008718
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008719INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8720
Shawn Willdend659c7c2021-02-19 14:51:51 -07008721using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008722
8723// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8724// between runs... and on most test devices there are no enrolled credentials so it can't be
8725// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8726// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8727// a manual test process, which includes unlocking between runs, which is why it's included here.
8728// Well, that and the fact that it's the only test we can do without also making calls into the
8729// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8730// implications might be, so that may or may not be a solution.
8731TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8732 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8733 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008734 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8735 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8736 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8737 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008738
8739 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8740 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8741 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8742 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8743
8744 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008745 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008746 ASSERT_EQ(ErrorCode::OK, rc);
8747 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8748 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8749 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8750 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008751}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008752
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008753INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8754
Shawn Willden22fb9c12022-06-02 14:04:33 -06008755using VsrRequirementTest = KeyMintAidlTestBase;
8756
8757TEST_P(VsrRequirementTest, Vsr13Test) {
8758 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008759 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008760 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8761 }
8762 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8763}
8764
Eran Messerib9346f52022-12-15 14:58:34 +00008765TEST_P(VsrRequirementTest, Vsr14Test) {
8766 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008767 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008768 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8769 }
8770 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8771}
8772
Shawn Willden22fb9c12022-06-02 14:04:33 -06008773INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8774
Janis Danisevskis24c04702020-12-16 18:28:39 -08008775} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008776
8777int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008778 std::cout << "Testing ";
8779 auto halInstances =
8780 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8781 std::cout << "HAL instances:\n";
8782 for (auto& entry : halInstances) {
8783 std::cout << " " << entry << '\n';
8784 }
8785
Selene Huang31ab4042020-04-29 04:22:39 -07008786 ::testing::InitGoogleTest(&argc, argv);
8787 for (int i = 1; i < argc; ++i) {
8788 if (argv[i][0] == '-') {
8789 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008790 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8791 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008792 }
8793 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008794 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8795 dump_Attestations = true;
8796 } else {
8797 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008798 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008799 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8800 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8801 // be run in emulated environments that don't have the normal bootloader
8802 // interactions.
8803 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8804 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008805 if (std::string(argv[i]) == "--keyblob_dir") {
8806 if (i + 1 >= argc) {
8807 std::cerr << "Missing argument for --keyblob_dir\n";
8808 return 1;
8809 }
8810 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8811 std::string(argv[i + 1]);
8812 ++i;
8813 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008814 if (std::string(argv[i]) == "--expect_upgrade") {
8815 if (i + 1 >= argc) {
8816 std::cerr << "Missing argument for --expect_upgrade\n";
8817 return 1;
8818 }
8819 std::string arg = argv[i + 1];
8820 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8821 expect_upgrade =
8822 arg == "yes"
8823 ? true
8824 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
8825 ++i;
8826 }
Selene Huang31ab4042020-04-29 04:22:39 -07008827 }
8828 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008829 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008830}