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