blob: a2e20dcce5151a04534d8f61a969c4f83030c5c5 [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) {
2085 auto challenge = "hello";
2086 auto app_id = "foo";
2087 auto subject = "cert subj 2";
2088 vector<uint8_t> subject_der(make_name_from_str(subject));
2089 uint64_t serial_int = 0x1010;
2090 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2091 const AuthorizationSetBuilder base_builder =
2092 AuthorizationSetBuilder()
2093 .Authorization(TAG_NO_AUTH_REQUIRED)
2094 .EcdsaSigningKey(EcCurve::P_256)
2095 .Digest(Digest::NONE)
2096 .AttestationChallenge(challenge)
2097 .AttestationApplicationId(app_id)
2098 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2099 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2100 .SetDefaultValidity();
2101
2102 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2103 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil24f75792023-09-07 15:25:14 +00002104 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
2105 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
2106 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
2107 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
2108 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
Tri Vo799e4352022-11-07 17:23:50 -08002109 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002110
2111 for (const KeyParameter& tag : extra_tags) {
2112 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2113 vector<uint8_t> key_blob;
2114 vector<KeyCharacteristics> key_characteristics;
2115 AuthorizationSetBuilder builder = base_builder;
2116 builder.push_back(tag);
2117 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002118 // Strongbox may not support factory provisioned attestation key.
2119 if (SecLevel() == SecurityLevel::STRONGBOX) {
2120 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2121 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002122 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2123 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002124 continue;
2125 }
2126 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002127 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002128 ASSERT_GT(key_blob.size(), 0U);
2129
2130 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2131 ASSERT_GT(cert_chain_.size(), 0);
2132 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2133
2134 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2135 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2136
2137 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2138 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2139 // attestation extension should contain them, so make sure the extra tag is added.
2140 hw_enforced.push_back(tag);
2141
2142 // Verifying the attestation record will check for the specific tag because
2143 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002144 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2145 hw_enforced, SecLevel(),
2146 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002147 }
2148}
2149
2150/*
David Drysdale565ccc72021-10-11 12:49:50 +01002151 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2152 *
2153 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2154 */
2155TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2156 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002157 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002158 auto challenge = "hello";
2159 auto subject = "cert subj 2";
2160 vector<uint8_t> subject_der(make_name_from_str(subject));
2161 uint64_t serial_int = 0x1010;
2162 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002163 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002164 AuthorizationSetBuilder()
2165 .Authorization(TAG_NO_AUTH_REQUIRED)
2166 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2167 .EcdsaSigningKey(EcCurve::P_256)
2168 .Digest(Digest::NONE)
2169 .AttestationChallenge(challenge)
2170 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2171 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2172 .AttestationApplicationId(app_id)
2173 .Authorization(TAG_CREATION_DATETIME, datetime)
2174 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002175 if (reset) {
2176 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2177 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002178 auto result = GenerateKey(builder);
2179 if (SecLevel() == SecurityLevel::STRONGBOX) {
2180 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2181 result = GenerateKeyWithSelfSignedAttestKey(
2182 AuthorizationSetBuilder()
2183 .EcdsaKey(EcCurve::P_256)
2184 .AttestKey()
2185 .SetDefaultValidity(), /* attest key params */
2186 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2187 }
2188 }
2189 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002190 ASSERT_GT(key_blob_.size(), 0U);
2191
2192 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2193 ASSERT_GT(cert_chain_.size(), 0);
2194 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2195
2196 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2197 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2198
2199 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002200 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2201 hw_enforced, SecLevel(),
2202 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002203 EXPECT_GT(unique_id->size(), 0);
2204 CheckedDeleteKey();
2205 };
2206
2207 // Generate unique ID
2208 auto app_id = "foo";
2209 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2210 vector<uint8_t> unique_id;
2211 get_unique_id(app_id, cert_date, &unique_id);
2212
2213 // Generating a new key with the same parameters should give the same unique ID.
2214 vector<uint8_t> unique_id2;
2215 get_unique_id(app_id, cert_date, &unique_id2);
2216 EXPECT_EQ(unique_id, unique_id2);
2217
2218 // Generating a new key with a slightly different date should give the same unique ID.
2219 uint64_t rounded_date = cert_date / 2592000000LLU;
2220 uint64_t min_date = rounded_date * 2592000000LLU;
2221 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2222
2223 vector<uint8_t> unique_id3;
2224 get_unique_id(app_id, min_date, &unique_id3);
2225 EXPECT_EQ(unique_id, unique_id3);
2226
2227 vector<uint8_t> unique_id4;
2228 get_unique_id(app_id, max_date, &unique_id4);
2229 EXPECT_EQ(unique_id, unique_id4);
2230
2231 // A different attestation application ID should yield a different unique ID.
2232 auto app_id2 = "different_foo";
2233 vector<uint8_t> unique_id5;
2234 get_unique_id(app_id2, cert_date, &unique_id5);
2235 EXPECT_NE(unique_id, unique_id5);
2236
2237 // A radically different date should yield a different unique ID.
2238 vector<uint8_t> unique_id6;
2239 get_unique_id(app_id, 1611621648000, &unique_id6);
2240 EXPECT_NE(unique_id, unique_id6);
2241
2242 vector<uint8_t> unique_id7;
2243 get_unique_id(app_id, max_date + 1, &unique_id7);
2244 EXPECT_NE(unique_id, unique_id7);
2245
2246 vector<uint8_t> unique_id8;
2247 get_unique_id(app_id, min_date - 1, &unique_id8);
2248 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002249
2250 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2251 vector<uint8_t> unique_id9;
2252 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2253 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002254}
2255
2256/*
David Drysdale37af4b32021-05-14 16:46:59 +01002257 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2258 *
2259 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2260 */
2261TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2262 auto challenge = "hello";
2263 auto attest_app_id = "foo";
2264 auto subject = "cert subj 2";
2265 vector<uint8_t> subject_der(make_name_from_str(subject));
2266 uint64_t serial_int = 0x1010;
2267 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2268
2269 // Earlier versions of the attestation extension schema included a slot:
2270 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2271 // This should never have been included, and should never be filled in.
2272 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2273 // to confirm that this field never makes it into the attestation extension.
2274 vector<uint8_t> key_blob;
2275 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002276 auto builder = AuthorizationSetBuilder()
2277 .Authorization(TAG_NO_AUTH_REQUIRED)
2278 .EcdsaSigningKey(EcCurve::P_256)
2279 .Digest(Digest::NONE)
2280 .AttestationChallenge(challenge)
2281 .AttestationApplicationId(attest_app_id)
2282 .Authorization(TAG_APPLICATION_ID, "client_id")
2283 .Authorization(TAG_APPLICATION_DATA, "appdata")
2284 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2285 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2286 .SetDefaultValidity();
2287
2288 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002289 // Strongbox may not support factory provisioned attestation key.
2290 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002291 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2292 result = GenerateKeyWithSelfSignedAttestKey(
2293 AuthorizationSetBuilder()
2294 .EcdsaKey(EcCurve::P_256)
2295 .AttestKey()
2296 .SetDefaultValidity(), /* attest key params */
2297 builder, &key_blob, &key_characteristics);
2298 }
subrahmanyaman05642492022-02-05 07:10:56 +00002299 }
David Drysdale37af4b32021-05-14 16:46:59 +01002300 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002301 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002302 ASSERT_GT(key_blob.size(), 0U);
2303
2304 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2305 ASSERT_GT(cert_chain_.size(), 0);
2306 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2307
2308 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2309 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002310 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2311 hw_enforced, SecLevel(),
2312 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002313
2314 // Check that the app id is not in the cert.
2315 string app_id = "clientid";
2316 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2317 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2318 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2319 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2320 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002321}
2322
2323/*
Selene Huang4f64c222021-04-13 19:54:36 -07002324 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2325 *
2326 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2327 * the key will generate a self signed attestation.
2328 */
2329TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002330 auto subject = "cert subj 2";
2331 vector<uint8_t> subject_der(make_name_from_str(subject));
2332
2333 uint64_t serial_int = 0x123456FFF1234;
2334 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2335
David Drysdaledf09e542021-06-08 15:46:11 +01002336 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002337 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002338 vector<uint8_t> key_blob;
2339 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002340 ASSERT_EQ(ErrorCode::OK,
2341 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002342 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002343 .Digest(Digest::NONE)
2344 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2345 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2346 .SetDefaultValidity(),
2347 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002348 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002349 ASSERT_GT(key_blob.size(), 0U);
2350 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002351 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002352
2353 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2354
2355 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002356 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002357
2358 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2359 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002360 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002361
2362 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2363 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002364 }
2365}
2366
2367/*
2368 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2369 *
2370 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2371 * app id must also be provided or else it will fail.
2372 */
2373TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2374 auto challenge = "hello";
2375 vector<uint8_t> key_blob;
2376 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002377 auto builder = AuthorizationSetBuilder()
2378 .EcdsaSigningKey(EcCurve::P_256)
2379 .Digest(Digest::NONE)
2380 .AttestationChallenge(challenge)
2381 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002382
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002383 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002384 // Strongbox may not support factory provisioned attestation key.
2385 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002386 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2387 result = GenerateKeyWithSelfSignedAttestKey(
2388 AuthorizationSetBuilder()
2389 .EcdsaKey(EcCurve::P_256)
2390 .AttestKey()
2391 .SetDefaultValidity(), /* attest key params */
2392 builder, &key_blob, &key_characteristics);
2393 }
subrahmanyaman05642492022-02-05 07:10:56 +00002394 }
2395 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002396}
2397
2398/*
2399 * NewKeyGenerationTest.EcdsaIgnoreAppId
2400 *
2401 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2402 * any appid will be ignored, and keymint will generate a self sign certificate.
2403 */
2404TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2405 auto app_id = "foo";
2406
David Drysdaledf09e542021-06-08 15:46:11 +01002407 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002408 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002409 vector<uint8_t> key_blob;
2410 vector<KeyCharacteristics> key_characteristics;
2411 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002412 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002413 .Digest(Digest::NONE)
2414 .AttestationApplicationId(app_id)
2415 .SetDefaultValidity(),
2416 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002417 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002418
2419 ASSERT_GT(key_blob.size(), 0U);
2420 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002421 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002422
2423 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2424
2425 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002426 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002427
2428 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2429 ASSERT_EQ(cert_chain_.size(), 1);
2430
2431 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2432 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002433 }
2434}
2435
2436/*
2437 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2438 *
2439 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2440 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2441 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2442 * to specify how many following bytes will be used to encode the length.
2443 */
2444TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2445 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002446 std::vector<uint32_t> app_id_lengths{143, 258};
2447
2448 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002449 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002450 const string app_id(length, 'a');
2451 vector<uint8_t> key_blob;
2452 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002453 auto builder = AuthorizationSetBuilder()
2454 .Authorization(TAG_NO_AUTH_REQUIRED)
2455 .EcdsaSigningKey(EcCurve::P_256)
2456 .Digest(Digest::NONE)
2457 .AttestationChallenge(challenge)
2458 .AttestationApplicationId(app_id)
2459 .SetDefaultValidity();
2460
2461 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002462 // Strongbox may not support factory provisioned attestation key.
2463 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002464 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2465 result = GenerateKeyWithSelfSignedAttestKey(
2466 AuthorizationSetBuilder()
2467 .EcdsaKey(EcCurve::P_256)
2468 .AttestKey()
2469 .SetDefaultValidity(), /* attest key params */
2470 builder, &key_blob, &key_characteristics);
2471 }
subrahmanyaman05642492022-02-05 07:10:56 +00002472 }
2473 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002474 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002475 ASSERT_GT(key_blob.size(), 0U);
2476 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002477 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002478
2479 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2480
2481 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002482 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002483
2484 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2485 ASSERT_GT(cert_chain_.size(), 0);
2486
2487 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2488 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002489 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002490 sw_enforced, hw_enforced, SecLevel(),
2491 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002492 }
2493}
2494
2495/*
Qi Wud22ec842020-11-26 13:27:53 +08002496 * NewKeyGenerationTest.LimitedUsageEcdsa
2497 *
2498 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2499 * resulting keys have correct characteristics.
2500 */
2501TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002502 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002503 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002504 vector<uint8_t> key_blob;
2505 vector<KeyCharacteristics> key_characteristics;
2506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002507 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002508 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002509 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2510 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002511 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002512 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002513
2514 ASSERT_GT(key_blob.size(), 0U);
2515 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002516 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002517
2518 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2519
2520 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002521 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002522
2523 // Check the usage count limit tag appears in the authorizations.
2524 AuthorizationSet auths;
2525 for (auto& entry : key_characteristics) {
2526 auths.push_back(AuthorizationSet(entry.authorizations));
2527 }
2528 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2529 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002530 }
2531}
2532
2533/*
Selene Huang31ab4042020-04-29 04:22:39 -07002534 * NewKeyGenerationTest.EcdsaDefaultSize
2535 *
David Drysdaledf09e542021-06-08 15:46:11 +01002536 * Verifies that failing to specify a curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002537 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002538 */
2539TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
David Drysdale84b685a2023-08-09 07:00:34 +01002540 auto result = GenerateKey(AuthorizationSetBuilder()
2541 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2542 .SigningKey()
2543 .Digest(Digest::NONE)
2544 .SetDefaultValidity());
2545 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2546 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2547 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002548}
2549
2550/*
David Drysdale42fe1892021-10-14 14:43:46 +01002551 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002552 *
David Drysdale42fe1892021-10-14 14:43:46 +01002553 * Verifies that specifying an invalid curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002554 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002555 */
David Drysdale42fe1892021-10-14 14:43:46 +01002556TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002557 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002558 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002559 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002560 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002561 auto result = GenerateKey(AuthorizationSetBuilder()
2562 .EcdsaSigningKey(curve)
2563 .Digest(Digest::NONE)
2564 .SetDefaultValidity(),
2565 &key_blob, &key_characteristics);
2566 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale84b685a2023-08-09 07:00:34 +01002567 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2568 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002569 }
2570
David Drysdaledf09e542021-06-08 15:46:11 +01002571 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2572 GenerateKey(AuthorizationSetBuilder()
2573 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2574 .Authorization(TAG_KEY_SIZE, 190)
2575 .SigningKey()
2576 .Digest(Digest::NONE)
2577 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002578}
2579
2580/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002581 * NewKeyGenerationTest.EcdsaMissingCurve
2582 *
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002583 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002584 */
2585TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002586 if (AidlVersion() < 3) {
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002587 /*
2588 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2589 * However, this was not checked at the time so we can only be strict about checking this
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002590 * for implementations of KeyMint version 3 and above.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002591 */
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002592 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002593 }
2594 /* If EC_CURVE not provided, generateKey
2595 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2596 */
2597 auto result = GenerateKey(
2598 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2599 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2600 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2601}
2602
2603/*
Selene Huang31ab4042020-04-29 04:22:39 -07002604 * NewKeyGenerationTest.EcdsaMismatchKeySize
2605 *
2606 * Verifies that specifying mismatched key size and curve for EC key generation returns
2607 * INVALID_ARGUMENT.
2608 */
2609TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002610 if (SecLevel() == SecurityLevel::STRONGBOX) {
2611 GTEST_SKIP() << "Test not applicable to StrongBox device";
2612 }
Selene Huang31ab4042020-04-29 04:22:39 -07002613
David Drysdaledf09e542021-06-08 15:46:11 +01002614 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002615 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002616 .Authorization(TAG_KEY_SIZE, 224)
2617 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002618 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002619 .Digest(Digest::NONE)
2620 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002621 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002622}
2623
2624/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002625 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002626 *
2627 * Verifies that keymint does not support any curve designated as unsupported.
2628 */
2629TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2630 Digest digest;
2631 if (SecLevel() == SecurityLevel::STRONGBOX) {
2632 digest = Digest::SHA_2_256;
2633 } else {
2634 digest = Digest::SHA_2_512;
2635 }
2636 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002637 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002638 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2639 .EcdsaSigningKey(curve)
2640 .Digest(digest)
2641 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002642 << "Failed to generate key on curve: " << curve;
2643 CheckedDeleteKey();
2644 }
2645}
2646
2647/*
2648 * NewKeyGenerationTest.Hmac
2649 *
2650 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2651 * characteristics.
2652 */
2653TEST_P(NewKeyGenerationTest, Hmac) {
2654 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002655 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002656 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002657 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002658 constexpr size_t key_size = 128;
2659 ASSERT_EQ(ErrorCode::OK,
2660 GenerateKey(
2661 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2662 TAG_MIN_MAC_LENGTH, 128),
2663 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002664 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002665
2666 ASSERT_GT(key_blob.size(), 0U);
2667 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002668 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002669
Shawn Willden7f424372021-01-10 18:06:50 -07002670 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2671 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2672 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2673 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002674 }
2675}
2676
2677/*
Selene Huang4f64c222021-04-13 19:54:36 -07002678 * NewKeyGenerationTest.HmacNoAttestation
2679 *
2680 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2681 * and app id are provided.
2682 */
2683TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2684 auto challenge = "hello";
2685 auto app_id = "foo";
2686
2687 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002688 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002689 vector<uint8_t> key_blob;
2690 vector<KeyCharacteristics> key_characteristics;
2691 constexpr size_t key_size = 128;
2692 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2693 .HmacKey(key_size)
2694 .Digest(digest)
2695 .AttestationChallenge(challenge)
2696 .AttestationApplicationId(app_id)
2697 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2698 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002699 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002700
2701 ASSERT_GT(key_blob.size(), 0U);
2702 ASSERT_EQ(cert_chain_.size(), 0);
2703 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002704 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002705
2706 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2707 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2708 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2709 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002710 }
2711}
2712
2713/*
Qi Wud22ec842020-11-26 13:27:53 +08002714 * NewKeyGenerationTest.LimitedUsageHmac
2715 *
2716 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2717 * resulting keys have correct characteristics.
2718 */
2719TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2720 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002721 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002722 vector<uint8_t> key_blob;
2723 vector<KeyCharacteristics> key_characteristics;
2724 constexpr size_t key_size = 128;
2725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2726 .HmacKey(key_size)
2727 .Digest(digest)
2728 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2729 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2730 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002731 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002732
2733 ASSERT_GT(key_blob.size(), 0U);
2734 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002735 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002736
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";
2741
2742 // Check the usage count limit tag appears in the authorizations.
2743 AuthorizationSet auths;
2744 for (auto& entry : key_characteristics) {
2745 auths.push_back(AuthorizationSet(entry.authorizations));
2746 }
2747 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2748 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002749 }
2750}
2751
2752/*
Selene Huang31ab4042020-04-29 04:22:39 -07002753 * NewKeyGenerationTest.HmacCheckKeySizes
2754 *
2755 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2756 */
2757TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2758 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002759 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002760 if (key_size < 64 || key_size % 8 != 0) {
2761 // To keep this test from being very slow, we only test a random fraction of
2762 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2763 // them, we expect to run ~40 of them in each run.
2764 if (key_size % 8 == 0 || random() % 10 == 0) {
2765 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2766 GenerateKey(AuthorizationSetBuilder()
2767 .HmacKey(key_size)
2768 .Digest(Digest::SHA_2_256)
2769 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2770 << "HMAC key size " << key_size << " invalid";
2771 }
2772 } else {
2773 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2774 .HmacKey(key_size)
2775 .Digest(Digest::SHA_2_256)
2776 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2777 << "Failed to generate HMAC key of size " << key_size;
2778 CheckedDeleteKey();
2779 }
2780 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002781 if (SecLevel() == SecurityLevel::STRONGBOX) {
2782 // STRONGBOX devices must not support keys larger than 512 bits.
2783 size_t key_size = 520;
2784 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2785 GenerateKey(AuthorizationSetBuilder()
2786 .HmacKey(key_size)
2787 .Digest(Digest::SHA_2_256)
2788 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2789 << "HMAC key size " << key_size << " unexpectedly valid";
2790 }
Selene Huang31ab4042020-04-29 04:22:39 -07002791}
2792
2793/*
2794 * NewKeyGenerationTest.HmacCheckMinMacLengths
2795 *
2796 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2797 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2798 * specific MAC length that failed, so reproducing a failed run will be easy.
2799 */
2800TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2801 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002802 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002803 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2804 // To keep this test from being very long, we only test a random fraction of
2805 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2806 // we expect to run ~17 of them in each run.
2807 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2808 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2809 GenerateKey(AuthorizationSetBuilder()
2810 .HmacKey(128)
2811 .Digest(Digest::SHA_2_256)
2812 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2813 << "HMAC min mac length " << min_mac_length << " invalid.";
2814 }
2815 } else {
2816 EXPECT_EQ(ErrorCode::OK,
2817 GenerateKey(AuthorizationSetBuilder()
2818 .HmacKey(128)
2819 .Digest(Digest::SHA_2_256)
2820 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2821 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2822 CheckedDeleteKey();
2823 }
2824 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002825
2826 // Minimum MAC length must be no more than 512 bits.
2827 size_t min_mac_length = 520;
2828 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2829 GenerateKey(AuthorizationSetBuilder()
2830 .HmacKey(128)
2831 .Digest(Digest::SHA_2_256)
2832 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2833 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002834}
2835
2836/*
2837 * NewKeyGenerationTest.HmacMultipleDigests
2838 *
2839 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2840 */
2841TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002842 if (SecLevel() == SecurityLevel::STRONGBOX) {
2843 GTEST_SKIP() << "Test not applicable to StrongBox device";
2844 }
Selene Huang31ab4042020-04-29 04:22:39 -07002845
2846 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2847 GenerateKey(AuthorizationSetBuilder()
2848 .HmacKey(128)
2849 .Digest(Digest::SHA1)
2850 .Digest(Digest::SHA_2_256)
2851 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2852}
2853
2854/*
2855 * NewKeyGenerationTest.HmacDigestNone
2856 *
2857 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2858 */
2859TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2860 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2861 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2862 128)));
2863
2864 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2865 GenerateKey(AuthorizationSetBuilder()
2866 .HmacKey(128)
2867 .Digest(Digest::NONE)
2868 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2869}
2870
Selene Huang4f64c222021-04-13 19:54:36 -07002871/*
2872 * NewKeyGenerationTest.AesNoAttestation
2873 *
2874 * Verifies that attestation parameters to AES keys are ignored and generateKey
2875 * will succeed.
2876 */
2877TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2878 auto challenge = "hello";
2879 auto app_id = "foo";
2880
2881 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2882 .Authorization(TAG_NO_AUTH_REQUIRED)
2883 .AesEncryptionKey(128)
2884 .EcbMode()
2885 .Padding(PaddingMode::PKCS7)
2886 .AttestationChallenge(challenge)
2887 .AttestationApplicationId(app_id)));
2888
2889 ASSERT_EQ(cert_chain_.size(), 0);
2890}
2891
2892/*
2893 * NewKeyGenerationTest.TripleDesNoAttestation
2894 *
2895 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2896 * will be successful. No attestation should be generated.
2897 */
2898TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2899 auto challenge = "hello";
2900 auto app_id = "foo";
2901
2902 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2903 .TripleDesEncryptionKey(168)
2904 .BlockMode(BlockMode::ECB)
2905 .Authorization(TAG_NO_AUTH_REQUIRED)
2906 .Padding(PaddingMode::NONE)
2907 .AttestationChallenge(challenge)
2908 .AttestationApplicationId(app_id)));
2909 ASSERT_EQ(cert_chain_.size(), 0);
2910}
2911
Selene Huang31ab4042020-04-29 04:22:39 -07002912INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2913
2914typedef KeyMintAidlTestBase SigningOperationsTest;
2915
2916/*
2917 * SigningOperationsTest.RsaSuccess
2918 *
2919 * Verifies that raw RSA signature operations succeed.
2920 */
2921TEST_P(SigningOperationsTest, RsaSuccess) {
2922 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2923 .RsaSigningKey(2048, 65537)
2924 .Digest(Digest::NONE)
2925 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002926 .Authorization(TAG_NO_AUTH_REQUIRED)
2927 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002928 string message = "12345678901234567890123456789012";
2929 string signature = SignMessage(
2930 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002931 LocalVerifyMessage(message, signature,
2932 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2933}
2934
2935/*
2936 * SigningOperationsTest.RsaAllPaddingsAndDigests
2937 *
2938 * Verifies RSA signature/verification for all padding modes and digests.
2939 */
2940TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2941 auto authorizations = AuthorizationSetBuilder()
2942 .Authorization(TAG_NO_AUTH_REQUIRED)
2943 .RsaSigningKey(2048, 65537)
2944 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2945 .Padding(PaddingMode::NONE)
2946 .Padding(PaddingMode::RSA_PSS)
2947 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2948 .SetDefaultValidity();
2949
2950 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2951
2952 string message(128, 'a');
2953 string corrupt_message(message);
2954 ++corrupt_message[corrupt_message.size() / 2];
2955
2956 for (auto padding :
2957 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2958 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002959 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002960 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2961 // Digesting only makes sense with padding.
2962 continue;
2963 }
2964
2965 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2966 // PSS requires digesting.
2967 continue;
2968 }
2969
2970 string signature =
2971 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2972 LocalVerifyMessage(message, signature,
2973 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2974 }
2975 }
Selene Huang31ab4042020-04-29 04:22:39 -07002976}
2977
2978/*
2979 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2980 *
Shawn Willden7f424372021-01-10 18:06:50 -07002981 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002982 */
2983TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2985 .Authorization(TAG_NO_AUTH_REQUIRED)
2986 .RsaSigningKey(2048, 65537)
2987 .Digest(Digest::NONE)
2988 .Padding(PaddingMode::NONE)
2989 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002990 .Authorization(TAG_APPLICATION_DATA, "appdata")
2991 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002992
2993 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2994
Selene Huang31ab4042020-04-29 04:22:39 -07002995 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2996 Begin(KeyPurpose::SIGN,
2997 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2998 AbortIfNeeded();
2999 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3000 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3001 .Digest(Digest::NONE)
3002 .Padding(PaddingMode::NONE)
3003 .Authorization(TAG_APPLICATION_ID, "clientid")));
3004 AbortIfNeeded();
3005 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3006 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3007 .Digest(Digest::NONE)
3008 .Padding(PaddingMode::NONE)
3009 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3010 AbortIfNeeded();
3011 EXPECT_EQ(ErrorCode::OK,
3012 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3013 .Digest(Digest::NONE)
3014 .Padding(PaddingMode::NONE)
3015 .Authorization(TAG_APPLICATION_DATA, "appdata")
3016 .Authorization(TAG_APPLICATION_ID, "clientid")));
3017 AbortIfNeeded();
3018}
3019
3020/*
3021 * SigningOperationsTest.RsaPssSha256Success
3022 *
3023 * Verifies that RSA-PSS signature operations succeed.
3024 */
3025TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3026 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3027 .RsaSigningKey(2048, 65537)
3028 .Digest(Digest::SHA_2_256)
3029 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003030 .Authorization(TAG_NO_AUTH_REQUIRED)
3031 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003032 // Use large message, which won't work without digesting.
3033 string message(1024, 'a');
3034 string signature = SignMessage(
3035 message,
3036 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3037}
3038
3039/*
3040 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3041 *
3042 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3043 * supports only unpadded operations.
3044 */
3045TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3046 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3047 .RsaSigningKey(2048, 65537)
3048 .Digest(Digest::NONE)
3049 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003050 .Padding(PaddingMode::NONE)
3051 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003052 string message = "12345678901234567890123456789012";
3053 string signature;
3054
3055 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3056 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3057 .Digest(Digest::NONE)
3058 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3059}
3060
3061/*
3062 * SigningOperationsTest.NoUserConfirmation
3063 *
3064 * Verifies that keymint rejects signing operations for keys with
3065 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3066 * presented.
3067 */
3068TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003069 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003070 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003071 .Digest(Digest::NONE)
3072 .Padding(PaddingMode::NONE)
3073 .Authorization(TAG_NO_AUTH_REQUIRED)
3074 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3075 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003076
3077 const string message = "12345678901234567890123456789012";
3078 EXPECT_EQ(ErrorCode::OK,
3079 Begin(KeyPurpose::SIGN,
3080 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3081 string signature;
3082 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3083}
3084
3085/*
3086 * SigningOperationsTest.RsaPkcs1Sha256Success
3087 *
3088 * Verifies that digested RSA-PKCS1 signature operations succeed.
3089 */
3090TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3092 .RsaSigningKey(2048, 65537)
3093 .Digest(Digest::SHA_2_256)
3094 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003095 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3096 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003097 string message(1024, 'a');
3098 string signature = SignMessage(message, AuthorizationSetBuilder()
3099 .Digest(Digest::SHA_2_256)
3100 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3101}
3102
3103/*
3104 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3105 *
3106 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3107 */
3108TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3110 .RsaSigningKey(2048, 65537)
3111 .Digest(Digest::NONE)
3112 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003113 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3114 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003115 string message(53, 'a');
3116 string signature = SignMessage(message, AuthorizationSetBuilder()
3117 .Digest(Digest::NONE)
3118 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3119}
3120
3121/*
3122 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3123 *
3124 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3125 * given a too-long message.
3126 */
3127TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3128 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3129 .RsaSigningKey(2048, 65537)
3130 .Digest(Digest::NONE)
3131 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003132 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3133 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003134 string message(257, 'a');
3135
3136 EXPECT_EQ(ErrorCode::OK,
3137 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3138 .Digest(Digest::NONE)
3139 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3140 string signature;
3141 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3142}
3143
3144/*
3145 * SigningOperationsTest.RsaPssSha512TooSmallKey
3146 *
3147 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3148 * used with a key that is too small for the message.
3149 *
3150 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3151 * keymint specification requires that salt_size == digest_size, so the message will be
3152 * digest_size * 2 +
3153 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3154 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3155 * for a 1024-bit key.
3156 */
3157TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003158 if (SecLevel() == SecurityLevel::STRONGBOX) {
3159 GTEST_SKIP() << "Test not applicable to StrongBox device";
3160 }
Selene Huang31ab4042020-04-29 04:22:39 -07003161 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3162 .RsaSigningKey(1024, 65537)
3163 .Digest(Digest::SHA_2_512)
3164 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003165 .Padding(PaddingMode::RSA_PSS)
3166 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003167 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3168 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3169 .Digest(Digest::SHA_2_512)
3170 .Padding(PaddingMode::RSA_PSS)));
3171}
3172
3173/*
3174 * SigningOperationsTest.RsaNoPaddingTooLong
3175 *
3176 * Verifies that raw RSA signature operations fail with the correct error code when
3177 * given a too-long message.
3178 */
3179TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3180 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3181 .RsaSigningKey(2048, 65537)
3182 .Digest(Digest::NONE)
3183 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003184 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3185 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003186 // One byte too long
3187 string message(2048 / 8 + 1, 'a');
3188 ASSERT_EQ(ErrorCode::OK,
3189 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3190 .Digest(Digest::NONE)
3191 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3192 string result;
3193 ErrorCode finish_error_code = Finish(message, &result);
3194 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3195 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3196
3197 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3198 message = string(128 * 1024, 'a');
3199 ASSERT_EQ(ErrorCode::OK,
3200 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3201 .Digest(Digest::NONE)
3202 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3203 finish_error_code = Finish(message, &result);
3204 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3205 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3206}
3207
3208/*
3209 * SigningOperationsTest.RsaAbort
3210 *
3211 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3212 * test, but the behavior should be algorithm and purpose-independent.
3213 */
3214TEST_P(SigningOperationsTest, RsaAbort) {
3215 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3216 .RsaSigningKey(2048, 65537)
3217 .Digest(Digest::NONE)
3218 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003219 .Padding(PaddingMode::NONE)
3220 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003221
3222 ASSERT_EQ(ErrorCode::OK,
3223 Begin(KeyPurpose::SIGN,
3224 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3225 EXPECT_EQ(ErrorCode::OK, Abort());
3226
3227 // Another abort should fail
3228 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3229
3230 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003231 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003232}
3233
3234/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003235 * SigningOperationsTest.RsaNonUniqueParams
3236 *
3237 * Verifies that an operation with multiple padding modes is rejected.
3238 */
3239TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3241 .RsaSigningKey(2048, 65537)
3242 .Digest(Digest::NONE)
3243 .Digest(Digest::SHA1)
3244 .Authorization(TAG_NO_AUTH_REQUIRED)
3245 .Padding(PaddingMode::NONE)
3246 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3247 .SetDefaultValidity()));
3248
3249 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3250 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3251 .Digest(Digest::NONE)
3252 .Padding(PaddingMode::NONE)
3253 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3254
Tommy Chiuc93c4392021-05-11 18:36:50 +08003255 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3256 .Digest(Digest::NONE)
3257 .Digest(Digest::SHA1)
3258 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3259 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003260
3261 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3262 Begin(KeyPurpose::SIGN,
3263 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3264}
3265
3266/*
Selene Huang31ab4042020-04-29 04:22:39 -07003267 * SigningOperationsTest.RsaUnsupportedPadding
3268 *
3269 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3270 * with a padding mode inappropriate for RSA.
3271 */
3272TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3273 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3274 .RsaSigningKey(2048, 65537)
3275 .Authorization(TAG_NO_AUTH_REQUIRED)
3276 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003277 .Padding(PaddingMode::PKCS7)
3278 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003279 ASSERT_EQ(
3280 ErrorCode::UNSUPPORTED_PADDING_MODE,
3281 Begin(KeyPurpose::SIGN,
3282 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003283 CheckedDeleteKey();
3284
3285 ASSERT_EQ(ErrorCode::OK,
3286 GenerateKey(
3287 AuthorizationSetBuilder()
3288 .RsaSigningKey(2048, 65537)
3289 .Authorization(TAG_NO_AUTH_REQUIRED)
3290 .Digest(Digest::SHA_2_256 /* supported digest */)
3291 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3292 .SetDefaultValidity()));
3293 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3294 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3295 .Digest(Digest::SHA_2_256)
3296 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003297}
3298
3299/*
3300 * SigningOperationsTest.RsaPssNoDigest
3301 *
3302 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3303 */
3304TEST_P(SigningOperationsTest, RsaNoDigest) {
3305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3306 .RsaSigningKey(2048, 65537)
3307 .Authorization(TAG_NO_AUTH_REQUIRED)
3308 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003309 .Padding(PaddingMode::RSA_PSS)
3310 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003311 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3312 Begin(KeyPurpose::SIGN,
3313 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3314
3315 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3316 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3317}
3318
3319/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003320 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003321 *
3322 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3323 * supported in some cases (as validated in other tests), but a mode must be specified.
3324 */
3325TEST_P(SigningOperationsTest, RsaNoPadding) {
3326 // Padding must be specified
3327 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3328 .RsaKey(2048, 65537)
3329 .Authorization(TAG_NO_AUTH_REQUIRED)
3330 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003331 .Digest(Digest::NONE)
3332 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003333 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3334 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3335}
3336
3337/*
3338 * SigningOperationsTest.RsaShortMessage
3339 *
3340 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3341 */
3342TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3343 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3344 .Authorization(TAG_NO_AUTH_REQUIRED)
3345 .RsaSigningKey(2048, 65537)
3346 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003347 .Padding(PaddingMode::NONE)
3348 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003349
3350 // Barely shorter
3351 string message(2048 / 8 - 1, 'a');
3352 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3353
3354 // Much shorter
3355 message = "a";
3356 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3357}
3358
3359/*
3360 * SigningOperationsTest.RsaSignWithEncryptionKey
3361 *
3362 * Verifies that RSA encryption keys cannot be used to sign.
3363 */
3364TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3366 .Authorization(TAG_NO_AUTH_REQUIRED)
3367 .RsaEncryptionKey(2048, 65537)
3368 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003369 .Padding(PaddingMode::NONE)
3370 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003371 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3372 Begin(KeyPurpose::SIGN,
3373 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3374}
3375
3376/*
3377 * SigningOperationsTest.RsaSignTooLargeMessage
3378 *
3379 * Verifies that attempting a raw signature of a message which is the same length as the key,
3380 * but numerically larger than the public modulus, fails with the correct error.
3381 */
3382TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3383 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3384 .Authorization(TAG_NO_AUTH_REQUIRED)
3385 .RsaSigningKey(2048, 65537)
3386 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003387 .Padding(PaddingMode::NONE)
3388 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003389
3390 // Largest possible message will always be larger than the public modulus.
3391 string message(2048 / 8, static_cast<char>(0xff));
3392 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3393 .Authorization(TAG_NO_AUTH_REQUIRED)
3394 .Digest(Digest::NONE)
3395 .Padding(PaddingMode::NONE)));
3396 string signature;
3397 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3398}
3399
3400/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003401 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3402 *
David Drysdale42fe1892021-10-14 14:43:46 +01003403 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003404 */
3405TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003406 string message = "1234567890";
3407 string corrupt_message = "2234567890";
3408 for (auto curve : ValidCurves()) {
3409 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003410 // Ed25519 only allows Digest::NONE.
3411 auto digests = (curve == EcCurve::CURVE_25519)
3412 ? std::vector<Digest>(1, Digest::NONE)
3413 : ValidDigests(true /* withNone */, false /* withMD5 */);
3414
David Drysdaledf8f52e2021-05-06 08:10:58 +01003415 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3416 .Authorization(TAG_NO_AUTH_REQUIRED)
3417 .EcdsaSigningKey(curve)
3418 .Digest(digests)
3419 .SetDefaultValidity());
3420 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3421 if (error != ErrorCode::OK) {
3422 continue;
3423 }
3424
3425 for (auto digest : digests) {
3426 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3427 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3428 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3429 }
3430
3431 auto rc = DeleteKey();
3432 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3433 }
3434}
3435
3436/*
Selene Huang31ab4042020-04-29 04:22:39 -07003437 * SigningOperationsTest.EcdsaAllCurves
3438 *
David Drysdale42fe1892021-10-14 14:43:46 +01003439 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003440 */
3441TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3442 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003443 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3444 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003445 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3446 .Authorization(TAG_NO_AUTH_REQUIRED)
3447 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003448 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003449 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003450 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3451 if (error != ErrorCode::OK) continue;
3452
3453 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003454 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003455 CheckedDeleteKey();
3456 }
3457}
3458
3459/*
David Drysdale42fe1892021-10-14 14:43:46 +01003460 * SigningOperationsTest.EcdsaCurve25519
3461 *
3462 * Verifies that ECDSA operations succeed with curve25519.
3463 */
3464TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3465 if (!Curve25519Supported()) {
3466 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3467 }
3468
3469 EcCurve curve = EcCurve::CURVE_25519;
3470 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3471 .Authorization(TAG_NO_AUTH_REQUIRED)
3472 .EcdsaSigningKey(curve)
3473 .Digest(Digest::NONE)
3474 .SetDefaultValidity());
3475 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3476
3477 string message(1024, 'a');
3478 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3479 CheckedDeleteKey();
3480}
3481
3482/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003483 * SigningOperationsTest.EcdsaCurve25519MaxSize
3484 *
3485 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3486 */
3487TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3488 if (!Curve25519Supported()) {
3489 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3490 }
3491
3492 EcCurve curve = EcCurve::CURVE_25519;
3493 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3494 .Authorization(TAG_NO_AUTH_REQUIRED)
3495 .EcdsaSigningKey(curve)
3496 .Digest(Digest::NONE)
3497 .SetDefaultValidity());
3498 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3499
3500 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3501
3502 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3503 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3504 string message(msg_size, 'a');
3505
3506 // Attempt to sign via Begin+Finish.
3507 AuthorizationSet out_params;
3508 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3509 EXPECT_TRUE(out_params.empty());
3510 string signature;
3511 auto result = Finish(message, &signature);
3512 EXPECT_EQ(result, ErrorCode::OK);
3513 LocalVerifyMessage(message, signature, params);
3514
3515 // Attempt to sign via Begin+Update+Finish
3516 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3517 EXPECT_TRUE(out_params.empty());
3518 string output;
3519 result = Update(message, &output);
3520 EXPECT_EQ(result, ErrorCode::OK);
3521 EXPECT_EQ(output.size(), 0);
3522 string signature2;
3523 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3524 LocalVerifyMessage(message, signature2, params);
3525 }
3526
3527 CheckedDeleteKey();
3528}
3529
3530/*
3531 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3532 *
3533 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3534 */
3535TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3536 if (!Curve25519Supported()) {
3537 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3538 }
3539
3540 EcCurve curve = EcCurve::CURVE_25519;
3541 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3542 .Authorization(TAG_NO_AUTH_REQUIRED)
3543 .EcdsaSigningKey(curve)
3544 .Digest(Digest::NONE)
3545 .SetDefaultValidity());
3546 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3547
3548 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3549
3550 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3551 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3552 string message(msg_size, 'a');
3553
3554 // Attempt to sign via Begin+Finish.
3555 AuthorizationSet out_params;
3556 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3557 EXPECT_TRUE(out_params.empty());
3558 string signature;
3559 auto result = Finish(message, &signature);
3560 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3561
3562 // Attempt to sign via Begin+Update (but never get to Finish)
3563 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3564 EXPECT_TRUE(out_params.empty());
3565 string output;
3566 result = Update(message, &output);
3567 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3568 }
3569
3570 CheckedDeleteKey();
3571}
3572
3573/*
Selene Huang31ab4042020-04-29 04:22:39 -07003574 * SigningOperationsTest.EcdsaNoDigestHugeData
3575 *
3576 * Verifies that ECDSA operations support very large messages, even without digesting. This
3577 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3578 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3579 * the framework.
3580 */
3581TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3583 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003584 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003585 .Digest(Digest::NONE)
3586 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003587 string message(1 * 1024, 'a');
3588 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3589}
3590
3591/*
3592 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3593 *
3594 * Verifies that using an EC key requires the correct app ID/data.
3595 */
3596TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3598 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003599 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003600 .Digest(Digest::NONE)
3601 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003602 .Authorization(TAG_APPLICATION_DATA, "appdata")
3603 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003604
3605 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3606
Selene Huang31ab4042020-04-29 04:22:39 -07003607 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3608 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3609 AbortIfNeeded();
3610 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3611 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3612 .Digest(Digest::NONE)
3613 .Authorization(TAG_APPLICATION_ID, "clientid")));
3614 AbortIfNeeded();
3615 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3616 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3617 .Digest(Digest::NONE)
3618 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3619 AbortIfNeeded();
3620 EXPECT_EQ(ErrorCode::OK,
3621 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3622 .Digest(Digest::NONE)
3623 .Authorization(TAG_APPLICATION_DATA, "appdata")
3624 .Authorization(TAG_APPLICATION_ID, "clientid")));
3625 AbortIfNeeded();
3626}
3627
3628/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003629 * SigningOperationsTest.EcdsaIncompatibleDigest
3630 *
3631 * Verifies that using an EC key requires compatible digest.
3632 */
3633TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3634 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3635 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003636 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003637 .Digest(Digest::NONE)
3638 .Digest(Digest::SHA1)
3639 .SetDefaultValidity()));
3640 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3641 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3642 AbortIfNeeded();
3643}
3644
3645/*
Selene Huang31ab4042020-04-29 04:22:39 -07003646 * SigningOperationsTest.AesEcbSign
3647 *
3648 * Verifies that attempts to use AES keys to sign fail in the correct way.
3649 */
3650TEST_P(SigningOperationsTest, AesEcbSign) {
3651 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3652 .Authorization(TAG_NO_AUTH_REQUIRED)
3653 .SigningKey()
3654 .AesEncryptionKey(128)
3655 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3656
3657 AuthorizationSet out_params;
3658 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3659 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3660 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3661 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3662}
3663
3664/*
3665 * SigningOperationsTest.HmacAllDigests
3666 *
3667 * Verifies that HMAC works with all digests.
3668 */
3669TEST_P(SigningOperationsTest, HmacAllDigests) {
3670 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003671 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003672 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3673 .Authorization(TAG_NO_AUTH_REQUIRED)
3674 .HmacKey(128)
3675 .Digest(digest)
3676 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3677 << "Failed to create HMAC key with digest " << digest;
3678 string message = "12345678901234567890123456789012";
3679 string signature = MacMessage(message, digest, 160);
3680 EXPECT_EQ(160U / 8U, signature.size())
3681 << "Failed to sign with HMAC key with digest " << digest;
3682 CheckedDeleteKey();
3683 }
3684}
3685
3686/*
3687 * SigningOperationsTest.HmacSha256TooLargeMacLength
3688 *
3689 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3690 * digest size.
3691 */
3692TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3693 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3694 .Authorization(TAG_NO_AUTH_REQUIRED)
3695 .HmacKey(128)
3696 .Digest(Digest::SHA_2_256)
3697 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3698 AuthorizationSet output_params;
3699 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3700 AuthorizationSetBuilder()
3701 .Digest(Digest::SHA_2_256)
3702 .Authorization(TAG_MAC_LENGTH, 264),
3703 &output_params));
3704}
3705
3706/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003707 * SigningOperationsTest.HmacSha256InvalidMacLength
3708 *
3709 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3710 * not a multiple of 8.
3711 */
3712TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3713 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3714 .Authorization(TAG_NO_AUTH_REQUIRED)
3715 .HmacKey(128)
3716 .Digest(Digest::SHA_2_256)
3717 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3718 AuthorizationSet output_params;
3719 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3720 AuthorizationSetBuilder()
3721 .Digest(Digest::SHA_2_256)
3722 .Authorization(TAG_MAC_LENGTH, 161),
3723 &output_params));
3724}
3725
3726/*
Selene Huang31ab4042020-04-29 04:22:39 -07003727 * SigningOperationsTest.HmacSha256TooSmallMacLength
3728 *
3729 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3730 * specified minimum MAC length.
3731 */
3732TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3733 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3734 .Authorization(TAG_NO_AUTH_REQUIRED)
3735 .HmacKey(128)
3736 .Digest(Digest::SHA_2_256)
3737 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3738 AuthorizationSet output_params;
3739 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3740 AuthorizationSetBuilder()
3741 .Digest(Digest::SHA_2_256)
3742 .Authorization(TAG_MAC_LENGTH, 120),
3743 &output_params));
3744}
3745
3746/*
3747 * SigningOperationsTest.HmacRfc4231TestCase3
3748 *
3749 * Validates against the test vectors from RFC 4231 test case 3.
3750 */
3751TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3752 string key(20, 0xaa);
3753 string message(50, 0xdd);
3754 uint8_t sha_224_expected[] = {
3755 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3756 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3757 };
3758 uint8_t sha_256_expected[] = {
3759 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3760 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3761 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3762 };
3763 uint8_t sha_384_expected[] = {
3764 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3765 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3766 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3767 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3768 };
3769 uint8_t sha_512_expected[] = {
3770 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3771 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3772 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3773 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3774 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3775 };
3776
3777 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3778 if (SecLevel() != SecurityLevel::STRONGBOX) {
3779 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3780 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3781 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3782 }
3783}
3784
3785/*
3786 * SigningOperationsTest.HmacRfc4231TestCase5
3787 *
3788 * Validates against the test vectors from RFC 4231 test case 5.
3789 */
3790TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3791 string key(20, 0x0c);
3792 string message = "Test With Truncation";
3793
3794 uint8_t sha_224_expected[] = {
3795 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3796 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3797 };
3798 uint8_t sha_256_expected[] = {
3799 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3800 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3801 };
3802 uint8_t sha_384_expected[] = {
3803 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3804 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3805 };
3806 uint8_t sha_512_expected[] = {
3807 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3808 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3809 };
3810
3811 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3812 if (SecLevel() != SecurityLevel::STRONGBOX) {
3813 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3814 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3815 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3816 }
3817}
3818
3819INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3820
3821typedef KeyMintAidlTestBase VerificationOperationsTest;
3822
3823/*
Selene Huang31ab4042020-04-29 04:22:39 -07003824 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3825 *
3826 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3827 */
3828TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3829 string key_material = "HelloThisIsAKey";
3830
3831 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003832 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003833 EXPECT_EQ(ErrorCode::OK,
3834 ImportKey(AuthorizationSetBuilder()
3835 .Authorization(TAG_NO_AUTH_REQUIRED)
3836 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3837 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3838 .Digest(Digest::SHA_2_256)
3839 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3840 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003841 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003842 EXPECT_EQ(ErrorCode::OK,
3843 ImportKey(AuthorizationSetBuilder()
3844 .Authorization(TAG_NO_AUTH_REQUIRED)
3845 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3846 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3847 .Digest(Digest::SHA_2_256)
3848 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3849 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003850 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003851
3852 string message = "This is a message.";
3853 string signature = SignMessage(
3854 signing_key, message,
3855 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3856
3857 // Signing key should not work.
3858 AuthorizationSet out_params;
3859 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3860 Begin(KeyPurpose::VERIFY, signing_key,
3861 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3862
3863 // Verification key should work.
3864 VerifyMessage(verification_key, message, signature,
3865 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003866}
3867
Prashant Patildec9fdc2021-12-08 15:25:47 +00003868/*
3869 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3870 *
3871 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3872 */
3873TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3874 string key_material = "HelloThisIsAKey";
3875
3876 vector<uint8_t> signing_key, verification_key;
3877 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3878 EXPECT_EQ(ErrorCode::OK,
3879 ImportKey(AuthorizationSetBuilder()
3880 .Authorization(TAG_NO_AUTH_REQUIRED)
3881 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3882 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3883 .Digest(Digest::SHA_2_256)
3884 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3885 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003886 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003887 EXPECT_EQ(ErrorCode::OK,
3888 ImportKey(AuthorizationSetBuilder()
3889 .Authorization(TAG_NO_AUTH_REQUIRED)
3890 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3891 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3892 .Digest(Digest::SHA_2_256)
3893 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3894 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003895 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003896
3897 string message = "This is a message.";
3898 string signature = SignMessage(
3899 signing_key, message,
3900 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3901
3902 AuthorizationSet begin_out_params;
3903 ASSERT_EQ(ErrorCode::OK,
3904 Begin(KeyPurpose::VERIFY, verification_key,
3905 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3906
3907 string corruptMessage = "This is b message."; // Corrupted message
3908 string output;
3909 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3910
3911 ASSERT_EQ(ErrorCode::OK,
3912 Begin(KeyPurpose::VERIFY, verification_key,
3913 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3914
3915 signature[0] += 1; // Corrupt a signature
3916 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003917}
3918
Selene Huang31ab4042020-04-29 04:22:39 -07003919INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3920
3921typedef KeyMintAidlTestBase ExportKeyTest;
3922
3923/*
3924 * ExportKeyTest.RsaUnsupportedKeyFormat
3925 *
3926 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3927 */
3928// TODO(seleneh) add ExportKey to GenerateKey
3929// check result
3930
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003931class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003932 public:
3933 template <TagType tag_type, Tag tag, typename ValueT>
3934 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3935 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003936 for (auto& entry : key_characteristics_) {
3937 if (entry.securityLevel == SecLevel()) {
3938 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3939 << "Tag " << tag << " with value " << expected
3940 << " not found at security level" << entry.securityLevel;
3941 } else {
3942 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3943 << "Tag " << tag << " found at security level " << entry.securityLevel;
3944 }
Selene Huang31ab4042020-04-29 04:22:39 -07003945 }
3946 }
3947
3948 void CheckOrigin() {
3949 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003950 // Origin isn't a crypto param, but it always lives with them.
3951 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003952 }
3953};
3954
3955/*
3956 * ImportKeyTest.RsaSuccess
3957 *
3958 * Verifies that importing and using an RSA key pair works correctly.
3959 */
3960TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003961 uint32_t key_size;
3962 string key;
3963
3964 if (SecLevel() == SecurityLevel::STRONGBOX) {
3965 key_size = 2048;
3966 key = rsa_2048_key;
3967 } else {
3968 key_size = 1024;
3969 key = rsa_key;
3970 }
3971
Selene Huang31ab4042020-04-29 04:22:39 -07003972 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3973 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003974 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003975 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003976 .Padding(PaddingMode::RSA_PSS)
3977 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003978 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003979
3980 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003981 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003982 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3983 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3984 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3985 CheckOrigin();
3986
3987 string message(1024 / 8, 'a');
3988 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3989 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003990 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003991}
3992
3993/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003994 * ImportKeyTest.RsaSuccessWithoutParams
3995 *
3996 * Verifies that importing and using an RSA key pair without specifying parameters
3997 * works correctly.
3998 */
3999TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4000 uint32_t key_size;
4001 string key;
4002
4003 if (SecLevel() == SecurityLevel::STRONGBOX) {
4004 key_size = 2048;
4005 key = rsa_2048_key;
4006 } else {
4007 key_size = 1024;
4008 key = rsa_key;
4009 }
4010
4011 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4012 .Authorization(TAG_NO_AUTH_REQUIRED)
4013 .SigningKey()
4014 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4015 .Digest(Digest::SHA_2_256)
4016 .Padding(PaddingMode::RSA_PSS)
4017 .SetDefaultValidity(),
4018 KeyFormat::PKCS8, key));
4019
4020 // Key size and public exponent are determined from the imported key material.
4021 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4022 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4023
4024 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4025 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4026 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4027 CheckOrigin();
4028
4029 string message(1024 / 8, 'a');
4030 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4031 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004032 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004033}
4034
4035/*
Selene Huang31ab4042020-04-29 04:22:39 -07004036 * ImportKeyTest.RsaKeySizeMismatch
4037 *
4038 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4039 * correct way.
4040 */
4041TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4042 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4043 ImportKey(AuthorizationSetBuilder()
4044 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4045 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004046 .Padding(PaddingMode::NONE)
4047 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004048 KeyFormat::PKCS8, rsa_key));
4049}
4050
4051/*
4052 * ImportKeyTest.RsaPublicExponentMismatch
4053 *
4054 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4055 * fails in the correct way.
4056 */
4057TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4058 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4059 ImportKey(AuthorizationSetBuilder()
4060 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4061 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004062 .Padding(PaddingMode::NONE)
4063 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004064 KeyFormat::PKCS8, rsa_key));
4065}
4066
4067/*
David Drysdalee60248c2021-10-04 12:54:13 +01004068 * ImportKeyTest.RsaAttestMultiPurposeFail
4069 *
4070 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4071 */
4072TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004073 if (AidlVersion() < 2) {
4074 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4075 // with other key purposes. However, this was not checked at the time
4076 // so we can only be strict about checking this for implementations of KeyMint
4077 // version 2 and above.
4078 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4079 }
David Drysdalee60248c2021-10-04 12:54:13 +01004080 uint32_t key_size = 2048;
4081 string key = rsa_2048_key;
4082
4083 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4084 ImportKey(AuthorizationSetBuilder()
4085 .Authorization(TAG_NO_AUTH_REQUIRED)
4086 .RsaSigningKey(key_size, 65537)
4087 .AttestKey()
4088 .Digest(Digest::SHA_2_256)
4089 .Padding(PaddingMode::RSA_PSS)
4090 .SetDefaultValidity(),
4091 KeyFormat::PKCS8, key));
4092}
4093
4094/*
Selene Huang31ab4042020-04-29 04:22:39 -07004095 * ImportKeyTest.EcdsaSuccess
4096 *
4097 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4098 */
4099TEST_P(ImportKeyTest, EcdsaSuccess) {
4100 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4101 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004102 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004103 .Digest(Digest::SHA_2_256)
4104 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004105 KeyFormat::PKCS8, ec_256_key));
4106
4107 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004108 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4109 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4110
4111 CheckOrigin();
4112
4113 string message(32, 'a');
4114 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4115 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004116 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004117}
4118
4119/*
David Drysdale9b8d75e2023-09-05 15:16:47 +01004120 * ImportKeyTest.EcdsaSuccessCurveNotSpecified
4121 *
4122 * Verifies that importing and using an ECDSA P-256 key pair works correctly
4123 * when the EC_CURVE is not explicitly specified.
4124 */
4125TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
David Drysdale1405dbc2023-11-02 09:26:44 +00004126 if (get_vsr_api_level() < __ANDROID_API_V__) {
David Drysdale9b8d75e2023-09-05 15:16:47 +01004127 /*
David Drysdale1405dbc2023-11-02 09:26:44 +00004128 * The KeyMint spec was previously not clear as to whether EC_CURVE was optional on import
4129 * of EC keys. However, this was not checked at the time so we can only be strict about
4130 * checking this for implementations at VSR-V or later.
David Drysdale9b8d75e2023-09-05 15:16:47 +01004131 */
David Drysdale1405dbc2023-11-02 09:26:44 +00004132 GTEST_SKIP() << "Skipping EC_CURVE on import only strict >= VSR-V";
David Drysdale9b8d75e2023-09-05 15:16:47 +01004133 }
4134
4135 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4136 .Authorization(TAG_NO_AUTH_REQUIRED)
4137 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4138 .SigningKey()
4139 .Digest(Digest::SHA_2_256)
4140 .SetDefaultValidity(),
4141 KeyFormat::PKCS8, ec_256_key));
4142
4143 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4144 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4145 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4146
4147 CheckOrigin();
4148
4149 string message(32, 'a');
4150 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4151 string signature = SignMessage(message, params);
4152 LocalVerifyMessage(message, signature, params);
4153}
4154
4155/*
Selene Huang31ab4042020-04-29 04:22:39 -07004156 * ImportKeyTest.EcdsaP256RFC5915Success
4157 *
4158 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4159 * correctly.
4160 */
4161TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4162 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4163 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004164 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004165 .Digest(Digest::SHA_2_256)
4166 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004167 KeyFormat::PKCS8, ec_256_key_rfc5915));
4168
4169 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004170 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4171 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4172
4173 CheckOrigin();
4174
4175 string message(32, 'a');
4176 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4177 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004178 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004179}
4180
4181/*
4182 * ImportKeyTest.EcdsaP256SEC1Success
4183 *
4184 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4185 */
4186TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4187 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4188 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004189 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004190 .Digest(Digest::SHA_2_256)
4191 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004192 KeyFormat::PKCS8, ec_256_key_sec1));
4193
4194 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004195 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4196 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4197
4198 CheckOrigin();
4199
4200 string message(32, 'a');
4201 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4202 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004203 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004204}
4205
4206/*
4207 * ImportKeyTest.Ecdsa521Success
4208 *
4209 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4210 */
4211TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004212 if (SecLevel() == SecurityLevel::STRONGBOX) {
4213 GTEST_SKIP() << "Test not applicable to StrongBox device";
4214 }
Selene Huang31ab4042020-04-29 04:22:39 -07004215 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4216 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004217 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004218 .Digest(Digest::SHA_2_256)
4219 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004220 KeyFormat::PKCS8, ec_521_key));
4221
4222 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004223 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4224 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4225 CheckOrigin();
4226
4227 string message(32, 'a');
4228 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4229 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004230 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004231}
4232
4233/*
Selene Huang31ab4042020-04-29 04:22:39 -07004234 * ImportKeyTest.EcdsaCurveMismatch
4235 *
4236 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4237 * the correct way.
4238 */
4239TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4240 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4241 ImportKey(AuthorizationSetBuilder()
4242 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004243 .Digest(Digest::NONE)
4244 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004245 KeyFormat::PKCS8, ec_256_key));
4246}
4247
4248/*
David Drysdalee60248c2021-10-04 12:54:13 +01004249 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4250 *
4251 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4252 */
4253TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004254 if (AidlVersion() < 2) {
4255 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4256 // with other key purposes. However, this was not checked at the time
4257 // so we can only be strict about checking this for implementations of KeyMint
4258 // version 2 and above.
4259 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4260 }
David Drysdalee60248c2021-10-04 12:54:13 +01004261 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4262 ImportKey(AuthorizationSetBuilder()
4263 .Authorization(TAG_NO_AUTH_REQUIRED)
4264 .EcdsaSigningKey(EcCurve::P_256)
4265 .AttestKey()
4266 .Digest(Digest::SHA_2_256)
4267 .SetDefaultValidity(),
4268 KeyFormat::PKCS8, ec_256_key));
4269}
4270
4271/*
David Drysdale42fe1892021-10-14 14:43:46 +01004272 * ImportKeyTest.Ed25519RawSuccess
4273 *
4274 * Verifies that importing and using a raw Ed25519 private key works correctly.
4275 */
4276TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4277 if (!Curve25519Supported()) {
4278 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4279 }
4280
4281 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4282 .Authorization(TAG_NO_AUTH_REQUIRED)
4283 .EcdsaSigningKey(EcCurve::CURVE_25519)
4284 .Digest(Digest::NONE)
4285 .SetDefaultValidity(),
4286 KeyFormat::RAW, ed25519_key));
4287 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4288 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4289 CheckOrigin();
4290
4291 // The returned cert should hold the correct public key.
4292 ASSERT_GT(cert_chain_.size(), 0);
4293 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4294 ASSERT_NE(kmKeyCert, nullptr);
4295 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4296 ASSERT_NE(kmPubKey.get(), nullptr);
4297 size_t kmPubKeySize = 32;
4298 uint8_t kmPubKeyData[32];
4299 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4300 ASSERT_EQ(kmPubKeySize, 32);
4301 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4302
4303 string message(32, 'a');
4304 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4305 string signature = SignMessage(message, params);
4306 LocalVerifyMessage(message, signature, params);
4307}
4308
4309/*
4310 * ImportKeyTest.Ed25519Pkcs8Success
4311 *
4312 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4313 */
4314TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4315 if (!Curve25519Supported()) {
4316 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4317 }
4318
4319 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4320 .Authorization(TAG_NO_AUTH_REQUIRED)
4321 .EcdsaSigningKey(EcCurve::CURVE_25519)
4322 .Digest(Digest::NONE)
4323 .SetDefaultValidity(),
4324 KeyFormat::PKCS8, ed25519_pkcs8_key));
4325 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4326 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4327 CheckOrigin();
4328
4329 // The returned cert should hold the correct public key.
4330 ASSERT_GT(cert_chain_.size(), 0);
4331 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4332 ASSERT_NE(kmKeyCert, nullptr);
4333 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4334 ASSERT_NE(kmPubKey.get(), nullptr);
4335 size_t kmPubKeySize = 32;
4336 uint8_t kmPubKeyData[32];
4337 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4338 ASSERT_EQ(kmPubKeySize, 32);
4339 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4340
4341 string message(32, 'a');
4342 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4343 string signature = SignMessage(message, params);
4344 LocalVerifyMessage(message, signature, params);
4345}
4346
4347/*
4348 * ImportKeyTest.Ed25519CurveMismatch
4349 *
4350 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4351 * the correct way.
4352 */
4353TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4354 if (!Curve25519Supported()) {
4355 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4356 }
4357
4358 ASSERT_NE(ErrorCode::OK,
4359 ImportKey(AuthorizationSetBuilder()
4360 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4361 .Digest(Digest::NONE)
4362 .SetDefaultValidity(),
4363 KeyFormat::RAW, ed25519_key));
4364}
4365
4366/*
4367 * ImportKeyTest.Ed25519FormatMismatch
4368 *
4369 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4370 */
4371TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4372 if (!Curve25519Supported()) {
4373 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4374 }
4375
4376 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4377 .EcdsaSigningKey(EcCurve::CURVE_25519)
4378 .Digest(Digest::NONE)
4379 .SetDefaultValidity(),
4380 KeyFormat::PKCS8, ed25519_key));
4381 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4382 .EcdsaSigningKey(EcCurve::CURVE_25519)
4383 .Digest(Digest::NONE)
4384 .SetDefaultValidity(),
4385 KeyFormat::RAW, ed25519_pkcs8_key));
4386}
4387
4388/*
4389 * ImportKeyTest.Ed25519PurposeMismatch
4390 *
4391 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4392 */
4393TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4394 if (!Curve25519Supported()) {
4395 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4396 }
4397
4398 // Can't have both SIGN and ATTEST_KEY
4399 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4400 .EcdsaSigningKey(EcCurve::CURVE_25519)
4401 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4402 .Digest(Digest::NONE)
4403 .SetDefaultValidity(),
4404 KeyFormat::RAW, ed25519_key));
4405 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4406 // PKCS#8 format and so includes an OID).
4407 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4408 .EcdsaKey(EcCurve::CURVE_25519)
4409 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4410 .Digest(Digest::NONE)
4411 .SetDefaultValidity(),
4412 KeyFormat::PKCS8, ed25519_pkcs8_key));
4413}
4414
4415/*
4416 * ImportKeyTest.X25519RawSuccess
4417 *
4418 * Verifies that importing and using a raw X25519 private key works correctly.
4419 */
4420TEST_P(ImportKeyTest, X25519RawSuccess) {
4421 if (!Curve25519Supported()) {
4422 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4423 }
4424
4425 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4426 .Authorization(TAG_NO_AUTH_REQUIRED)
4427 .EcdsaKey(EcCurve::CURVE_25519)
4428 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4429 .SetDefaultValidity(),
4430 KeyFormat::RAW, x25519_key));
4431
4432 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4433 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4434 CheckOrigin();
4435}
4436
4437/*
4438 * ImportKeyTest.X25519Pkcs8Success
4439 *
4440 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4441 */
4442TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4443 if (!Curve25519Supported()) {
4444 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4445 }
4446
4447 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4448 .Authorization(TAG_NO_AUTH_REQUIRED)
4449 .EcdsaKey(EcCurve::CURVE_25519)
4450 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4451 .SetDefaultValidity(),
4452 KeyFormat::PKCS8, x25519_pkcs8_key));
4453
4454 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4455 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4456 CheckOrigin();
4457}
4458
4459/*
4460 * ImportKeyTest.X25519CurveMismatch
4461 *
4462 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4463 * the correct way.
4464 */
4465TEST_P(ImportKeyTest, X25519CurveMismatch) {
4466 if (!Curve25519Supported()) {
4467 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4468 }
4469
4470 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4471 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4472 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4473 .SetDefaultValidity(),
4474 KeyFormat::RAW, x25519_key));
4475}
4476
4477/*
4478 * ImportKeyTest.X25519FormatMismatch
4479 *
4480 * Verifies that importing an X25519 key with an invalid format fails.
4481 */
4482TEST_P(ImportKeyTest, X25519FormatMismatch) {
4483 if (!Curve25519Supported()) {
4484 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4485 }
4486
4487 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4488 .EcdsaKey(EcCurve::CURVE_25519)
4489 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4490 .SetDefaultValidity(),
4491 KeyFormat::PKCS8, x25519_key));
4492 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4493 .EcdsaKey(EcCurve::CURVE_25519)
4494 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4495 .SetDefaultValidity(),
4496 KeyFormat::RAW, x25519_pkcs8_key));
4497}
4498
4499/*
4500 * ImportKeyTest.X25519PurposeMismatch
4501 *
4502 * Verifies that importing an X25519 key pair with an invalid format fails.
4503 */
4504TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4505 if (!Curve25519Supported()) {
4506 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4507 }
4508
4509 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4510 .EcdsaKey(EcCurve::CURVE_25519)
4511 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4512 .SetDefaultValidity(),
4513 KeyFormat::PKCS8, x25519_pkcs8_key));
4514 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4515 .EcdsaSigningKey(EcCurve::CURVE_25519)
4516 .SetDefaultValidity(),
4517 KeyFormat::PKCS8, x25519_pkcs8_key));
4518}
4519
4520/*
Selene Huang31ab4042020-04-29 04:22:39 -07004521 * ImportKeyTest.AesSuccess
4522 *
4523 * Verifies that importing and using an AES key works.
4524 */
4525TEST_P(ImportKeyTest, AesSuccess) {
4526 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4527 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4528 .Authorization(TAG_NO_AUTH_REQUIRED)
4529 .AesEncryptionKey(key.size() * 8)
4530 .EcbMode()
4531 .Padding(PaddingMode::PKCS7),
4532 KeyFormat::RAW, key));
4533
4534 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4535 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4536 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4537 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4538 CheckOrigin();
4539
4540 string message = "Hello World!";
4541 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4542 string ciphertext = EncryptMessage(message, params);
4543 string plaintext = DecryptMessage(ciphertext, params);
4544 EXPECT_EQ(message, plaintext);
4545}
4546
4547/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004548 * ImportKeyTest.AesFailure
4549 *
4550 * Verifies that importing an invalid AES key fails.
4551 */
4552TEST_P(ImportKeyTest, AesFailure) {
4553 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4554 uint32_t bitlen = key.size() * 8;
4555 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004556 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004557 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004558 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004559 .Authorization(TAG_NO_AUTH_REQUIRED)
4560 .AesEncryptionKey(key_size)
4561 .EcbMode()
4562 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004563 KeyFormat::RAW, key);
4564 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004565 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4566 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004567 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004568
4569 // Explicit key size matches that of the provided key, but it's not a valid size.
4570 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4571 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4572 ImportKey(AuthorizationSetBuilder()
4573 .Authorization(TAG_NO_AUTH_REQUIRED)
4574 .AesEncryptionKey(long_key.size() * 8)
4575 .EcbMode()
4576 .Padding(PaddingMode::PKCS7),
4577 KeyFormat::RAW, long_key));
4578 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4579 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4580 ImportKey(AuthorizationSetBuilder()
4581 .Authorization(TAG_NO_AUTH_REQUIRED)
4582 .AesEncryptionKey(short_key.size() * 8)
4583 .EcbMode()
4584 .Padding(PaddingMode::PKCS7),
4585 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004586}
4587
4588/*
4589 * ImportKeyTest.TripleDesSuccess
4590 *
4591 * Verifies that importing and using a 3DES key works.
4592 */
4593TEST_P(ImportKeyTest, TripleDesSuccess) {
4594 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4595 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4596 .Authorization(TAG_NO_AUTH_REQUIRED)
4597 .TripleDesEncryptionKey(168)
4598 .EcbMode()
4599 .Padding(PaddingMode::PKCS7),
4600 KeyFormat::RAW, key));
4601
4602 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4603 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4604 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4605 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4606 CheckOrigin();
4607
4608 string message = "Hello World!";
4609 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4610 string ciphertext = EncryptMessage(message, params);
4611 string plaintext = DecryptMessage(ciphertext, params);
4612 EXPECT_EQ(message, plaintext);
4613}
4614
4615/*
4616 * ImportKeyTest.TripleDesFailure
4617 *
4618 * Verifies that importing an invalid 3DES key fails.
4619 */
4620TEST_P(ImportKeyTest, TripleDesFailure) {
4621 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004622 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004623 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004624 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004625 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004626 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004627 .Authorization(TAG_NO_AUTH_REQUIRED)
4628 .TripleDesEncryptionKey(key_size)
4629 .EcbMode()
4630 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004631 KeyFormat::RAW, key);
4632 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004633 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4634 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004635 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004636 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004637 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004638 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4639 ImportKey(AuthorizationSetBuilder()
4640 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004641 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004642 .EcbMode()
4643 .Padding(PaddingMode::PKCS7),
4644 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004645 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004646 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4647 ImportKey(AuthorizationSetBuilder()
4648 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004649 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004650 .EcbMode()
4651 .Padding(PaddingMode::PKCS7),
4652 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004653}
4654
4655/*
4656 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004657 *
4658 * Verifies that importing and using an HMAC key works.
4659 */
4660TEST_P(ImportKeyTest, HmacKeySuccess) {
4661 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4662 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4663 .Authorization(TAG_NO_AUTH_REQUIRED)
4664 .HmacKey(key.size() * 8)
4665 .Digest(Digest::SHA_2_256)
4666 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4667 KeyFormat::RAW, key));
4668
4669 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4670 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4671 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4672 CheckOrigin();
4673
4674 string message = "Hello World!";
4675 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4676 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4677}
4678
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004679/*
4680 * ImportKeyTest.GetKeyCharacteristics
4681 *
4682 * Verifies that imported keys have the correct characteristics.
4683 */
4684TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4685 vector<uint8_t> key_blob;
4686 vector<KeyCharacteristics> key_characteristics;
4687 auto base_builder = AuthorizationSetBuilder()
4688 .Padding(PaddingMode::NONE)
4689 .Authorization(TAG_NO_AUTH_REQUIRED)
4690 .SetDefaultValidity();
4691 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4692 Algorithm::TRIPLE_DES};
4693 ErrorCode result;
4694 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4695 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4696 for (auto alg : algorithms) {
4697 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4698 AuthorizationSetBuilder builder(base_builder);
4699 switch (alg) {
4700 case Algorithm::RSA:
4701 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4702
4703 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4704 &key_characteristics);
4705 break;
4706 case Algorithm::EC:
4707 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4708 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4709 &key_characteristics);
4710 break;
4711 case Algorithm::HMAC:
4712 builder.HmacKey(128)
4713 .Digest(Digest::SHA_2_256)
4714 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4715 result =
4716 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4717 break;
4718 case Algorithm::AES:
4719 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4720 result =
4721 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4722 break;
4723 case Algorithm::TRIPLE_DES:
4724 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4725 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4726 &key_characteristics);
4727 break;
4728 default:
4729 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4730 continue;
4731 }
4732 ASSERT_EQ(ErrorCode::OK, result);
4733 CheckCharacteristics(key_blob, key_characteristics);
4734 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4735 }
4736}
4737
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004738/*
4739 * ImportKeyTest.RsaOaepMGFDigestSuccess
4740 *
4741 * Include MGF-Digest explicitly in import key authorization list.
4742 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4743 * should have the correct characteristics.
4744 */
4745TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
Prashant Patil2114dca2023-09-21 14:57:10 +00004746 // There was no test to assert that MGF1 digest was present in generated/imported key
4747 // characteristics before Keymint V3, so there are some Keymint implementations where
4748 // this test case fails(b/297306437), hence this test is skipped for Keymint < 3.
4749 if (AidlVersion() < 3) {
4750 GTEST_SKIP() << "Test not applicable to Keymint < V3";
4751 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004752 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4753 size_t key_size = 2048;
4754
4755 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4756 .OaepMGFDigest(mgf_digests)
4757 .Authorization(TAG_NO_AUTH_REQUIRED)
4758 .RsaEncryptionKey(key_size, 65537)
4759 .Digest(Digest::SHA_2_256)
4760 .Padding(PaddingMode::RSA_OAEP)
4761 .SetDefaultValidity(),
4762 KeyFormat::PKCS8, rsa_2048_key));
4763
4764 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4765 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4766 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4767 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4768 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4769 CheckOrigin();
4770
4771 // Make sure explicitly specified mgf-digests exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004772 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digests, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004773
4774 string message = "Hello";
4775
4776 for (auto digest : mgf_digests) {
4777 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4778 auto params = AuthorizationSetBuilder()
4779 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4780 .Digest(Digest::SHA_2_256)
4781 .Padding(PaddingMode::RSA_OAEP);
4782 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4783 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4784 EXPECT_EQ(key_size / 8, ciphertext1.size());
4785
4786 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4787 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4788 EXPECT_EQ(key_size / 8, ciphertext2.size());
4789
4790 // OAEP randomizes padding so every result should be different (with astronomically high
4791 // probability).
4792 EXPECT_NE(ciphertext1, ciphertext2);
4793
4794 string plaintext1 = DecryptMessage(ciphertext1, params);
4795 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4796 string plaintext2 = DecryptMessage(ciphertext2, params);
4797 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4798
4799 // Decrypting corrupted ciphertext should fail.
4800 size_t offset_to_corrupt = ciphertext1.size() - 1;
4801 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4802 ciphertext1[offset_to_corrupt] = corrupt_byte;
4803
4804 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4805 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04004806 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004807 EXPECT_EQ(0U, result.size());
4808 }
4809}
4810
4811/*
4812 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4813 *
4814 * Don't specify MGF-Digest explicitly in import key authorization list.
4815 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4816 * verify that imported key should have the correct characteristics. Default
4817 * mgf-digest shouldn't be included in key charecteristics.
4818 */
4819TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4820 size_t key_size = 2048;
4821 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4822 .Authorization(TAG_NO_AUTH_REQUIRED)
4823 .RsaEncryptionKey(key_size, 65537)
4824 .Digest(Digest::SHA_2_256)
4825 .Padding(PaddingMode::RSA_OAEP)
4826 .SetDefaultValidity(),
4827 KeyFormat::PKCS8, rsa_2048_key));
4828
4829 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4830 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4831 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4832 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4833 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4834 CheckOrigin();
4835
Prashant Patil2114dca2023-09-21 14:57:10 +00004836 vector defaultDigest = {Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004837 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004838 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004839}
4840
Selene Huang31ab4042020-04-29 04:22:39 -07004841INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4842
4843auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004844 // IKeyMintDevice.aidl
4845 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4846 "020100" // INTEGER length 1 value 0x00 (version)
4847 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4848 "934bf94e2aa28a3f83c9f79297250262"
4849 "fbe3276b5a1c91159bbfa3ef8957aac8"
4850 "4b59b30b455a79c2973480823d8b3863"
4851 "c3deef4a8e243590268d80e18751a0e1"
4852 "30f67ce6a1ace9f79b95e097474febc9"
4853 "81195b1d13a69086c0863f66a7b7fdb4"
4854 "8792227b1ac5e2489febdf087ab54864"
4855 "83033a6f001ca5d1ec1e27f5c30f4cec"
4856 "2642074a39ae68aee552e196627a8e3d"
4857 "867e67a8c01b11e75f13cca0a97ab668"
4858 "b50cda07a8ecb7cd8e3dd7009c963653"
4859 "4f6f239cffe1fc8daa466f78b676c711"
4860 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4861 "99b801597d5220e307eaa5bee507fb94"
4862 "d1fa69f9e519b2de315bac92c36f2ea1"
4863 "fa1df4478c0ddedeae8c70e0233cd098"
4864 "040c" // OCTET STRING length 0x0c (initializationVector)
4865 "d796b02c370f1fa4cc0124f1"
4866 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4867 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4868 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4869 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4870 "3106" // SET length 0x06
4871 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4872 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4873 // } end SET
4874 // } end [1]
4875 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4876 "020120" // INTEGER length 1 value 0x20 (AES)
4877 // } end [2]
4878 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4879 "02020100" // INTEGER length 2 value 0x100
4880 // } end [3]
4881 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4882 "3103" // SET length 0x03 {
4883 "020101" // INTEGER length 1 value 0x01 (ECB)
4884 // } end SET
4885 // } end [4]
4886 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4887 "3103" // SET length 0x03 {
4888 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4889 // } end SET
4890 // } end [5]
4891 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4892 // (noAuthRequired)
4893 "0500" // NULL
4894 // } end [503]
4895 // } end SEQUENCE (AuthorizationList)
4896 // } end SEQUENCE (KeyDescription)
4897 "0420" // OCTET STRING length 0x20 (encryptedKey)
4898 "ccd540855f833a5e1480bfd2d36faf3a"
4899 "eee15df5beabe2691bc82dde2a7aa910"
4900 "0410" // OCTET STRING length 0x10 (tag)
4901 "64c9f689c60ff6223ab6e6999e0eb6e5"
4902 // } SEQUENCE (SecureKeyWrapper)
4903);
Selene Huang31ab4042020-04-29 04:22:39 -07004904
4905auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004906 // IKeyMintDevice.aidl
4907 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4908 "020100" // INTEGER length 1 value 0x00 (version)
4909 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4910 "aad93ed5924f283b4bb5526fbe7a1412"
4911 "f9d9749ec30db9062b29e574a8546f33"
4912 "c88732452f5b8e6a391ee76c39ed1712"
4913 "c61d8df6213dec1cffbc17a8c6d04c7b"
4914 "30893d8daa9b2015213e219468215532"
4915 "07f8f9931c4caba23ed3bee28b36947e"
4916 "47f10e0a5c3dc51c988a628daad3e5e1"
4917 "f4005e79c2d5a96c284b4b8d7e4948f3"
4918 "31e5b85dd5a236f85579f3ea1d1b8484"
4919 "87470bdb0ab4f81a12bee42c99fe0df4"
4920 "bee3759453e69ad1d68a809ce06b949f"
4921 "7694a990429b2fe81e066ff43e56a216"
4922 "02db70757922a4bcc23ab89f1e35da77"
4923 "586775f423e519c2ea394caf48a28d0c"
4924 "8020f1dcf6b3a68ec246f615ae96dae9"
4925 "a079b1f6eb959033c1af5c125fd94168"
4926 "040c" // OCTET STRING length 0x0c (initializationVector)
4927 "6d9721d08589581ab49204a3"
4928 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4929 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4930 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4931 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4932 "3106" // SET length 0x06
4933 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4934 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4935 // } end SET
4936 // } end [1]
4937 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4938 "020120" // INTEGER length 1 value 0x20 (AES)
4939 // } end [2]
4940 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4941 "02020100" // INTEGER length 2 value 0x100
4942 // } end [3]
4943 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4944 "3103" // SET length 0x03 {
4945 "020101" // INTEGER length 1 value 0x01 (ECB)
4946 // } end SET
4947 // } end [4]
4948 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4949 "3103" // SET length 0x03 {
4950 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4951 // } end SET
4952 // } end [5]
4953 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4954 // (noAuthRequired)
4955 "0500" // NULL
4956 // } end [503]
4957 // } end SEQUENCE (AuthorizationList)
4958 // } end SEQUENCE (KeyDescription)
4959 "0420" // OCTET STRING length 0x20 (encryptedKey)
4960 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4961 "c20d1f99a9a024a76f35c8e2cab9b68d"
4962 "0410" // OCTET STRING length 0x10 (tag)
4963 "2560c70109ae67c030f00b98b512a670"
4964 // } SEQUENCE (SecureKeyWrapper)
4965);
Selene Huang31ab4042020-04-29 04:22:39 -07004966
4967auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004968 // RFC 5208 s5
4969 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4970 "020100" // INTEGER length 1 value 0x00 (version)
4971 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4972 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4973 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4974 "0500" // NULL (parameters)
4975 // } SEQUENCE (AlgorithmIdentifier)
4976 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4977 // RFC 8017 A.1.2
4978 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4979 "020100" // INTEGER length 1 value 0x00 (version)
4980 "02820101" // INTEGER length 0x0101 (modulus) value...
4981 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4982 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4983 "7b06e673a837313d56b1c725150a3fef" // 0x30
4984 "86acbddc41bb759c2854eae32d35841e" // 0x40
4985 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4986 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4987 "312d7bd5921ffaea1347c157406fef71" // 0x70
4988 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4989 "f4645c11f5c1374c3886427411c44979" // 0x90
4990 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4991 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4992 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4993 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4994 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4995 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4996 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4997 "55" // 0x101
4998 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4999 "02820100" // INTEGER length 0x100 (privateExponent) value...
5000 "431447b6251908112b1ee76f99f3711a" // 0x10
5001 "52b6630960046c2de70de188d833f8b8" // 0x20
5002 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
5003 "641f7fe24f14c67a88959bdb27766df9" // 0x40
5004 "e710b630a03adc683b5d2c43080e52be" // 0x50
5005 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
5006 "822bccff087d63c940ba8a45f670feb2" // 0x70
5007 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
5008 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
5009 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
5010 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
5011 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
5012 "52659d5a5ba05b663737a8696281865b" // 0xd0
5013 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
5014 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
5015 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5016 "028181" // INTEGER length 0x81 (prime1) value...
5017 "00de392e18d682c829266cc3454e1d61" // 0x10
5018 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5019 "ff841be5bac82a164c5970007047b8c5" // 0x30
5020 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5021 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5022 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5023 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5024 "9e91346130748a6e3c124f9149d71c74" // 0x80
5025 "35"
5026 "028181" // INTEGER length 0x81 (prime2) value...
5027 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5028 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5029 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5030 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5031 "9ed39a2d934c880440aed8832f984316" // 0x50
5032 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5033 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5034 "b880677c068e1be936e81288815252a8" // 0x80
5035 "a1"
5036 "028180" // INTEGER length 0x80 (exponent1) value...
5037 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5038 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5039 "5a063212a4f105a3764743e53281988a" // 0x30
5040 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5041 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5042 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5043 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5044 "4719d6e2b9439823719cd08bcd031781" // 0x80
5045 "028181" // INTEGER length 0x81 (exponent2) value...
5046 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5047 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5048 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5049 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5050 "1254186af30b22c10582a8a43e34fe94" // 0x50
5051 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5052 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5053 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5054 "61"
5055 "028181" // INTEGER length 0x81 (coefficient) value...
5056 "00c931617c77829dfb1270502be9195c" // 0x10
5057 "8f2830885f57dba869536811e6864236" // 0x20
5058 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5059 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5060 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5061 "959356210723287b0affcc9f727044d4" // 0x60
5062 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5063 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5064 "22"
5065 // } SEQUENCE
5066 // } SEQUENCE ()
5067);
Selene Huang31ab4042020-04-29 04:22:39 -07005068
5069string zero_masking_key =
5070 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5071string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5072
5073class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5074
5075TEST_P(ImportWrappedKeyTest, Success) {
5076 auto wrapping_key_desc = AuthorizationSetBuilder()
5077 .RsaEncryptionKey(2048, 65537)
5078 .Digest(Digest::SHA_2_256)
5079 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005080 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5081 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005082
5083 ASSERT_EQ(ErrorCode::OK,
5084 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5085 AuthorizationSetBuilder()
5086 .Digest(Digest::SHA_2_256)
5087 .Padding(PaddingMode::RSA_OAEP)));
5088
5089 string message = "Hello World!";
5090 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5091 string ciphertext = EncryptMessage(message, params);
5092 string plaintext = DecryptMessage(ciphertext, params);
5093 EXPECT_EQ(message, plaintext);
5094}
5095
David Drysdaled2cc8c22021-04-15 13:29:45 +01005096/*
5097 * ImportWrappedKeyTest.SuccessSidsIgnored
5098 *
5099 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5100 * include Tag:USER_SECURE_ID.
5101 */
5102TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5103 auto wrapping_key_desc = AuthorizationSetBuilder()
5104 .RsaEncryptionKey(2048, 65537)
5105 .Digest(Digest::SHA_2_256)
5106 .Padding(PaddingMode::RSA_OAEP)
5107 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5108 .SetDefaultValidity();
5109
5110 int64_t password_sid = 42;
5111 int64_t biometric_sid = 24;
5112 ASSERT_EQ(ErrorCode::OK,
5113 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5114 AuthorizationSetBuilder()
5115 .Digest(Digest::SHA_2_256)
5116 .Padding(PaddingMode::RSA_OAEP),
5117 password_sid, biometric_sid));
5118
5119 string message = "Hello World!";
5120 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5121 string ciphertext = EncryptMessage(message, params);
5122 string plaintext = DecryptMessage(ciphertext, params);
5123 EXPECT_EQ(message, plaintext);
5124}
5125
Selene Huang31ab4042020-04-29 04:22:39 -07005126TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5127 auto wrapping_key_desc = AuthorizationSetBuilder()
5128 .RsaEncryptionKey(2048, 65537)
5129 .Digest(Digest::SHA_2_256)
5130 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005131 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5132 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005133
5134 ASSERT_EQ(ErrorCode::OK,
5135 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5136 AuthorizationSetBuilder()
5137 .Digest(Digest::SHA_2_256)
5138 .Padding(PaddingMode::RSA_OAEP)));
5139}
5140
5141TEST_P(ImportWrappedKeyTest, WrongMask) {
5142 auto wrapping_key_desc = AuthorizationSetBuilder()
5143 .RsaEncryptionKey(2048, 65537)
5144 .Digest(Digest::SHA_2_256)
5145 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005146 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5147 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005148
5149 ASSERT_EQ(
5150 ErrorCode::VERIFICATION_FAILED,
5151 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5152 AuthorizationSetBuilder()
5153 .Digest(Digest::SHA_2_256)
5154 .Padding(PaddingMode::RSA_OAEP)));
5155}
5156
5157TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5158 auto wrapping_key_desc = AuthorizationSetBuilder()
5159 .RsaEncryptionKey(2048, 65537)
5160 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005161 .Padding(PaddingMode::RSA_OAEP)
5162 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005163
5164 ASSERT_EQ(
5165 ErrorCode::INCOMPATIBLE_PURPOSE,
5166 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5167 AuthorizationSetBuilder()
5168 .Digest(Digest::SHA_2_256)
5169 .Padding(PaddingMode::RSA_OAEP)));
5170}
5171
David Drysdaled2cc8c22021-04-15 13:29:45 +01005172TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5173 auto wrapping_key_desc = AuthorizationSetBuilder()
5174 .RsaEncryptionKey(2048, 65537)
5175 .Digest(Digest::SHA_2_256)
5176 .Padding(PaddingMode::RSA_PSS)
5177 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5178 .SetDefaultValidity();
5179
5180 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5181 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5182 AuthorizationSetBuilder()
5183 .Digest(Digest::SHA_2_256)
5184 .Padding(PaddingMode::RSA_OAEP)));
5185}
5186
5187TEST_P(ImportWrappedKeyTest, WrongDigest) {
5188 auto wrapping_key_desc = AuthorizationSetBuilder()
5189 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005190 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005191 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005192 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5193 .SetDefaultValidity();
5194
5195 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5196 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5197 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005198 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005199 .Padding(PaddingMode::RSA_OAEP)));
5200}
5201
Selene Huang31ab4042020-04-29 04:22:39 -07005202INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5203
5204typedef KeyMintAidlTestBase EncryptionOperationsTest;
5205
5206/*
5207 * EncryptionOperationsTest.RsaNoPaddingSuccess
5208 *
David Drysdale59cae642021-05-12 13:52:03 +01005209 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005210 */
5211TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005212 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005213 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5215 .Authorization(TAG_NO_AUTH_REQUIRED)
5216 .RsaEncryptionKey(2048, exponent)
5217 .Padding(PaddingMode::NONE)
5218 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005219
David Drysdaled2cc8c22021-04-15 13:29:45 +01005220 string message = string(2048 / 8, 'a');
5221 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005222 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005223 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005224
David Drysdale59cae642021-05-12 13:52:03 +01005225 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005226 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005227
David Drysdaled2cc8c22021-04-15 13:29:45 +01005228 // Unpadded RSA is deterministic
5229 EXPECT_EQ(ciphertext1, ciphertext2);
5230
5231 CheckedDeleteKey();
5232 }
Selene Huang31ab4042020-04-29 04:22:39 -07005233}
5234
5235/*
5236 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5237 *
David Drysdale59cae642021-05-12 13:52:03 +01005238 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005239 */
5240TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5242 .Authorization(TAG_NO_AUTH_REQUIRED)
5243 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005244 .Padding(PaddingMode::NONE)
5245 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005246
5247 string message = "1";
5248 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5249
David Drysdale59cae642021-05-12 13:52:03 +01005250 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005251 EXPECT_EQ(2048U / 8, ciphertext.size());
5252
5253 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5254 string plaintext = DecryptMessage(ciphertext, params);
5255
5256 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005257}
5258
5259/*
Selene Huang31ab4042020-04-29 04:22:39 -07005260 * EncryptionOperationsTest.RsaOaepSuccess
5261 *
David Drysdale59cae642021-05-12 13:52:03 +01005262 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005263 */
5264TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5265 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Prashant Patil2114dca2023-09-21 14:57:10 +00005266 auto mgf_digest = vector{Digest::SHA1};
Selene Huang31ab4042020-04-29 04:22:39 -07005267
5268 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5270 .Authorization(TAG_NO_AUTH_REQUIRED)
5271 .RsaEncryptionKey(key_size, 65537)
5272 .Padding(PaddingMode::RSA_OAEP)
5273 .Digest(digests)
Prashant Patil2114dca2023-09-21 14:57:10 +00005274 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005275 .SetDefaultValidity()));
5276
5277 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005278 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Selene Huang31ab4042020-04-29 04:22:39 -07005279
5280 string message = "Hello";
5281
5282 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005283 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5284
5285 auto params = AuthorizationSetBuilder()
5286 .Digest(digest)
5287 .Padding(PaddingMode::RSA_OAEP)
5288 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5289 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005290 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5291 EXPECT_EQ(key_size / 8, ciphertext1.size());
5292
David Drysdale59cae642021-05-12 13:52:03 +01005293 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005294 EXPECT_EQ(key_size / 8, ciphertext2.size());
5295
5296 // OAEP randomizes padding so every result should be different (with astronomically high
5297 // probability).
5298 EXPECT_NE(ciphertext1, ciphertext2);
5299
5300 string plaintext1 = DecryptMessage(ciphertext1, params);
5301 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5302 string plaintext2 = DecryptMessage(ciphertext2, params);
5303 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5304
5305 // Decrypting corrupted ciphertext should fail.
5306 size_t offset_to_corrupt = random() % ciphertext1.size();
5307 char corrupt_byte;
5308 do {
5309 corrupt_byte = static_cast<char>(random() % 256);
5310 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5311 ciphertext1[offset_to_corrupt] = corrupt_byte;
5312
5313 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5314 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005315 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005316 EXPECT_EQ(0U, result.size());
5317 }
5318}
5319
5320/*
5321 * EncryptionOperationsTest.RsaOaepInvalidDigest
5322 *
David Drysdale59cae642021-05-12 13:52:03 +01005323 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005324 * without a digest.
5325 */
5326TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5327 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5328 .Authorization(TAG_NO_AUTH_REQUIRED)
5329 .RsaEncryptionKey(2048, 65537)
5330 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005331 .Digest(Digest::NONE)
5332 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005333
5334 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005335 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005336}
5337
5338/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005339 * EncryptionOperationsTest.RsaOaepInvalidPadding
5340 *
David Drysdale59cae642021-05-12 13:52:03 +01005341 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005342 * with a padding value that is only suitable for signing/verifying.
5343 */
5344TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5345 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5346 .Authorization(TAG_NO_AUTH_REQUIRED)
5347 .RsaEncryptionKey(2048, 65537)
5348 .Padding(PaddingMode::RSA_PSS)
5349 .Digest(Digest::NONE)
5350 .SetDefaultValidity()));
5351
5352 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005353 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005354}
5355
5356/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005357 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005358 *
David Drysdale59cae642021-05-12 13:52:03 +01005359 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005360 * with a different digest than was used to encrypt.
5361 */
5362TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005363 if (SecLevel() == SecurityLevel::STRONGBOX) {
5364 GTEST_SKIP() << "Test not applicable to StrongBox device";
5365 }
Selene Huang31ab4042020-04-29 04:22:39 -07005366
5367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5368 .Authorization(TAG_NO_AUTH_REQUIRED)
5369 .RsaEncryptionKey(1024, 65537)
5370 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005371 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5372 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005373 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005374 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005375 message,
5376 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5377
5378 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5379 .Digest(Digest::SHA_2_256)
5380 .Padding(PaddingMode::RSA_OAEP)));
5381 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005382 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005383 EXPECT_EQ(0U, result.size());
5384}
5385
5386/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005387 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5388 *
David Drysdale59cae642021-05-12 13:52:03 +01005389 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005390 * digests.
5391 */
5392TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5393 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5394
5395 size_t key_size = 2048; // Need largish key for SHA-512 test.
5396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5397 .OaepMGFDigest(digests)
5398 .Authorization(TAG_NO_AUTH_REQUIRED)
5399 .RsaEncryptionKey(key_size, 65537)
5400 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005401 .Digest(Digest::SHA_2_256)
5402 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005403 if (AidlVersion() >= 3) {
5404 std::vector<Digest> mgf1DigestsInAuths;
5405 mgf1DigestsInAuths.reserve(digests.size());
5406 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5407 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5408 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5409 KeyParameterValue value = param.value;
5410 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5411 }
5412 });
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005413
Prashant Patil2114dca2023-09-21 14:57:10 +00005414 std::sort(digests.begin(), digests.end());
5415 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5416 EXPECT_EQ(digests, mgf1DigestsInAuths);
5417 }
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005418 string message = "Hello";
5419
5420 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005421 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005422 auto params = AuthorizationSetBuilder()
5423 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5424 .Digest(Digest::SHA_2_256)
5425 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005426 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005427 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5428 EXPECT_EQ(key_size / 8, ciphertext1.size());
5429
David Drysdale59cae642021-05-12 13:52:03 +01005430 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005431 EXPECT_EQ(key_size / 8, ciphertext2.size());
5432
5433 // OAEP randomizes padding so every result should be different (with astronomically high
5434 // probability).
5435 EXPECT_NE(ciphertext1, ciphertext2);
5436
5437 string plaintext1 = DecryptMessage(ciphertext1, params);
5438 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5439 string plaintext2 = DecryptMessage(ciphertext2, params);
5440 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5441
5442 // Decrypting corrupted ciphertext should fail.
5443 size_t offset_to_corrupt = random() % ciphertext1.size();
5444 char corrupt_byte;
5445 do {
5446 corrupt_byte = static_cast<char>(random() % 256);
5447 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5448 ciphertext1[offset_to_corrupt] = corrupt_byte;
5449
5450 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5451 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005452 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005453 EXPECT_EQ(0U, result.size());
5454 }
5455}
5456
5457/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005458 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5459 *
5460 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5461 * specified, defaulting to SHA-1.
5462 */
5463TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5464 size_t key_size = 2048;
5465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5466 .Authorization(TAG_NO_AUTH_REQUIRED)
5467 .RsaEncryptionKey(key_size, 65537)
5468 .Padding(PaddingMode::RSA_OAEP)
5469 .Digest(Digest::SHA_2_256)
5470 .SetDefaultValidity()));
5471
Prashant Patil2114dca2023-09-21 14:57:10 +00005472 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005473 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005474 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005475
David Drysdaleae3727b2021-11-11 09:00:14 +00005476 // Do local RSA encryption using the default MGF digest of SHA-1.
5477 string message = "Hello";
5478 auto params =
5479 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5480 string ciphertext = LocalRsaEncryptMessage(message, params);
5481 EXPECT_EQ(key_size / 8, ciphertext.size());
5482
5483 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5484 string plaintext = DecryptMessage(ciphertext, params);
5485 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5486
5487 // Decrypting corrupted ciphertext should fail.
5488 size_t offset_to_corrupt = random() % ciphertext.size();
5489 char corrupt_byte;
5490 do {
5491 corrupt_byte = static_cast<char>(random() % 256);
5492 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5493 ciphertext[offset_to_corrupt] = corrupt_byte;
5494
5495 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5496 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005497 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
David Drysdaleae3727b2021-11-11 09:00:14 +00005498 EXPECT_EQ(0U, result.size());
5499}
5500
5501/*
5502 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5503 *
5504 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5505 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5506 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5507 */
5508TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5509 size_t key_size = 2048;
Prashant Patil2114dca2023-09-21 14:57:10 +00005510 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5512 .Authorization(TAG_NO_AUTH_REQUIRED)
Prashant Patil2114dca2023-09-21 14:57:10 +00005513 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005514 .RsaEncryptionKey(key_size, 65537)
5515 .Padding(PaddingMode::RSA_OAEP)
5516 .Digest(Digest::SHA_2_256)
5517 .SetDefaultValidity()));
5518
5519 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005520 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
5521 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005522 // Make sure default mgf-digest is not included in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005523 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
David Drysdaleae3727b2021-11-11 09:00:14 +00005524
5525 // Do local RSA encryption using the default MGF digest of SHA-1.
5526 string message = "Hello";
5527 auto params =
5528 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5529 string ciphertext = LocalRsaEncryptMessage(message, params);
5530 EXPECT_EQ(key_size / 8, ciphertext.size());
5531
5532 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5533 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5534 // is checked against those values, and found absent.
5535 auto result = Begin(KeyPurpose::DECRYPT, params);
5536 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5537 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5538}
5539
5540/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005541 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5542 *
David Drysdale59cae642021-05-12 13:52:03 +01005543 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005544 * with incompatible MGF digest.
5545 */
5546TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005547 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005549 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005550 .Authorization(TAG_NO_AUTH_REQUIRED)
5551 .RsaEncryptionKey(2048, 65537)
5552 .Padding(PaddingMode::RSA_OAEP)
5553 .Digest(Digest::SHA_2_256)
5554 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005555
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005556 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005557 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005558
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005559 string message = "Hello World!";
5560
5561 auto params = AuthorizationSetBuilder()
5562 .Padding(PaddingMode::RSA_OAEP)
5563 .Digest(Digest::SHA_2_256)
5564 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005565 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005566}
5567
5568/*
5569 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5570 *
5571 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5572 * with unsupported MGF digest.
5573 */
5574TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005575 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005576 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005577 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005578 .Authorization(TAG_NO_AUTH_REQUIRED)
5579 .RsaEncryptionKey(2048, 65537)
5580 .Padding(PaddingMode::RSA_OAEP)
5581 .Digest(Digest::SHA_2_256)
5582 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005583
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005584 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005585 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005586
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005587 string message = "Hello World!";
5588
5589 auto params = AuthorizationSetBuilder()
5590 .Padding(PaddingMode::RSA_OAEP)
5591 .Digest(Digest::SHA_2_256)
5592 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005593 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005594}
5595
5596/*
Selene Huang31ab4042020-04-29 04:22:39 -07005597 * EncryptionOperationsTest.RsaPkcs1Success
5598 *
5599 * Verifies that RSA PKCS encryption/decrypts works.
5600 */
5601TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5603 .Authorization(TAG_NO_AUTH_REQUIRED)
5604 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005605 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5606 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005607
5608 string message = "Hello World!";
5609 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005610 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005611 EXPECT_EQ(2048U / 8, ciphertext1.size());
5612
David Drysdale59cae642021-05-12 13:52:03 +01005613 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005614 EXPECT_EQ(2048U / 8, ciphertext2.size());
5615
5616 // PKCS1 v1.5 randomizes padding so every result should be different.
5617 EXPECT_NE(ciphertext1, ciphertext2);
5618
5619 string plaintext = DecryptMessage(ciphertext1, params);
5620 EXPECT_EQ(message, plaintext);
5621
5622 // Decrypting corrupted ciphertext should fail.
5623 size_t offset_to_corrupt = random() % ciphertext1.size();
5624 char corrupt_byte;
5625 do {
5626 corrupt_byte = static_cast<char>(random() % 256);
5627 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5628 ciphertext1[offset_to_corrupt] = corrupt_byte;
5629
5630 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5631 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005632 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005633 EXPECT_EQ(0U, result.size());
5634}
5635
5636/*
Selene Huang31ab4042020-04-29 04:22:39 -07005637 * EncryptionOperationsTest.EcdsaEncrypt
5638 *
5639 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5640 */
5641TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5642 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5643 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005644 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005645 .Digest(Digest::NONE)
5646 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005647 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5648 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5649 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5650}
5651
5652/*
5653 * EncryptionOperationsTest.HmacEncrypt
5654 *
5655 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5656 */
5657TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5659 .Authorization(TAG_NO_AUTH_REQUIRED)
5660 .HmacKey(128)
5661 .Digest(Digest::SHA_2_256)
5662 .Padding(PaddingMode::NONE)
5663 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5664 auto params = AuthorizationSetBuilder()
5665 .Digest(Digest::SHA_2_256)
5666 .Padding(PaddingMode::NONE)
5667 .Authorization(TAG_MAC_LENGTH, 128);
5668 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5669 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5670}
5671
5672/*
5673 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5674 *
5675 * Verifies that AES ECB mode works.
5676 */
5677TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5679 .Authorization(TAG_NO_AUTH_REQUIRED)
5680 .AesEncryptionKey(128)
5681 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5682 .Padding(PaddingMode::NONE)));
5683
5684 ASSERT_GT(key_blob_.size(), 0U);
5685 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5686
5687 // Two-block message.
5688 string message = "12345678901234567890123456789012";
5689 string ciphertext1 = EncryptMessage(message, params);
5690 EXPECT_EQ(message.size(), ciphertext1.size());
5691
5692 string ciphertext2 = EncryptMessage(string(message), params);
5693 EXPECT_EQ(message.size(), ciphertext2.size());
5694
5695 // ECB is deterministic.
5696 EXPECT_EQ(ciphertext1, ciphertext2);
5697
5698 string plaintext = DecryptMessage(ciphertext1, params);
5699 EXPECT_EQ(message, plaintext);
5700}
5701
5702/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005703 * EncryptionOperationsTest.AesEcbUnknownTag
5704 *
5705 * Verifies that AES ECB operations ignore unknown tags.
5706 */
5707TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5708 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5709 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5710 KeyParameter unknown_param;
5711 unknown_param.tag = unknown_tag;
5712
5713 vector<KeyCharacteristics> key_characteristics;
5714 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5715 .Authorization(TAG_NO_AUTH_REQUIRED)
5716 .AesEncryptionKey(128)
5717 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5718 .Padding(PaddingMode::NONE)
5719 .Authorization(unknown_param),
5720 &key_blob_, &key_characteristics));
5721 ASSERT_GT(key_blob_.size(), 0U);
5722
5723 // Unknown tags should not be returned in key characteristics.
5724 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5725 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5726 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5727 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5728
5729 // Encrypt without mentioning the unknown parameter.
5730 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5731 string message = "12345678901234567890123456789012";
5732 string ciphertext = EncryptMessage(message, params);
5733 EXPECT_EQ(message.size(), ciphertext.size());
5734
5735 // Decrypt including the unknown parameter.
5736 auto decrypt_params = AuthorizationSetBuilder()
5737 .BlockMode(BlockMode::ECB)
5738 .Padding(PaddingMode::NONE)
5739 .Authorization(unknown_param);
5740 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5741 EXPECT_EQ(message, plaintext);
5742}
5743
5744/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005745 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005746 *
5747 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5748 */
5749TEST_P(EncryptionOperationsTest, AesWrongMode) {
5750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5751 .Authorization(TAG_NO_AUTH_REQUIRED)
5752 .AesEncryptionKey(128)
5753 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5754 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005755 ASSERT_GT(key_blob_.size(), 0U);
5756
Selene Huang31ab4042020-04-29 04:22:39 -07005757 EXPECT_EQ(
5758 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5759 Begin(KeyPurpose::ENCRYPT,
5760 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5761}
5762
5763/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005764 * EncryptionOperationsTest.AesWrongPadding
5765 *
5766 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5767 */
5768TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5770 .Authorization(TAG_NO_AUTH_REQUIRED)
5771 .AesEncryptionKey(128)
5772 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5773 .Padding(PaddingMode::NONE)));
5774 ASSERT_GT(key_blob_.size(), 0U);
5775
5776 EXPECT_EQ(
5777 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5778 Begin(KeyPurpose::ENCRYPT,
5779 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5780}
5781
5782/*
5783 * EncryptionOperationsTest.AesInvalidParams
5784 *
5785 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5786 */
5787TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5789 .Authorization(TAG_NO_AUTH_REQUIRED)
5790 .AesEncryptionKey(128)
5791 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5792 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5793 .Padding(PaddingMode::NONE)
5794 .Padding(PaddingMode::PKCS7)));
5795 ASSERT_GT(key_blob_.size(), 0U);
5796
5797 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5798 .BlockMode(BlockMode::CBC)
5799 .BlockMode(BlockMode::ECB)
5800 .Padding(PaddingMode::NONE));
5801 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5802 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5803
5804 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5805 .BlockMode(BlockMode::ECB)
5806 .Padding(PaddingMode::NONE)
5807 .Padding(PaddingMode::PKCS7));
5808 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5809 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5810}
5811
5812/*
Selene Huang31ab4042020-04-29 04:22:39 -07005813 * EncryptionOperationsTest.AesWrongPurpose
5814 *
5815 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5816 * specified.
5817 */
5818TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5819 auto err = GenerateKey(AuthorizationSetBuilder()
5820 .Authorization(TAG_NO_AUTH_REQUIRED)
5821 .AesKey(128)
5822 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5823 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5824 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5825 .Padding(PaddingMode::NONE));
5826 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5827 ASSERT_GT(key_blob_.size(), 0U);
5828
5829 err = Begin(KeyPurpose::DECRYPT, 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 CheckedDeleteKey();
5836
5837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5838 .Authorization(TAG_NO_AUTH_REQUIRED)
5839 .AesKey(128)
5840 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5841 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5842 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5843 .Padding(PaddingMode::NONE)));
5844
5845 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5846 .BlockMode(BlockMode::GCM)
5847 .Padding(PaddingMode::NONE)
5848 .Authorization(TAG_MAC_LENGTH, 128));
5849 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5850}
5851
5852/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005853 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005854 *
5855 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5856 * multiple of the block size and no padding is specified.
5857 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005858TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5859 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005860 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5862 .Authorization(TAG_NO_AUTH_REQUIRED)
5863 .AesEncryptionKey(128)
5864 .Authorization(TAG_BLOCK_MODE, blockMode)
5865 .Padding(PaddingMode::NONE)));
5866 // Message is slightly shorter than two blocks.
5867 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005868
David Drysdaled2cc8c22021-04-15 13:29:45 +01005869 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5870 AuthorizationSet out_params;
5871 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5872 string ciphertext;
5873 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5874 EXPECT_EQ(0U, ciphertext.size());
5875
5876 CheckedDeleteKey();
5877 }
Selene Huang31ab4042020-04-29 04:22:39 -07005878}
5879
5880/*
5881 * EncryptionOperationsTest.AesEcbPkcs7Padding
5882 *
5883 * Verifies that AES PKCS7 padding works for any message length.
5884 */
5885TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5887 .Authorization(TAG_NO_AUTH_REQUIRED)
5888 .AesEncryptionKey(128)
5889 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5890 .Padding(PaddingMode::PKCS7)));
5891
5892 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5893
5894 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005895 for (size_t i = 0; i <= 48; i++) {
5896 SCOPED_TRACE(testing::Message() << "i = " << i);
5897 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5898 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005899 string ciphertext = EncryptMessage(message, params);
5900 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5901 string plaintext = DecryptMessage(ciphertext, params);
5902 EXPECT_EQ(message, plaintext);
5903 }
5904}
5905
5906/*
5907 * EncryptionOperationsTest.AesEcbWrongPadding
5908 *
5909 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5910 * specified.
5911 */
5912TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5913 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5914 .Authorization(TAG_NO_AUTH_REQUIRED)
5915 .AesEncryptionKey(128)
5916 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5917 .Padding(PaddingMode::NONE)));
5918
5919 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5920
5921 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005922 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005923 string message(i, 'a');
5924 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5925 }
5926}
5927
5928/*
5929 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5930 *
5931 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5932 */
5933TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5934 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5935 .Authorization(TAG_NO_AUTH_REQUIRED)
5936 .AesEncryptionKey(128)
5937 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5938 .Padding(PaddingMode::PKCS7)));
5939
5940 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5941
5942 string message = "a";
5943 string ciphertext = EncryptMessage(message, params);
5944 EXPECT_EQ(16U, ciphertext.size());
5945 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005946
Seth Moore7a55ae32021-06-23 14:28:11 -07005947 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5948 ++ciphertext[ciphertext.size() / 2];
5949
5950 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5951 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005952 ErrorCode error = Finish(ciphertext, &plaintext);
5953 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005954 // This is the expected error, we can exit the test now.
5955 return;
5956 } else {
5957 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005958 ASSERT_EQ(error, ErrorCode::OK)
5959 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005960 }
5961 }
5962 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005963}
5964
David Drysdaleb8093292022-04-08 12:22:35 +01005965/*
5966 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5967 *
5968 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5969 */
5970TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5971 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5972 .Authorization(TAG_NO_AUTH_REQUIRED)
5973 .AesEncryptionKey(128)
5974 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5975 .Padding(PaddingMode::PKCS7)));
5976
5977 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5978
5979 string message = "a";
5980 string ciphertext = EncryptMessage(message, params);
5981 EXPECT_EQ(16U, ciphertext.size());
5982 EXPECT_NE(ciphertext, message);
5983
5984 // Shorten the ciphertext.
5985 ciphertext.resize(ciphertext.size() - 1);
5986 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5987 string plaintext;
5988 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5989}
5990
Selene Huang31ab4042020-04-29 04:22:39 -07005991vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5992 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005993 EXPECT_TRUE(iv);
5994 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005995}
5996
5997/*
5998 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5999 *
6000 * Verifies that AES CTR mode works.
6001 */
6002TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
6003 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6004 .Authorization(TAG_NO_AUTH_REQUIRED)
6005 .AesEncryptionKey(128)
6006 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6007 .Padding(PaddingMode::NONE)));
6008
6009 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6010
6011 string message = "123";
6012 AuthorizationSet out_params;
6013 string ciphertext1 = EncryptMessage(message, params, &out_params);
6014 vector<uint8_t> iv1 = CopyIv(out_params);
6015 EXPECT_EQ(16U, iv1.size());
6016
6017 EXPECT_EQ(message.size(), ciphertext1.size());
6018
6019 out_params.Clear();
6020 string ciphertext2 = EncryptMessage(message, params, &out_params);
6021 vector<uint8_t> iv2 = CopyIv(out_params);
6022 EXPECT_EQ(16U, iv2.size());
6023
6024 // IVs should be random, so ciphertexts should differ.
6025 EXPECT_NE(ciphertext1, ciphertext2);
6026
6027 auto params_iv1 =
6028 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6029 auto params_iv2 =
6030 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6031
6032 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6033 EXPECT_EQ(message, plaintext);
6034 plaintext = DecryptMessage(ciphertext2, params_iv2);
6035 EXPECT_EQ(message, plaintext);
6036
6037 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6038 plaintext = DecryptMessage(ciphertext1, params_iv2);
6039 EXPECT_NE(message, plaintext);
6040 plaintext = DecryptMessage(ciphertext2, params_iv1);
6041 EXPECT_NE(message, plaintext);
6042}
6043
6044/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306045 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006046 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306047 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006048 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306049TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6050 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6051}
Selene Huang31ab4042020-04-29 04:22:39 -07006052
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306053/*
6054 * EncryptionOperationsTest.AesCbcIncremental
6055 *
6056 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6057 */
6058TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6059 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6060}
Selene Huang31ab4042020-04-29 04:22:39 -07006061
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306062/*
6063 * EncryptionOperationsTest.AesCtrIncremental
6064 *
6065 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6066 */
6067TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6068 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6069}
Selene Huang31ab4042020-04-29 04:22:39 -07006070
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306071/*
6072 * EncryptionOperationsTest.AesGcmIncremental
6073 *
6074 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6075 */
6076TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6077 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006078}
6079
Prashant Patildd5f7f02022-07-06 18:58:07 +00006080/*
6081 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6082 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6083 */
6084TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6085 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6086 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6087 string kat_plaintext =
6088 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6089 "809FFF37081C22EF278F896AB213A2A631");
6090 string kat_ciphertext =
6091 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6092 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6093 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6094 kat_ciphertext);
6095}
6096
6097/*
6098 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6099 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6100 */
6101TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6102 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6103 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6104 string kat_plaintext =
6105 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6106 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6107 string kat_ciphertext =
6108 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6109 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6110 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6111 kat_plaintext, kat_ciphertext);
6112}
6113
6114/*
6115 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6116 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6117 */
6118TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6119 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6120 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6121 string kat_plaintext =
6122 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6123 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6124 string kat_ciphertext =
6125 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6126 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6127 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6128 kat_ciphertext);
6129}
6130
6131/*
6132 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6133 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6134 */
6135TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6136 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6137 string kat_plaintext =
6138 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6139 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6140 string kat_ciphertext =
6141 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6142 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6143 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6144 kat_ciphertext);
6145}
6146
6147/*
6148 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6149 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6150 */
6151TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6152 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6153 string kat_plaintext =
6154 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6155 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6156 string kat_ciphertext =
6157 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6158 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6159 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6160 kat_ciphertext);
6161}
6162
6163/*
6164 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6165 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6166 */
6167TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6168 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6169 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6170 string kat_plaintext =
6171 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6172 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6173 string kat_ciphertext =
6174 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6175 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6176 "bdfcc0cba0");
6177
6178 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6179 kat_ciphertext);
6180}
6181
6182/*
6183 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6184 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6185 */
6186TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6187 if (SecLevel() == SecurityLevel::STRONGBOX) {
6188 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6189 }
6190 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6191 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6192 string kat_plaintext =
6193 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6194 "167f2497c994bd496eb80bfb2ba2c9d5af");
6195 string kat_ciphertext =
6196 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6197 "72c134552f3a138e726fbe493b3a839598");
6198 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6199 kat_ciphertext);
6200}
6201
6202/*
6203 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6204 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6205 */
6206TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6207 if (SecLevel() == SecurityLevel::STRONGBOX) {
6208 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6209 }
6210 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6211 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6212 string kat_plaintext =
6213 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6214 "b170");
6215 string kat_ciphertext =
6216 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6217 "4e3884138ff403a41fd99818708ada301c");
6218 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6219 kat_plaintext, kat_ciphertext);
6220}
6221
6222/*
6223 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6224 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6225 */
6226TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6227 if (SecLevel() == SecurityLevel::STRONGBOX) {
6228 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6229 }
6230 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6231 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6232 string kat_plaintext =
6233 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6234 "28091e09cdbbd3b42b");
6235 string kat_ciphertext =
6236 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6237 "2ae0f90f0c19f42b4a");
6238 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6239 kat_ciphertext);
6240}
6241
6242/*
6243 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6244 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6245 */
6246TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6247 if (SecLevel() == SecurityLevel::STRONGBOX) {
6248 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6249 }
6250 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6251 string kat_plaintext =
6252 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6253 "44ab");
6254 string kat_ciphertext =
6255 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6256 "2453");
6257 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6258 kat_ciphertext);
6259}
6260
6261/*
6262 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6263 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6264 */
6265TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6266 if (SecLevel() == SecurityLevel::STRONGBOX) {
6267 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6268 }
6269 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6270 string kat_plaintext =
6271 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6272 "e2c7");
6273 string kat_ciphertext =
6274 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6275 "bb7e3a889dd4a9589098b44acf1056e7aa");
6276 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6277 kat_ciphertext);
6278}
6279
6280/*
6281 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6282 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6283 */
6284TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6285 if (SecLevel() == SecurityLevel::STRONGBOX) {
6286 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6287 }
6288 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6289 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6290 string kat_plaintext =
6291 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6292 "ff52");
6293 string kat_ciphertext =
6294 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6295 "1413ad70fb0e1970669095ad77ebb5974ae8");
6296
6297 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6298 kat_ciphertext);
6299}
6300
6301/*
6302 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6303 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6304 */
6305TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6306 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6307 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6308 string kat_plaintext =
6309 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6310 "494cb53caca353e4b637ba05687be20f8d");
6311 string kat_ciphertext =
6312 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6313 "6047da1e4fd7c4e1cf2656097f75ae8685");
6314 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6315 kat_ciphertext);
6316}
6317
6318/*
6319 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6320 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6321 */
6322TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6323 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6324 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6325 string kat_plaintext =
6326 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6327 "2545a82b73c48078b9dae62261c65909");
6328 string kat_ciphertext =
6329 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6330 "9403a71987b95124073d69f2a3cb95b0ab");
6331 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6332 kat_plaintext, kat_ciphertext);
6333}
6334
6335/*
6336 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6337 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6338 */
6339TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6340 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6341 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6342 string kat_plaintext =
6343 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6344 "1f6db3c884");
6345 string kat_ciphertext =
6346 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6347 "a7be30d4c3");
6348 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6349 kat_ciphertext);
6350}
6351
6352/*
6353 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6354 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6355 */
6356TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6357 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6358 string kat_plaintext =
6359 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6360 "31a476d6806b8116089c6ec50bb543200f");
6361 string kat_ciphertext =
6362 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6363 "c83e377faf246288931136bef2a07c0be4");
6364 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6365 kat_ciphertext);
6366}
6367
6368/*
6369 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6370 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6371 */
6372TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6373 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6374 string kat_plaintext =
6375 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6376 "6f");
6377 string kat_ciphertext =
6378 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6379 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6380 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6381 kat_ciphertext);
6382}
6383
6384/*
6385 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6386 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6387 */
6388TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6389 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6390 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6391 string kat_plaintext =
6392 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6393 "f0");
6394 string kat_ciphertext =
6395 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6396 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6397
6398 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6399 kat_ciphertext);
6400}
6401
Selene Huang31ab4042020-04-29 04:22:39 -07006402struct AesCtrSp80038aTestVector {
6403 const char* key;
6404 const char* nonce;
6405 const char* plaintext;
6406 const char* ciphertext;
6407};
6408
6409// These test vectors are taken from
6410// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6411static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6412 // AES-128
6413 {
6414 "2b7e151628aed2a6abf7158809cf4f3c",
6415 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6416 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6417 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6418 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6419 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6420 },
6421 // AES-192
6422 {
6423 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6424 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6425 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6426 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6427 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6428 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6429 },
6430 // AES-256
6431 {
6432 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6433 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6434 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6435 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6436 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6437 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6438 },
6439};
6440
6441/*
6442 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6443 *
6444 * Verifies AES CTR implementation against SP800-38A test vectors.
6445 */
6446TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6447 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6448 for (size_t i = 0; i < 3; i++) {
6449 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6450 const string key = hex2str(test.key);
6451 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6452 InvalidSizes.end())
6453 continue;
6454 const string nonce = hex2str(test.nonce);
6455 const string plaintext = hex2str(test.plaintext);
6456 const string ciphertext = hex2str(test.ciphertext);
6457 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6458 }
6459}
6460
6461/*
6462 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6463 *
6464 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6465 */
6466TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6467 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6468 .Authorization(TAG_NO_AUTH_REQUIRED)
6469 .AesEncryptionKey(128)
6470 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6471 .Padding(PaddingMode::PKCS7)));
6472 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6473 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6474}
6475
6476/*
6477 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6478 *
6479 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6480 */
6481TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6482 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6483 .Authorization(TAG_NO_AUTH_REQUIRED)
6484 .AesEncryptionKey(128)
6485 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6486 .Authorization(TAG_CALLER_NONCE)
6487 .Padding(PaddingMode::NONE)));
6488
6489 auto params = AuthorizationSetBuilder()
6490 .BlockMode(BlockMode::CTR)
6491 .Padding(PaddingMode::NONE)
6492 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6493 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6494
6495 params = AuthorizationSetBuilder()
6496 .BlockMode(BlockMode::CTR)
6497 .Padding(PaddingMode::NONE)
6498 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6499 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6500
6501 params = AuthorizationSetBuilder()
6502 .BlockMode(BlockMode::CTR)
6503 .Padding(PaddingMode::NONE)
6504 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6505 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6506}
6507
6508/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006509 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006510 *
6511 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6512 */
6513TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6515 .Authorization(TAG_NO_AUTH_REQUIRED)
6516 .AesEncryptionKey(128)
6517 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6518 .Padding(PaddingMode::NONE)));
6519 // Two-block message.
6520 string message = "12345678901234567890123456789012";
6521 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6522 AuthorizationSet out_params;
6523 string ciphertext1 = EncryptMessage(message, params, &out_params);
6524 vector<uint8_t> iv1 = CopyIv(out_params);
6525 EXPECT_EQ(message.size(), ciphertext1.size());
6526
6527 out_params.Clear();
6528
6529 string ciphertext2 = EncryptMessage(message, params, &out_params);
6530 vector<uint8_t> iv2 = CopyIv(out_params);
6531 EXPECT_EQ(message.size(), ciphertext2.size());
6532
6533 // IVs should be random, so ciphertexts should differ.
6534 EXPECT_NE(ciphertext1, ciphertext2);
6535
6536 params.push_back(TAG_NONCE, iv1);
6537 string plaintext = DecryptMessage(ciphertext1, params);
6538 EXPECT_EQ(message, plaintext);
6539}
6540
6541/*
Tommy Chiuee705692021-09-23 20:09:13 +08006542 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6543 *
6544 * Verifies that keymaster generates correct output on zero-input with
6545 * NonePadding mode
6546 */
6547TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6549 .Authorization(TAG_NO_AUTH_REQUIRED)
6550 .AesEncryptionKey(128)
6551 .BlockMode(BlockMode::CBC)
6552 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6553
6554 // Zero input message
6555 string message = "";
6556 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006557 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006558 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6559 AuthorizationSet out_params;
6560 string ciphertext1 = EncryptMessage(message, params, &out_params);
6561 vector<uint8_t> iv1 = CopyIv(out_params);
6562 if (padding == PaddingMode::NONE)
6563 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6564 else
6565 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6566
6567 out_params.Clear();
6568
6569 string ciphertext2 = EncryptMessage(message, params, &out_params);
6570 vector<uint8_t> iv2 = CopyIv(out_params);
6571 if (padding == PaddingMode::NONE)
6572 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6573 else
6574 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6575
6576 // IVs should be random
6577 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6578
6579 params.push_back(TAG_NONCE, iv1);
6580 string plaintext = DecryptMessage(ciphertext1, params);
6581 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6582 }
6583}
6584
6585/*
Selene Huang31ab4042020-04-29 04:22:39 -07006586 * EncryptionOperationsTest.AesCallerNonce
6587 *
6588 * Verifies that AES caller-provided nonces work correctly.
6589 */
6590TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6592 .Authorization(TAG_NO_AUTH_REQUIRED)
6593 .AesEncryptionKey(128)
6594 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6595 .Authorization(TAG_CALLER_NONCE)
6596 .Padding(PaddingMode::NONE)));
6597
6598 string message = "12345678901234567890123456789012";
6599
6600 // Don't specify nonce, should get a random one.
6601 AuthorizationSetBuilder params =
6602 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6603 AuthorizationSet out_params;
6604 string ciphertext = EncryptMessage(message, params, &out_params);
6605 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006606 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006607
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006608 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006609 string plaintext = DecryptMessage(ciphertext, params);
6610 EXPECT_EQ(message, plaintext);
6611
6612 // Now specify a nonce, should also work.
6613 params = AuthorizationSetBuilder()
6614 .BlockMode(BlockMode::CBC)
6615 .Padding(PaddingMode::NONE)
6616 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6617 out_params.Clear();
6618 ciphertext = EncryptMessage(message, params, &out_params);
6619
6620 // Decrypt with correct nonce.
6621 plaintext = DecryptMessage(ciphertext, params);
6622 EXPECT_EQ(message, plaintext);
6623
6624 // Try with wrong nonce.
6625 params = AuthorizationSetBuilder()
6626 .BlockMode(BlockMode::CBC)
6627 .Padding(PaddingMode::NONE)
6628 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6629 plaintext = DecryptMessage(ciphertext, params);
6630 EXPECT_NE(message, plaintext);
6631}
6632
6633/*
6634 * EncryptionOperationsTest.AesCallerNonceProhibited
6635 *
6636 * Verifies that caller-provided nonces are not permitted when not specified in the key
6637 * authorizations.
6638 */
6639TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6640 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6641 .Authorization(TAG_NO_AUTH_REQUIRED)
6642 .AesEncryptionKey(128)
6643 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6644 .Padding(PaddingMode::NONE)));
6645
6646 string message = "12345678901234567890123456789012";
6647
6648 // Don't specify nonce, should get a random one.
6649 AuthorizationSetBuilder params =
6650 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6651 AuthorizationSet out_params;
6652 string ciphertext = EncryptMessage(message, params, &out_params);
6653 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006654 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006655
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006656 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006657 string plaintext = DecryptMessage(ciphertext, params);
6658 EXPECT_EQ(message, plaintext);
6659
6660 // Now specify a nonce, should fail
6661 params = AuthorizationSetBuilder()
6662 .BlockMode(BlockMode::CBC)
6663 .Padding(PaddingMode::NONE)
6664 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6665 out_params.Clear();
6666 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6667}
6668
6669/*
6670 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6671 *
6672 * Verifies that AES GCM mode works.
6673 */
6674TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6676 .Authorization(TAG_NO_AUTH_REQUIRED)
6677 .AesEncryptionKey(128)
6678 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6679 .Padding(PaddingMode::NONE)
6680 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6681
6682 string aad = "foobar";
6683 string message = "123456789012345678901234567890123456";
6684
6685 auto begin_params = AuthorizationSetBuilder()
6686 .BlockMode(BlockMode::GCM)
6687 .Padding(PaddingMode::NONE)
6688 .Authorization(TAG_MAC_LENGTH, 128);
6689
Selene Huang31ab4042020-04-29 04:22:39 -07006690 // Encrypt
6691 AuthorizationSet begin_out_params;
6692 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6693 << "Begin encrypt";
6694 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006695 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6696 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006697 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6698
6699 // Grab nonce
6700 begin_params.push_back(begin_out_params);
6701
6702 // Decrypt.
6703 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006704 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006705 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006706 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006707 EXPECT_EQ(message.length(), plaintext.length());
6708 EXPECT_EQ(message, plaintext);
6709}
6710
6711/*
6712 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6713 *
6714 * Verifies that AES GCM mode works, even when there's a long delay
6715 * between operations.
6716 */
6717TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6719 .Authorization(TAG_NO_AUTH_REQUIRED)
6720 .AesEncryptionKey(128)
6721 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6722 .Padding(PaddingMode::NONE)
6723 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6724
6725 string aad = "foobar";
6726 string message = "123456789012345678901234567890123456";
6727
6728 auto begin_params = AuthorizationSetBuilder()
6729 .BlockMode(BlockMode::GCM)
6730 .Padding(PaddingMode::NONE)
6731 .Authorization(TAG_MAC_LENGTH, 128);
6732
Selene Huang31ab4042020-04-29 04:22:39 -07006733 // Encrypt
6734 AuthorizationSet begin_out_params;
6735 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6736 << "Begin encrypt";
6737 string ciphertext;
6738 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006739 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006740 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006741 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006742
6743 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6744
6745 // Grab nonce
6746 begin_params.push_back(begin_out_params);
6747
6748 // Decrypt.
6749 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6750 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006751 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006752 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006753 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006754 sleep(5);
6755 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6756 EXPECT_EQ(message.length(), plaintext.length());
6757 EXPECT_EQ(message, plaintext);
6758}
6759
6760/*
6761 * EncryptionOperationsTest.AesGcmDifferentNonces
6762 *
6763 * Verifies that encrypting the same data with different nonces produces different outputs.
6764 */
6765TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6767 .Authorization(TAG_NO_AUTH_REQUIRED)
6768 .AesEncryptionKey(128)
6769 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6770 .Padding(PaddingMode::NONE)
6771 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6772 .Authorization(TAG_CALLER_NONCE)));
6773
6774 string aad = "foobar";
6775 string message = "123456789012345678901234567890123456";
6776 string nonce1 = "000000000000";
6777 string nonce2 = "111111111111";
6778 string nonce3 = "222222222222";
6779
6780 string ciphertext1 =
6781 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6782 string ciphertext2 =
6783 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6784 string ciphertext3 =
6785 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6786
6787 ASSERT_NE(ciphertext1, ciphertext2);
6788 ASSERT_NE(ciphertext1, ciphertext3);
6789 ASSERT_NE(ciphertext2, ciphertext3);
6790}
6791
6792/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006793 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6794 *
6795 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6796 */
6797TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6798 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6799 .Authorization(TAG_NO_AUTH_REQUIRED)
6800 .AesEncryptionKey(128)
6801 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6802 .Padding(PaddingMode::NONE)
6803 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6804
6805 string aad = "foobar";
6806 string message = "123456789012345678901234567890123456";
6807
6808 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6809 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6810 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6811
6812 ASSERT_NE(ciphertext1, ciphertext2);
6813 ASSERT_NE(ciphertext1, ciphertext3);
6814 ASSERT_NE(ciphertext2, ciphertext3);
6815}
6816
6817/*
Selene Huang31ab4042020-04-29 04:22:39 -07006818 * EncryptionOperationsTest.AesGcmTooShortTag
6819 *
6820 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6821 */
6822TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6823 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6824 .Authorization(TAG_NO_AUTH_REQUIRED)
6825 .AesEncryptionKey(128)
6826 .BlockMode(BlockMode::GCM)
6827 .Padding(PaddingMode::NONE)
6828 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6829 string message = "123456789012345678901234567890123456";
6830 auto params = AuthorizationSetBuilder()
6831 .BlockMode(BlockMode::GCM)
6832 .Padding(PaddingMode::NONE)
6833 .Authorization(TAG_MAC_LENGTH, 96);
6834
6835 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6836}
6837
6838/*
6839 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6840 *
6841 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6842 */
6843TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6844 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6845 .Authorization(TAG_NO_AUTH_REQUIRED)
6846 .AesEncryptionKey(128)
6847 .BlockMode(BlockMode::GCM)
6848 .Padding(PaddingMode::NONE)
6849 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6850 string aad = "foobar";
6851 string message = "123456789012345678901234567890123456";
6852 auto params = AuthorizationSetBuilder()
6853 .BlockMode(BlockMode::GCM)
6854 .Padding(PaddingMode::NONE)
6855 .Authorization(TAG_MAC_LENGTH, 128);
6856
Selene Huang31ab4042020-04-29 04:22:39 -07006857 // Encrypt
6858 AuthorizationSet begin_out_params;
6859 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6860 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006861 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006862
6863 AuthorizationSet finish_out_params;
6864 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006865 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6866 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006867
6868 params = AuthorizationSetBuilder()
6869 .Authorizations(begin_out_params)
6870 .BlockMode(BlockMode::GCM)
6871 .Padding(PaddingMode::NONE)
6872 .Authorization(TAG_MAC_LENGTH, 96);
6873
6874 // Decrypt.
6875 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6876}
6877
6878/*
6879 * EncryptionOperationsTest.AesGcmCorruptKey
6880 *
6881 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6882 */
6883TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6884 const uint8_t nonce_bytes[] = {
6885 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6886 };
6887 string nonce = make_string(nonce_bytes);
6888 const uint8_t ciphertext_bytes[] = {
6889 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6890 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6891 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6892 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6893 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6894 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6895 };
6896 string ciphertext = make_string(ciphertext_bytes);
6897
6898 auto params = AuthorizationSetBuilder()
6899 .BlockMode(BlockMode::GCM)
6900 .Padding(PaddingMode::NONE)
6901 .Authorization(TAG_MAC_LENGTH, 128)
6902 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6903
6904 auto import_params = AuthorizationSetBuilder()
6905 .Authorization(TAG_NO_AUTH_REQUIRED)
6906 .AesEncryptionKey(128)
6907 .BlockMode(BlockMode::GCM)
6908 .Padding(PaddingMode::NONE)
6909 .Authorization(TAG_CALLER_NONCE)
6910 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6911
6912 // Import correct key and decrypt
6913 const uint8_t key_bytes[] = {
6914 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6915 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6916 };
6917 string key = make_string(key_bytes);
6918 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6919 string plaintext = DecryptMessage(ciphertext, params);
6920 CheckedDeleteKey();
6921
6922 // Corrupt key and attempt to decrypt
6923 key[0] = 0;
6924 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6925 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6926 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6927 CheckedDeleteKey();
6928}
6929
6930/*
6931 * EncryptionOperationsTest.AesGcmAadNoData
6932 *
6933 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6934 * encrypt.
6935 */
6936TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6938 .Authorization(TAG_NO_AUTH_REQUIRED)
6939 .AesEncryptionKey(128)
6940 .BlockMode(BlockMode::GCM)
6941 .Padding(PaddingMode::NONE)
6942 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6943
6944 string aad = "1234567890123456";
6945 auto params = AuthorizationSetBuilder()
6946 .BlockMode(BlockMode::GCM)
6947 .Padding(PaddingMode::NONE)
6948 .Authorization(TAG_MAC_LENGTH, 128);
6949
Selene Huang31ab4042020-04-29 04:22:39 -07006950 // Encrypt
6951 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006952 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006953 string ciphertext;
6954 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006955 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6956 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006957 EXPECT_TRUE(finish_out_params.empty());
6958
6959 // Grab nonce
6960 params.push_back(begin_out_params);
6961
6962 // Decrypt.
6963 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006964 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006965 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006966 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006967
6968 EXPECT_TRUE(finish_out_params.empty());
6969
6970 EXPECT_EQ("", plaintext);
6971}
6972
6973/*
6974 * EncryptionOperationsTest.AesGcmMultiPartAad
6975 *
6976 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6977 * chunks.
6978 */
6979TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6980 const size_t tag_bits = 128;
6981 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6982 .Authorization(TAG_NO_AUTH_REQUIRED)
6983 .AesEncryptionKey(128)
6984 .BlockMode(BlockMode::GCM)
6985 .Padding(PaddingMode::NONE)
6986 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6987
6988 string message = "123456789012345678901234567890123456";
6989 auto begin_params = AuthorizationSetBuilder()
6990 .BlockMode(BlockMode::GCM)
6991 .Padding(PaddingMode::NONE)
6992 .Authorization(TAG_MAC_LENGTH, tag_bits);
6993 AuthorizationSet begin_out_params;
6994
David Drysdale7fc26b92022-05-13 09:54:24 +01006995 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006996
6997 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006998 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6999 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007000 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007001 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7002 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007003
Selene Huang31ab4042020-04-29 04:22:39 -07007004 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07007005 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07007006
7007 // Grab nonce.
7008 begin_params.push_back(begin_out_params);
7009
7010 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01007011 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007012 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007013 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007014 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007015 EXPECT_EQ(message, plaintext);
7016}
7017
7018/*
7019 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7020 *
7021 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7022 */
7023TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7024 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7025 .Authorization(TAG_NO_AUTH_REQUIRED)
7026 .AesEncryptionKey(128)
7027 .BlockMode(BlockMode::GCM)
7028 .Padding(PaddingMode::NONE)
7029 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7030
7031 string message = "123456789012345678901234567890123456";
7032 auto begin_params = AuthorizationSetBuilder()
7033 .BlockMode(BlockMode::GCM)
7034 .Padding(PaddingMode::NONE)
7035 .Authorization(TAG_MAC_LENGTH, 128);
7036 AuthorizationSet begin_out_params;
7037
David Drysdale7fc26b92022-05-13 09:54:24 +01007038 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007039
Shawn Willden92d79c02021-02-19 07:31:55 -07007040 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007041 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007042 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7043 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007044
David Drysdaled2cc8c22021-04-15 13:29:45 +01007045 // The failure should have already cancelled the operation.
7046 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7047
Shawn Willden92d79c02021-02-19 07:31:55 -07007048 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007049}
7050
7051/*
7052 * EncryptionOperationsTest.AesGcmBadAad
7053 *
7054 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7055 */
7056TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7058 .Authorization(TAG_NO_AUTH_REQUIRED)
7059 .AesEncryptionKey(128)
7060 .BlockMode(BlockMode::GCM)
7061 .Padding(PaddingMode::NONE)
7062 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7063
7064 string message = "12345678901234567890123456789012";
7065 auto begin_params = AuthorizationSetBuilder()
7066 .BlockMode(BlockMode::GCM)
7067 .Padding(PaddingMode::NONE)
7068 .Authorization(TAG_MAC_LENGTH, 128);
7069
Selene Huang31ab4042020-04-29 04:22:39 -07007070 // Encrypt
7071 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007072 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007073 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007074 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007075 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007076
7077 // Grab nonce
7078 begin_params.push_back(begin_out_params);
7079
Selene Huang31ab4042020-04-29 04:22:39 -07007080 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007081 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007082 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007083 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007084 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007085}
7086
7087/*
7088 * EncryptionOperationsTest.AesGcmWrongNonce
7089 *
7090 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7091 */
7092TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7093 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7094 .Authorization(TAG_NO_AUTH_REQUIRED)
7095 .AesEncryptionKey(128)
7096 .BlockMode(BlockMode::GCM)
7097 .Padding(PaddingMode::NONE)
7098 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7099
7100 string message = "12345678901234567890123456789012";
7101 auto begin_params = AuthorizationSetBuilder()
7102 .BlockMode(BlockMode::GCM)
7103 .Padding(PaddingMode::NONE)
7104 .Authorization(TAG_MAC_LENGTH, 128);
7105
Selene Huang31ab4042020-04-29 04:22:39 -07007106 // Encrypt
7107 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007108 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007109 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007110 string ciphertext;
7111 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007112 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007113
7114 // Wrong nonce
7115 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7116
7117 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007118 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007119 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007120 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007121 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007122
7123 // With wrong nonce, should have gotten garbage plaintext (or none).
7124 EXPECT_NE(message, plaintext);
7125}
7126
7127/*
7128 * EncryptionOperationsTest.AesGcmCorruptTag
7129 *
7130 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7131 */
7132TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7133 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7134 .Authorization(TAG_NO_AUTH_REQUIRED)
7135 .AesEncryptionKey(128)
7136 .BlockMode(BlockMode::GCM)
7137 .Padding(PaddingMode::NONE)
7138 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7139
7140 string aad = "1234567890123456";
7141 string message = "123456789012345678901234567890123456";
7142
7143 auto params = AuthorizationSetBuilder()
7144 .BlockMode(BlockMode::GCM)
7145 .Padding(PaddingMode::NONE)
7146 .Authorization(TAG_MAC_LENGTH, 128);
7147
Selene Huang31ab4042020-04-29 04:22:39 -07007148 // Encrypt
7149 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007150 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007151 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007152 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007153 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007154
7155 // Corrupt tag
7156 ++(*ciphertext.rbegin());
7157
7158 // Grab nonce
7159 params.push_back(begin_out_params);
7160
7161 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007162 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007163 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007164 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007165 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007166}
7167
7168/*
7169 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7170 *
7171 * Verifies that 3DES is basically functional.
7172 */
7173TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7174 auto auths = AuthorizationSetBuilder()
7175 .TripleDesEncryptionKey(168)
7176 .BlockMode(BlockMode::ECB)
7177 .Authorization(TAG_NO_AUTH_REQUIRED)
7178 .Padding(PaddingMode::NONE);
7179
7180 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7181 // Two-block message.
7182 string message = "1234567890123456";
7183 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7184 string ciphertext1 = EncryptMessage(message, inParams);
7185 EXPECT_EQ(message.size(), ciphertext1.size());
7186
7187 string ciphertext2 = EncryptMessage(string(message), inParams);
7188 EXPECT_EQ(message.size(), ciphertext2.size());
7189
7190 // ECB is deterministic.
7191 EXPECT_EQ(ciphertext1, ciphertext2);
7192
7193 string plaintext = DecryptMessage(ciphertext1, inParams);
7194 EXPECT_EQ(message, plaintext);
7195}
7196
7197/*
7198 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7199 *
7200 * Verifies that CBC keys reject ECB usage.
7201 */
7202TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7204 .TripleDesEncryptionKey(168)
7205 .BlockMode(BlockMode::CBC)
7206 .Authorization(TAG_NO_AUTH_REQUIRED)
7207 .Padding(PaddingMode::NONE)));
7208
7209 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7210 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7211}
7212
7213/*
7214 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7215 *
7216 * Tests ECB mode with PKCS#7 padding, various message sizes.
7217 */
7218TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7219 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7220 .TripleDesEncryptionKey(168)
7221 .BlockMode(BlockMode::ECB)
7222 .Authorization(TAG_NO_AUTH_REQUIRED)
7223 .Padding(PaddingMode::PKCS7)));
7224
7225 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007226 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007227 string message(i, 'a');
7228 auto inParams =
7229 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7230 string ciphertext = EncryptMessage(message, inParams);
7231 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7232 string plaintext = DecryptMessage(ciphertext, inParams);
7233 EXPECT_EQ(message, plaintext);
7234 }
7235}
7236
7237/*
7238 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7239 *
7240 * Verifies that keys configured for no padding reject PKCS7 padding
7241 */
7242TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7243 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7244 .TripleDesEncryptionKey(168)
7245 .BlockMode(BlockMode::ECB)
7246 .Authorization(TAG_NO_AUTH_REQUIRED)
7247 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007248 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7249 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007250}
7251
7252/*
7253 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7254 *
7255 * Verifies that corrupted padding is detected.
7256 */
7257TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7258 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7259 .TripleDesEncryptionKey(168)
7260 .BlockMode(BlockMode::ECB)
7261 .Authorization(TAG_NO_AUTH_REQUIRED)
7262 .Padding(PaddingMode::PKCS7)));
7263
7264 string message = "a";
7265 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7266 EXPECT_EQ(8U, ciphertext.size());
7267 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007268
7269 AuthorizationSetBuilder begin_params;
7270 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7271 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007272
7273 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7274 ++ciphertext[ciphertext.size() / 2];
7275
David Drysdale7fc26b92022-05-13 09:54:24 +01007276 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007277 string plaintext;
7278 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7279 ErrorCode error = Finish(&plaintext);
7280 if (error == ErrorCode::INVALID_ARGUMENT) {
7281 // This is the expected error, we can exit the test now.
7282 return;
7283 } else {
7284 // Very small chance we got valid decryption, so try again.
7285 ASSERT_EQ(error, ErrorCode::OK);
7286 }
7287 }
7288 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007289}
7290
7291struct TripleDesTestVector {
7292 const char* name;
7293 const KeyPurpose purpose;
7294 const BlockMode block_mode;
7295 const PaddingMode padding_mode;
7296 const char* key;
7297 const char* iv;
7298 const char* input;
7299 const char* output;
7300};
7301
7302// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7303// of the NIST vectors are multiples of the block size.
7304static const TripleDesTestVector kTripleDesTestVectors[] = {
7305 {
7306 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7307 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7308 "", // IV
7309 "329d86bdf1bc5af4", // input
7310 "d946c2756d78633f", // output
7311 },
7312 {
7313 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7314 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7315 "", // IV
7316 "6b1540781b01ce1997adae102dbf3c5b", // input
7317 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7318 },
7319 {
7320 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7321 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7322 "", // IV
7323 "6daad94ce08acfe7", // input
7324 "660e7d32dcc90e79", // output
7325 },
7326 {
7327 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7328 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7329 "", // IV
7330 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7331 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7332 },
7333 {
7334 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7335 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7336 "43f791134c5647ba", // IV
7337 "dcc153cef81d6f24", // input
7338 "92538bd8af18d3ba", // output
7339 },
7340 {
7341 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7342 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7343 "c2e999cb6249023c", // IV
7344 "c689aee38a301bb316da75db36f110b5", // input
7345 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7346 },
7347 {
7348 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7349 PaddingMode::PKCS7,
7350 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7351 "c2e999cb6249023c", // IV
7352 "c689aee38a301bb316da75db36f110b500", // input
7353 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7354 },
7355 {
7356 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7357 PaddingMode::PKCS7,
7358 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7359 "c2e999cb6249023c", // IV
7360 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7361 "c689aee38a301bb316da75db36f110b500", // output
7362 },
7363 {
7364 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7365 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7366 "41746c7e442d3681", // IV
7367 "c53a7b0ec40600fe", // input
7368 "d4f00eb455de1034", // output
7369 },
7370 {
7371 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7372 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7373 "3982bc02c3727d45", // IV
7374 "6006f10adef52991fcc777a1238bbb65", // input
7375 "edae09288e9e3bc05746d872b48e3b29", // output
7376 },
7377};
7378
7379/*
7380 * EncryptionOperationsTest.TripleDesTestVector
7381 *
7382 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7383 */
7384TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7385 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7386 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7387 SCOPED_TRACE(test->name);
7388 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7389 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7390 hex2str(test->output));
7391 }
7392}
7393
7394/*
7395 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7396 *
7397 * Validates CBC mode functionality.
7398 */
7399TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7401 .TripleDesEncryptionKey(168)
7402 .BlockMode(BlockMode::CBC)
7403 .Authorization(TAG_NO_AUTH_REQUIRED)
7404 .Padding(PaddingMode::NONE)));
7405
7406 ASSERT_GT(key_blob_.size(), 0U);
7407
Brian J Murray734c8412022-01-13 14:55:30 -08007408 // Four-block message.
7409 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007410 vector<uint8_t> iv1;
7411 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7412 EXPECT_EQ(message.size(), ciphertext1.size());
7413
7414 vector<uint8_t> iv2;
7415 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7416 EXPECT_EQ(message.size(), ciphertext2.size());
7417
7418 // IVs should be random, so ciphertexts should differ.
7419 EXPECT_NE(iv1, iv2);
7420 EXPECT_NE(ciphertext1, ciphertext2);
7421
7422 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7423 EXPECT_EQ(message, plaintext);
7424}
7425
7426/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007427 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7428 *
7429 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7430 */
7431TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7433 .TripleDesEncryptionKey(168)
7434 .BlockMode(BlockMode::CBC)
7435 .Authorization(TAG_NO_AUTH_REQUIRED)
7436 .Authorization(TAG_CALLER_NONCE)
7437 .Padding(PaddingMode::NONE)));
7438 auto params = AuthorizationSetBuilder()
7439 .BlockMode(BlockMode::CBC)
7440 .Padding(PaddingMode::NONE)
7441 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7442 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7443}
7444
7445/*
Selene Huang31ab4042020-04-29 04:22:39 -07007446 * EncryptionOperationsTest.TripleDesCallerIv
7447 *
7448 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7449 */
7450TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7451 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7452 .TripleDesEncryptionKey(168)
7453 .BlockMode(BlockMode::CBC)
7454 .Authorization(TAG_NO_AUTH_REQUIRED)
7455 .Authorization(TAG_CALLER_NONCE)
7456 .Padding(PaddingMode::NONE)));
7457 string message = "1234567890123456";
7458 vector<uint8_t> iv;
7459 // Don't specify IV, should get a random one.
7460 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7461 EXPECT_EQ(message.size(), ciphertext1.size());
7462 EXPECT_EQ(8U, iv.size());
7463
7464 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7465 EXPECT_EQ(message, plaintext);
7466
7467 // Now specify an IV, should also work.
7468 iv = AidlBuf("abcdefgh");
7469 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7470
7471 // Decrypt with correct IV.
7472 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7473 EXPECT_EQ(message, plaintext);
7474
7475 // Now try with wrong IV.
7476 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7477 EXPECT_NE(message, plaintext);
7478}
7479
7480/*
7481 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7482 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007483 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007484 */
7485TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7487 .TripleDesEncryptionKey(168)
7488 .BlockMode(BlockMode::CBC)
7489 .Authorization(TAG_NO_AUTH_REQUIRED)
7490 .Padding(PaddingMode::NONE)));
7491
7492 string message = "12345678901234567890123456789012";
7493 vector<uint8_t> iv;
7494 // Don't specify nonce, should get a random one.
7495 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7496 EXPECT_EQ(message.size(), ciphertext1.size());
7497 EXPECT_EQ(8U, iv.size());
7498
7499 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7500 EXPECT_EQ(message, plaintext);
7501
7502 // Now specify a nonce, should fail.
7503 auto input_params = AuthorizationSetBuilder()
7504 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7505 .BlockMode(BlockMode::CBC)
7506 .Padding(PaddingMode::NONE);
7507 AuthorizationSet output_params;
7508 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7509 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7510}
7511
7512/*
7513 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7514 *
7515 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7516 */
7517TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7518 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7519 .TripleDesEncryptionKey(168)
7520 .BlockMode(BlockMode::ECB)
7521 .Authorization(TAG_NO_AUTH_REQUIRED)
7522 .Padding(PaddingMode::NONE)));
7523 // Two-block message.
7524 string message = "1234567890123456";
7525 auto begin_params =
7526 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7527 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7528}
7529
7530/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007531 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007532 *
7533 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7534 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007535TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7536 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007537 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7539 .TripleDesEncryptionKey(168)
7540 .BlockMode(blockMode)
7541 .Authorization(TAG_NO_AUTH_REQUIRED)
7542 .Padding(PaddingMode::NONE)));
7543 // Message is slightly shorter than two blocks.
7544 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007545
David Drysdaled2cc8c22021-04-15 13:29:45 +01007546 auto begin_params =
7547 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7548 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007549 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007550 string ciphertext;
7551 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7552
7553 CheckedDeleteKey();
7554 }
Selene Huang31ab4042020-04-29 04:22:39 -07007555}
7556
7557/*
7558 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7559 *
7560 * Verifies that PKCS7 padding works correctly in CBC mode.
7561 */
7562TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7564 .TripleDesEncryptionKey(168)
7565 .BlockMode(BlockMode::CBC)
7566 .Authorization(TAG_NO_AUTH_REQUIRED)
7567 .Padding(PaddingMode::PKCS7)));
7568
7569 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007570 for (size_t i = 0; i <= 32; i++) {
7571 SCOPED_TRACE(testing::Message() << "i = " << i);
7572 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7573 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007574 vector<uint8_t> iv;
7575 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7576 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7577 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7578 EXPECT_EQ(message, plaintext);
7579 }
7580}
7581
7582/*
7583 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7584 *
7585 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7586 */
7587TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7589 .TripleDesEncryptionKey(168)
7590 .BlockMode(BlockMode::CBC)
7591 .Authorization(TAG_NO_AUTH_REQUIRED)
7592 .Padding(PaddingMode::NONE)));
7593
7594 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007595 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007596 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007597 auto begin_params =
7598 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7599 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7600 }
7601}
7602
7603/*
7604 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7605 *
7606 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7607 */
7608TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7610 .TripleDesEncryptionKey(168)
7611 .BlockMode(BlockMode::CBC)
7612 .Authorization(TAG_NO_AUTH_REQUIRED)
7613 .Padding(PaddingMode::PKCS7)));
7614
7615 string message = "a";
7616 vector<uint8_t> iv;
7617 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7618 EXPECT_EQ(8U, ciphertext.size());
7619 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007620
7621 auto begin_params = AuthorizationSetBuilder()
7622 .BlockMode(BlockMode::CBC)
7623 .Padding(PaddingMode::PKCS7)
7624 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007625
7626 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007627 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007628 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007629 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007630 string plaintext;
7631 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7632 ErrorCode error = Finish(&plaintext);
7633 if (error == ErrorCode::INVALID_ARGUMENT) {
7634 // This is the expected error, we can exit the test now.
7635 return;
7636 } else {
7637 // Very small chance we got valid decryption, so try again.
7638 ASSERT_EQ(error, ErrorCode::OK);
7639 }
7640 }
7641 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007642}
7643
7644/*
7645 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7646 *
7647 * Verifies that 3DES CBC works with many different input sizes.
7648 */
7649TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7651 .TripleDesEncryptionKey(168)
7652 .BlockMode(BlockMode::CBC)
7653 .Authorization(TAG_NO_AUTH_REQUIRED)
7654 .Padding(PaddingMode::NONE)));
7655
7656 int increment = 7;
7657 string message(240, 'a');
7658 AuthorizationSet input_params =
7659 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7660 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007661 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007662
7663 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007664 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007665 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007666 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7667 EXPECT_EQ(message.size(), ciphertext.size());
7668
7669 // Move TAG_NONCE into input_params
7670 input_params = output_params;
7671 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7672 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7673 output_params.Clear();
7674
David Drysdale7fc26b92022-05-13 09:54:24 +01007675 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007676 string plaintext;
7677 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007678 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007679 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7680 EXPECT_EQ(ciphertext.size(), plaintext.size());
7681 EXPECT_EQ(message, plaintext);
7682}
7683
7684INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7685
7686typedef KeyMintAidlTestBase MaxOperationsTest;
7687
7688/*
7689 * MaxOperationsTest.TestLimitAes
7690 *
7691 * Verifies that the max uses per boot tag works correctly with AES keys.
7692 */
7693TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007694 if (SecLevel() == SecurityLevel::STRONGBOX) {
7695 GTEST_SKIP() << "Test not applicable to StrongBox device";
7696 }
Selene Huang31ab4042020-04-29 04:22:39 -07007697
7698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7699 .Authorization(TAG_NO_AUTH_REQUIRED)
7700 .AesEncryptionKey(128)
7701 .EcbMode()
7702 .Padding(PaddingMode::NONE)
7703 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7704
7705 string message = "1234567890123456";
7706
7707 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7708
7709 EncryptMessage(message, params);
7710 EncryptMessage(message, params);
7711 EncryptMessage(message, params);
7712
7713 // Fourth time should fail.
7714 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7715}
7716
7717/*
Qi Wud22ec842020-11-26 13:27:53 +08007718 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007719 *
7720 * Verifies that the max uses per boot tag works correctly with RSA keys.
7721 */
7722TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007723 if (SecLevel() == SecurityLevel::STRONGBOX) {
7724 GTEST_SKIP() << "Test not applicable to StrongBox device";
7725 }
Selene Huang31ab4042020-04-29 04:22:39 -07007726
7727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7728 .Authorization(TAG_NO_AUTH_REQUIRED)
7729 .RsaSigningKey(1024, 65537)
7730 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007731 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7732 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007733
7734 string message = "1234567890123456";
7735
7736 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7737
7738 SignMessage(message, params);
7739 SignMessage(message, params);
7740 SignMessage(message, params);
7741
7742 // Fourth time should fail.
7743 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7744}
7745
7746INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7747
Qi Wud22ec842020-11-26 13:27:53 +08007748typedef KeyMintAidlTestBase UsageCountLimitTest;
7749
7750/*
Qi Wubeefae42021-01-28 23:16:37 +08007751 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007752 *
Qi Wubeefae42021-01-28 23:16:37 +08007753 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007754 */
Qi Wubeefae42021-01-28 23:16:37 +08007755TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007756 if (SecLevel() == SecurityLevel::STRONGBOX) {
7757 GTEST_SKIP() << "Test not applicable to StrongBox device";
7758 }
Qi Wud22ec842020-11-26 13:27:53 +08007759
7760 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7761 .Authorization(TAG_NO_AUTH_REQUIRED)
7762 .AesEncryptionKey(128)
7763 .EcbMode()
7764 .Padding(PaddingMode::NONE)
7765 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7766
7767 // Check the usage count limit tag appears in the authorizations.
7768 AuthorizationSet auths;
7769 for (auto& entry : key_characteristics_) {
7770 auths.push_back(AuthorizationSet(entry.authorizations));
7771 }
7772 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7773 << "key usage count limit " << 1U << " missing";
7774
7775 string message = "1234567890123456";
7776 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7777
Qi Wubeefae42021-01-28 23:16:37 +08007778 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7779 AuthorizationSet keystore_auths =
7780 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7781
Qi Wud22ec842020-11-26 13:27:53 +08007782 // First usage of AES key should work.
7783 EncryptMessage(message, params);
7784
Qi Wud22ec842020-11-26 13:27:53 +08007785 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7786 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7787 // must be invalidated from secure storage (such as RPMB partition).
7788 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7789 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007790 // Usage count limit tag is enforced by keystore, keymint does nothing.
7791 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007792 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007793 }
7794}
7795
7796/*
Qi Wubeefae42021-01-28 23:16:37 +08007797 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007798 *
Qi Wubeefae42021-01-28 23:16:37 +08007799 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007800 */
Qi Wubeefae42021-01-28 23:16:37 +08007801TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007802 if (SecLevel() == SecurityLevel::STRONGBOX) {
7803 GTEST_SKIP() << "Test not applicable to StrongBox device";
7804 }
Qi Wubeefae42021-01-28 23:16:37 +08007805
7806 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7807 .Authorization(TAG_NO_AUTH_REQUIRED)
7808 .AesEncryptionKey(128)
7809 .EcbMode()
7810 .Padding(PaddingMode::NONE)
7811 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7812
7813 // Check the usage count limit tag appears in the authorizations.
7814 AuthorizationSet auths;
7815 for (auto& entry : key_characteristics_) {
7816 auths.push_back(AuthorizationSet(entry.authorizations));
7817 }
7818 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7819 << "key usage count limit " << 3U << " missing";
7820
7821 string message = "1234567890123456";
7822 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7823
7824 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7825 AuthorizationSet keystore_auths =
7826 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7827
7828 EncryptMessage(message, params);
7829 EncryptMessage(message, params);
7830 EncryptMessage(message, params);
7831
7832 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7833 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7834 // must be invalidated from secure storage (such as RPMB partition).
7835 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7836 } else {
7837 // Usage count limit tag is enforced by keystore, keymint does nothing.
7838 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007839 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007840 }
7841}
7842
7843/*
7844 * UsageCountLimitTest.TestSingleUseRsa
7845 *
7846 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7847 */
7848TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007849 if (SecLevel() == SecurityLevel::STRONGBOX) {
7850 GTEST_SKIP() << "Test not applicable to StrongBox device";
7851 }
Qi Wud22ec842020-11-26 13:27:53 +08007852
7853 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7854 .Authorization(TAG_NO_AUTH_REQUIRED)
7855 .RsaSigningKey(1024, 65537)
7856 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007857 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7858 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007859
7860 // Check the usage count limit tag appears in the authorizations.
7861 AuthorizationSet auths;
7862 for (auto& entry : key_characteristics_) {
7863 auths.push_back(AuthorizationSet(entry.authorizations));
7864 }
7865 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7866 << "key usage count limit " << 1U << " missing";
7867
7868 string message = "1234567890123456";
7869 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7870
Qi Wubeefae42021-01-28 23:16:37 +08007871 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7872 AuthorizationSet keystore_auths =
7873 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7874
Qi Wud22ec842020-11-26 13:27:53 +08007875 // First usage of RSA key should work.
7876 SignMessage(message, params);
7877
Qi Wud22ec842020-11-26 13:27:53 +08007878 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7879 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7880 // must be invalidated from secure storage (such as RPMB partition).
7881 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7882 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007883 // Usage count limit tag is enforced by keystore, keymint does nothing.
7884 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007885 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007886 }
7887}
7888
7889/*
7890 * UsageCountLimitTest.TestLimitUseRsa
7891 *
7892 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7893 */
7894TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007895 if (SecLevel() == SecurityLevel::STRONGBOX) {
7896 GTEST_SKIP() << "Test not applicable to StrongBox device";
7897 }
Qi Wubeefae42021-01-28 23:16:37 +08007898
7899 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7900 .Authorization(TAG_NO_AUTH_REQUIRED)
7901 .RsaSigningKey(1024, 65537)
7902 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007903 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7904 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007905
7906 // Check the usage count limit tag appears in the authorizations.
7907 AuthorizationSet auths;
7908 for (auto& entry : key_characteristics_) {
7909 auths.push_back(AuthorizationSet(entry.authorizations));
7910 }
7911 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7912 << "key usage count limit " << 3U << " missing";
7913
7914 string message = "1234567890123456";
7915 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7916
7917 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7918 AuthorizationSet keystore_auths =
7919 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7920
7921 SignMessage(message, params);
7922 SignMessage(message, params);
7923 SignMessage(message, params);
7924
7925 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7926 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7927 // must be invalidated from secure storage (such as RPMB partition).
7928 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7929 } else {
7930 // Usage count limit tag is enforced by keystore, keymint does nothing.
7931 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007932 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007933 }
7934}
7935
Qi Wu8e727f72021-02-11 02:49:33 +08007936/*
7937 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7938 *
7939 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7940 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7941 * in hardware.
7942 */
7943TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007944 auto error = GenerateKey(AuthorizationSetBuilder()
7945 .RsaSigningKey(2048, 65537)
7946 .Digest(Digest::NONE)
7947 .Padding(PaddingMode::NONE)
7948 .Authorization(TAG_NO_AUTH_REQUIRED)
7949 .Authorization(TAG_ROLLBACK_RESISTANCE)
7950 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007951 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7952 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007953 }
David Drysdale513bf122021-10-06 11:53:13 +01007954
7955 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7956 ASSERT_EQ(ErrorCode::OK, error);
7957 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7958 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7959 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7960
7961 // The KeyMint should also enforce single use key in hardware when it supports rollback
7962 // resistance.
7963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7964 .Authorization(TAG_NO_AUTH_REQUIRED)
7965 .RsaSigningKey(1024, 65537)
7966 .NoDigestOrPadding()
7967 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7968 .SetDefaultValidity()));
7969
7970 // Check the usage count limit tag appears in the hardware authorizations.
7971 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7972 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7973 << "key usage count limit " << 1U << " missing";
7974
7975 string message = "1234567890123456";
7976 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7977
7978 // First usage of RSA key should work.
7979 SignMessage(message, params);
7980
7981 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7982 // must be invalidated from secure storage (such as RPMB partition).
7983 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007984}
7985
Qi Wud22ec842020-11-26 13:27:53 +08007986INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7987
David Drysdale7de9feb2021-03-05 14:56:19 +00007988typedef KeyMintAidlTestBase GetHardwareInfoTest;
7989
7990TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7991 // Retrieving hardware info should give the same result each time.
7992 KeyMintHardwareInfo info;
7993 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7994 KeyMintHardwareInfo info2;
7995 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7996 EXPECT_EQ(info, info2);
7997}
7998
7999INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
8000
Selene Huang31ab4042020-04-29 04:22:39 -07008001typedef KeyMintAidlTestBase AddEntropyTest;
8002
8003/*
8004 * AddEntropyTest.AddEntropy
8005 *
8006 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
8007 * is actually added.
8008 */
8009TEST_P(AddEntropyTest, AddEntropy) {
8010 string data = "foo";
8011 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
8012}
8013
8014/*
8015 * AddEntropyTest.AddEmptyEntropy
8016 *
8017 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
8018 */
8019TEST_P(AddEntropyTest, AddEmptyEntropy) {
8020 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8021}
8022
8023/*
8024 * AddEntropyTest.AddLargeEntropy
8025 *
8026 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8027 */
8028TEST_P(AddEntropyTest, AddLargeEntropy) {
8029 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8030}
8031
David Drysdalebb3d85e2021-04-13 11:15:51 +01008032/*
8033 * AddEntropyTest.AddTooLargeEntropy
8034 *
8035 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8036 */
8037TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8038 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8039 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8040}
8041
Selene Huang31ab4042020-04-29 04:22:39 -07008042INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8043
Selene Huang31ab4042020-04-29 04:22:39 -07008044typedef KeyMintAidlTestBase KeyDeletionTest;
8045
8046/**
8047 * KeyDeletionTest.DeleteKey
8048 *
8049 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8050 * valid key blob.
8051 */
8052TEST_P(KeyDeletionTest, DeleteKey) {
8053 auto error = GenerateKey(AuthorizationSetBuilder()
8054 .RsaSigningKey(2048, 65537)
8055 .Digest(Digest::NONE)
8056 .Padding(PaddingMode::NONE)
8057 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008058 .Authorization(TAG_ROLLBACK_RESISTANCE)
8059 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008060 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8061 GTEST_SKIP() << "Rollback resistance not supported";
8062 }
Selene Huang31ab4042020-04-29 04:22:39 -07008063
8064 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008065 ASSERT_EQ(ErrorCode::OK, error);
8066 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8067 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008068
David Drysdale513bf122021-10-06 11:53:13 +01008069 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008070
David Drysdale513bf122021-10-06 11:53:13 +01008071 string message = "12345678901234567890123456789012";
8072 AuthorizationSet begin_out_params;
8073 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8074 Begin(KeyPurpose::SIGN, key_blob_,
8075 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8076 &begin_out_params));
8077 AbortIfNeeded();
8078 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008079}
8080
8081/**
8082 * KeyDeletionTest.DeleteInvalidKey
8083 *
8084 * This test checks that the HAL excepts invalid key blobs..
8085 */
8086TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8087 // Generate key just to check if rollback protection is implemented
8088 auto error = GenerateKey(AuthorizationSetBuilder()
8089 .RsaSigningKey(2048, 65537)
8090 .Digest(Digest::NONE)
8091 .Padding(PaddingMode::NONE)
8092 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008093 .Authorization(TAG_ROLLBACK_RESISTANCE)
8094 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008095 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8096 GTEST_SKIP() << "Rollback resistance not supported";
8097 }
Selene Huang31ab4042020-04-29 04:22:39 -07008098
8099 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008100 ASSERT_EQ(ErrorCode::OK, error);
8101 AuthorizationSet enforced(SecLevelAuthorizations());
8102 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008103
David Drysdale513bf122021-10-06 11:53:13 +01008104 // Delete the key we don't care about the result at this point.
8105 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008106
David Drysdale513bf122021-10-06 11:53:13 +01008107 // Now create an invalid key blob and delete it.
8108 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008109
David Drysdale513bf122021-10-06 11:53:13 +01008110 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008111}
8112
8113/**
8114 * KeyDeletionTest.DeleteAllKeys
8115 *
8116 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8117 *
8118 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8119 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8120 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8121 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8122 * credentials stored in Keystore/Keymint.
8123 */
8124TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008125 if (!arm_deleteAllKeys) {
8126 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8127 return;
8128 }
Selene Huang31ab4042020-04-29 04:22:39 -07008129 auto error = GenerateKey(AuthorizationSetBuilder()
8130 .RsaSigningKey(2048, 65537)
8131 .Digest(Digest::NONE)
8132 .Padding(PaddingMode::NONE)
8133 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008134 .Authorization(TAG_ROLLBACK_RESISTANCE)
8135 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008136 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8137 GTEST_SKIP() << "Rollback resistance not supported";
8138 }
Selene Huang31ab4042020-04-29 04:22:39 -07008139
8140 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008141 ASSERT_EQ(ErrorCode::OK, error);
8142 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8143 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008144
David Drysdale513bf122021-10-06 11:53:13 +01008145 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008146
David Drysdale513bf122021-10-06 11:53:13 +01008147 string message = "12345678901234567890123456789012";
8148 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008149
David Drysdale513bf122021-10-06 11:53:13 +01008150 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8151 Begin(KeyPurpose::SIGN, key_blob_,
8152 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8153 &begin_out_params));
8154 AbortIfNeeded();
8155 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008156}
8157
8158INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8159
David Drysdaled2cc8c22021-04-15 13:29:45 +01008160typedef KeyMintAidlTestBase KeyUpgradeTest;
8161
8162/**
8163 * KeyUpgradeTest.UpgradeInvalidKey
8164 *
8165 * This test checks that the HAL excepts invalid key blobs..
8166 */
8167TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8168 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8169
8170 std::vector<uint8_t> new_blob;
8171 Status result = keymint_->upgradeKey(key_blob,
8172 AuthorizationSetBuilder()
8173 .Authorization(TAG_APPLICATION_ID, "clientid")
8174 .Authorization(TAG_APPLICATION_DATA, "appdata")
8175 .vector_data(),
8176 &new_blob);
8177 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8178}
8179
8180INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8181
Selene Huang31ab4042020-04-29 04:22:39 -07008182using UpgradeKeyTest = KeyMintAidlTestBase;
8183
8184/*
8185 * UpgradeKeyTest.UpgradeKey
8186 *
8187 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8188 */
8189TEST_P(UpgradeKeyTest, UpgradeKey) {
8190 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8191 .AesEncryptionKey(128)
8192 .Padding(PaddingMode::NONE)
8193 .Authorization(TAG_NO_AUTH_REQUIRED)));
8194
8195 auto result = UpgradeKey(key_blob_);
8196
8197 // Key doesn't need upgrading. Should get okay, but no new key blob.
8198 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8199}
8200
8201INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8202
8203using ClearOperationsTest = KeyMintAidlTestBase;
8204
8205/*
8206 * ClearSlotsTest.TooManyOperations
8207 *
8208 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8209 * operations are started without being finished or aborted. Also verifies
8210 * that aborting the operations clears the operations.
8211 *
8212 */
8213TEST_P(ClearOperationsTest, TooManyOperations) {
8214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8215 .Authorization(TAG_NO_AUTH_REQUIRED)
8216 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008217 .Padding(PaddingMode::NONE)
8218 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008219
8220 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8221 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008222 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008223 AuthorizationSet out_params;
8224 ErrorCode result;
8225 size_t i;
8226
8227 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008228 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008229 if (ErrorCode::OK != result) {
8230 break;
8231 }
8232 }
8233 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8234 // Try again just in case there's a weird overflow bug
8235 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008236 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008237 for (size_t j = 0; j < i; j++) {
8238 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8239 << "Aboort failed for i = " << j << std::endl;
8240 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008241 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008242 AbortIfNeeded();
8243}
8244
8245INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8246
8247typedef KeyMintAidlTestBase TransportLimitTest;
8248
8249/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008250 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008251 *
8252 * Verifies that passing input data to finish succeeds as expected.
8253 */
8254TEST_P(TransportLimitTest, LargeFinishInput) {
8255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8256 .Authorization(TAG_NO_AUTH_REQUIRED)
8257 .AesEncryptionKey(128)
8258 .BlockMode(BlockMode::ECB)
8259 .Padding(PaddingMode::NONE)));
8260
8261 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008262 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008263 auto cipher_params =
8264 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8265
8266 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008267 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008268
8269 string plain_message = std::string(1 << msg_size, 'x');
8270 string encrypted_message;
8271 auto rc = Finish(plain_message, &encrypted_message);
8272
8273 EXPECT_EQ(ErrorCode::OK, rc);
8274 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8275 << "Encrypt finish returned OK, but did not consume all of the given input";
8276 cipher_params.push_back(out_params);
8277
David Drysdale7fc26b92022-05-13 09:54:24 +01008278 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008279
8280 string decrypted_message;
8281 rc = Finish(encrypted_message, &decrypted_message);
8282 EXPECT_EQ(ErrorCode::OK, rc);
8283 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8284 << "Decrypt finish returned OK, did not consume all of the given input";
8285 }
8286}
8287
8288INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8289
Seth Moored79a0ec2021-12-13 20:03:33 +00008290static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008291 switch (curve) {
8292 case EcCurve::P_224:
8293 return NID_secp224r1;
8294 case EcCurve::P_256:
8295 return NID_X9_62_prime256v1;
8296 case EcCurve::P_384:
8297 return NID_secp384r1;
8298 case EcCurve::P_521:
8299 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008300 case EcCurve::CURVE_25519:
8301 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008302 }
8303}
8304
David Drysdale42fe1892021-10-14 14:43:46 +01008305class KeyAgreementTest : public KeyMintAidlTestBase {
8306 protected:
8307 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8308 std::vector<uint8_t>* localPublicKey) {
8309 // Generate EC key locally (with access to private key material)
8310 if (localCurve == EcCurve::CURVE_25519) {
8311 uint8_t privKeyData[32];
8312 uint8_t pubKeyData[32];
8313 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008314 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8315 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8316 } else {
8317 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8318 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8319 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8320 ASSERT_NE(group, nullptr);
8321 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8322 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8323 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8324 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008325 }
David Drysdalea410b772022-05-09 16:44:13 +01008326
8327 // Get encoded form of the public part of the locally generated key...
8328 unsigned char* p = nullptr;
8329 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8330 ASSERT_GT(localPublicKeySize, 0);
8331 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8332 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8333 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008334 }
8335
8336 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8337 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008338 auto builder = AuthorizationSetBuilder()
8339 .Authorization(TAG_NO_AUTH_REQUIRED)
8340 .Authorization(TAG_EC_CURVE, curve)
8341 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8342 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8343 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8344 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8345 .SetDefaultValidity();
8346 ErrorCode result = GenerateKey(builder);
8347
8348 if (SecLevel() == SecurityLevel::STRONGBOX) {
8349 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8350 result = GenerateKeyWithSelfSignedAttestKey(
8351 AuthorizationSetBuilder()
8352 .EcdsaKey(EcCurve::P_256)
8353 .AttestKey()
8354 .SetDefaultValidity(), /* attest key params */
8355 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8356 }
8357 }
David Drysdale42fe1892021-10-14 14:43:46 +01008358 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8359 ASSERT_GT(cert_chain_.size(), 0);
8360 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8361 ASSERT_NE(kmKeyCert, nullptr);
8362 // Check that keyAgreement (bit 4) is set in KeyUsage
8363 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8364 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8365 ASSERT_NE(*kmPubKey, nullptr);
8366 if (dump_Attestations) {
8367 for (size_t n = 0; n < cert_chain_.size(); n++) {
8368 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8369 }
8370 }
8371 }
8372
8373 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8374 const std::vector<uint8_t>& localPublicKey) {
8375 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8376 string ZabFromKeyMintStr;
8377 ASSERT_EQ(ErrorCode::OK,
8378 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8379 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8380 vector<uint8_t> ZabFromTest;
8381
8382 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8383 size_t kmPubKeySize = 32;
8384 uint8_t kmPubKeyData[32];
8385 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8386 ASSERT_EQ(kmPubKeySize, 32);
8387
8388 uint8_t localPrivKeyData[32];
8389 size_t localPrivKeySize = 32;
8390 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8391 &localPrivKeySize));
8392 ASSERT_EQ(localPrivKeySize, 32);
8393
8394 uint8_t sharedKey[32];
8395 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8396 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8397 } else {
8398 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8399 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8400 ASSERT_NE(ctx, nullptr);
8401 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8402 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8403 size_t ZabFromTestLen = 0;
8404 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8405 ZabFromTest.resize(ZabFromTestLen);
8406 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8407 }
8408 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8409 }
8410};
8411
David Zeuthene0c40892021-01-08 12:54:11 -05008412/*
8413 * KeyAgreementTest.Ecdh
8414 *
David Drysdale42fe1892021-10-14 14:43:46 +01008415 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008416 */
8417TEST_P(KeyAgreementTest, Ecdh) {
8418 // Because it's possible to use this API with keys on different curves, we
8419 // check all N^2 combinations where N is the number of supported
8420 // curves.
8421 //
8422 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8423 // lot more curves we can be smart about things and just pick |otherCurve| so
8424 // it's not |curve| and that way we end up with only 2*N runs
8425 //
8426 for (auto curve : ValidCurves()) {
8427 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008428 SCOPED_TRACE(testing::Message()
8429 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8430
David Zeuthene0c40892021-01-08 12:54:11 -05008431 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008432 EVP_PKEY_Ptr localPrivKey;
8433 vector<uint8_t> localPublicKey;
8434 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008435
8436 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008437 EVP_PKEY_Ptr kmPubKey;
8438 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008439
8440 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8441 if (curve != localCurve) {
8442 // If the keys are using different curves KeyMint should fail with
8443 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008444 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008445 string ZabFromKeyMintStr;
8446 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008447 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008448 &ZabFromKeyMintStr));
8449
8450 } else {
8451 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008452 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008453 }
8454
8455 CheckedDeleteKey();
8456 }
8457 }
8458}
8459
David Drysdale42fe1892021-10-14 14:43:46 +01008460/*
8461 * KeyAgreementTest.EcdhCurve25519
8462 *
8463 * Verifies that ECDH works for curve25519. This is also covered by the general
8464 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8465 * KeyMint 1.0.
8466 */
8467TEST_P(KeyAgreementTest, EcdhCurve25519) {
8468 if (!Curve25519Supported()) {
8469 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8470 }
8471
8472 // Generate EC key in KeyMint (only access to public key material)
8473 EcCurve curve = EcCurve::CURVE_25519;
8474 EVP_PKEY_Ptr kmPubKey = nullptr;
8475 GenerateKeyMintEcKey(curve, &kmPubKey);
8476
8477 // Generate EC key on same curve locally (with access to private key material).
8478 EVP_PKEY_Ptr privKey;
8479 vector<uint8_t> encodedPublicKey;
8480 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8481
8482 // Agree on a key between local and KeyMint and check it.
8483 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8484
8485 CheckedDeleteKey();
8486}
8487
8488/*
8489 * KeyAgreementTest.EcdhCurve25519Imported
8490 *
8491 * Verifies that ECDH works for an imported curve25519 key.
8492 */
8493TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8494 if (!Curve25519Supported()) {
8495 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8496 }
8497
8498 // Import x25519 key into KeyMint.
8499 EcCurve curve = EcCurve::CURVE_25519;
8500 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8501 .Authorization(TAG_NO_AUTH_REQUIRED)
8502 .EcdsaKey(EcCurve::CURVE_25519)
8503 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8504 .SetDefaultValidity(),
8505 KeyFormat::PKCS8, x25519_pkcs8_key));
8506 ASSERT_GT(cert_chain_.size(), 0);
8507 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8508 ASSERT_NE(kmKeyCert, nullptr);
8509 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8510 ASSERT_NE(kmPubKey.get(), nullptr);
8511
8512 // Expect the import to emit corresponding public key data.
8513 size_t kmPubKeySize = 32;
8514 uint8_t kmPubKeyData[32];
8515 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8516 ASSERT_EQ(kmPubKeySize, 32);
8517 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8518 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8519
8520 // Generate EC key on same curve locally (with access to private key material).
8521 EVP_PKEY_Ptr privKey;
8522 vector<uint8_t> encodedPublicKey;
8523 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8524
8525 // Agree on a key between local and KeyMint and check it.
8526 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8527
8528 CheckedDeleteKey();
8529}
8530
8531/*
8532 * KeyAgreementTest.EcdhCurve25519InvalidSize
8533 *
8534 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8535 */
8536TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8537 if (!Curve25519Supported()) {
8538 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8539 }
8540
8541 // Generate EC key in KeyMint (only access to public key material)
8542 EcCurve curve = EcCurve::CURVE_25519;
8543 EVP_PKEY_Ptr kmPubKey = nullptr;
8544 GenerateKeyMintEcKey(curve, &kmPubKey);
8545
8546 // Generate EC key on same curve locally (with access to private key material).
8547 EVP_PKEY_Ptr privKey;
8548 vector<uint8_t> encodedPublicKey;
8549 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8550
8551 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8552 string ZabFromKeyMintStr;
8553 // Send in an incomplete public key.
8554 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8555 &ZabFromKeyMintStr));
8556
8557 CheckedDeleteKey();
8558}
8559
8560/*
8561 * KeyAgreementTest.EcdhCurve25519Mismatch
8562 *
8563 * Verifies that ECDH fails between curve25519 and other curves.
8564 */
8565TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8566 if (!Curve25519Supported()) {
8567 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8568 }
8569
8570 // Generate EC key in KeyMint (only access to public key material)
8571 EcCurve curve = EcCurve::CURVE_25519;
8572 EVP_PKEY_Ptr kmPubKey = nullptr;
8573 GenerateKeyMintEcKey(curve, &kmPubKey);
8574
8575 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008576 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008577 if (localCurve == curve) {
8578 continue;
8579 }
8580 // Generate EC key on a different curve locally (with access to private key material).
8581 EVP_PKEY_Ptr privKey;
8582 vector<uint8_t> encodedPublicKey;
8583 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8584
David Drysdale7fc26b92022-05-13 09:54:24 +01008585 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008586 string ZabFromKeyMintStr;
8587 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8588 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8589 &ZabFromKeyMintStr));
8590 }
8591
8592 CheckedDeleteKey();
8593}
8594
David Zeuthene0c40892021-01-08 12:54:11 -05008595INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8596
David Drysdaled2cc8c22021-04-15 13:29:45 +01008597using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8598
8599// This is a problematic test, as it can render the device under test permanently unusable.
8600// Re-enable and run at your own risk.
8601TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8602 auto result = DestroyAttestationIds();
8603 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8604}
8605
8606INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8607
Shawn Willdend659c7c2021-02-19 14:51:51 -07008608using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008609
David Drysdaledb0dcf52021-05-18 11:43:31 +01008610/*
8611 * EarlyBootKeyTest.CreateEarlyBootKeys
8612 *
8613 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8614 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008615TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008616 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008617 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8618 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008619 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8620 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8621 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8622 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008623
David Drysdaleadfe6112021-05-27 12:00:53 +01008624 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8625 ASSERT_GT(keyData.blob.size(), 0U);
8626 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8627 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8628 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008629}
8630
David Drysdaledb0dcf52021-05-18 11:43:31 +01008631/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008632 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8633 *
8634 * Verifies that creating an early boot key with attestation succeeds.
8635 */
8636TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8637 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8638 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8639 builder->AttestationChallenge("challenge");
8640 builder->AttestationApplicationId("app_id");
8641 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008642 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8643 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8644 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8645 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008646
8647 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008648 // Strongbox may not support factory attestation. Key creation might fail with
8649 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8650 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8651 continue;
8652 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008653 ASSERT_GT(keyData.blob.size(), 0U);
8654 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8655 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8656 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008657}
8658
8659/*
8660 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008661 *
8662 * Verifies that using early boot keys at a later stage fails.
8663 */
8664TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8665 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8666 .Authorization(TAG_NO_AUTH_REQUIRED)
8667 .Authorization(TAG_EARLY_BOOT_ONLY)
8668 .HmacKey(128)
8669 .Digest(Digest::SHA_2_256)
8670 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8671 AuthorizationSet output_params;
8672 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8673 AuthorizationSetBuilder()
8674 .Digest(Digest::SHA_2_256)
8675 .Authorization(TAG_MAC_LENGTH, 256),
8676 &output_params));
8677}
8678
8679/*
8680 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8681 *
8682 * Verifies that importing early boot keys fails.
8683 */
8684TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8685 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8686 .Authorization(TAG_NO_AUTH_REQUIRED)
8687 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008688 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008689 .Digest(Digest::SHA_2_256)
8690 .SetDefaultValidity(),
8691 KeyFormat::PKCS8, ec_256_key));
8692}
8693
David Drysdaled2cc8c22021-04-15 13:29:45 +01008694// 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 +00008695// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8696// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8697// early boot, so you'll have to reboot between runs.
8698TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8699 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8700 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008701 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8702 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8703 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8704 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8705
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008706 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8707 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8708 EXPECT_TRUE(
8709 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8710 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8711 EXPECT_TRUE(
8712 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8713
8714 // Should be able to use keys, since early boot has not ended
8715 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8716 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8717 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8718 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8719
8720 // End early boot
8721 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8722 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8723
8724 // Should not be able to use already-created keys.
8725 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8726 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8727 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8728 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8729
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008730 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008731 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008732 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008733 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8734 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8735 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8736 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008737}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008738
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008739INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8740
Shawn Willdend659c7c2021-02-19 14:51:51 -07008741using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008742
8743// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8744// between runs... and on most test devices there are no enrolled credentials so it can't be
8745// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8746// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8747// a manual test process, which includes unlocking between runs, which is why it's included here.
8748// Well, that and the fact that it's the only test we can do without also making calls into the
8749// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8750// implications might be, so that may or may not be a solution.
8751TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8752 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8753 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008754 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8755 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8756 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8757 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008758
8759 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8760 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8761 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8762 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8763
8764 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008765 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008766 ASSERT_EQ(ErrorCode::OK, rc);
8767 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8768 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8769 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8770 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008771}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008772
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008773INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8774
Shawn Willden22fb9c12022-06-02 14:04:33 -06008775using VsrRequirementTest = KeyMintAidlTestBase;
8776
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008777// @VsrTest = VSR-3.10-008
Shawn Willden22fb9c12022-06-02 14:04:33 -06008778TEST_P(VsrRequirementTest, Vsr13Test) {
8779 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008780 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008781 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8782 }
8783 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8784}
8785
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008786// @VsrTest = VSR-3.10-013.001
Eran Messerib9346f52022-12-15 14:58:34 +00008787TEST_P(VsrRequirementTest, Vsr14Test) {
8788 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008789 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008790 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8791 }
8792 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8793}
8794
Shawn Willden22fb9c12022-06-02 14:04:33 -06008795INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8796
Janis Danisevskis24c04702020-12-16 18:28:39 -08008797} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008798
David Drysdale77a86d82024-01-03 11:22:56 +00008799using aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase;
8800
Selene Huang31ab4042020-04-29 04:22:39 -07008801int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008802 std::cout << "Testing ";
David Drysdale77a86d82024-01-03 11:22:56 +00008803 auto halInstances = KeyMintAidlTestBase::build_params();
Shawn Willden7c130392020-12-21 09:58:22 -07008804 std::cout << "HAL instances:\n";
8805 for (auto& entry : halInstances) {
8806 std::cout << " " << entry << '\n';
8807 }
8808
Selene Huang31ab4042020-04-29 04:22:39 -07008809 ::testing::InitGoogleTest(&argc, argv);
8810 for (int i = 1; i < argc; ++i) {
8811 if (argv[i][0] == '-') {
8812 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
David Drysdale77a86d82024-01-03 11:22:56 +00008813 KeyMintAidlTestBase::arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008814 }
8815 if (std::string(argv[i]) == "--dump_attestations") {
David Drysdale77a86d82024-01-03 11:22:56 +00008816 KeyMintAidlTestBase::dump_Attestations = true;
Shawn Willden7c130392020-12-21 09:58:22 -07008817 } else {
8818 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008819 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008820 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8821 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8822 // be run in emulated environments that don't have the normal bootloader
8823 // interactions.
8824 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8825 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008826 if (std::string(argv[i]) == "--keyblob_dir") {
8827 if (i + 1 >= argc) {
8828 std::cerr << "Missing argument for --keyblob_dir\n";
8829 return 1;
8830 }
David Drysdale77a86d82024-01-03 11:22:56 +00008831 KeyMintAidlTestBase::keyblob_dir = std::string(argv[i + 1]);
David Drysdale9f5c0c52022-11-03 15:10:16 +00008832 ++i;
8833 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008834 if (std::string(argv[i]) == "--expect_upgrade") {
8835 if (i + 1 >= argc) {
8836 std::cerr << "Missing argument for --expect_upgrade\n";
8837 return 1;
8838 }
8839 std::string arg = argv[i + 1];
David Drysdale77a86d82024-01-03 11:22:56 +00008840 KeyMintAidlTestBase::expect_upgrade =
8841 arg == "yes" ? true
8842 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
8843 if (KeyMintAidlTestBase::expect_upgrade.has_value()) {
8844 std::cout << "expect_upgrade = "
8845 << (KeyMintAidlTestBase::expect_upgrade.value() ? "true" : "false")
8846 << std::endl;
8847 } else {
8848 std::cerr << "Error! Option --expect_upgrade " << arg << " unrecognized"
8849 << std::endl;
8850 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008851 ++i;
8852 }
Selene Huang31ab4042020-04-29 04:22:39 -07008853 }
8854 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008855 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008856}