blob: bdec4d3fb41cf06e6477f70ae48a4f6b20c27ae9 [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));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100743 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000744 vector<uint8_t> key_blob;
745 vector<KeyCharacteristics> key_characteristics;
746 // No key size specified
747 auto builder = AuthorizationSetBuilder()
748 .Authorization(TAG_ALGORITHM, Algorithm::AES)
749 .BlockMode(block_mode)
750 .Padding(padding_mode)
751 .SetDefaultValidity();
752 if (block_mode == BlockMode::GCM) {
753 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
754 }
755 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
756 GenerateKey(builder, &key_blob, &key_characteristics));
757 }
758 }
759}
760
761/*
762 * NewKeyGenerationTest.AesInvalidPadding
763 *
764 * Verifies that specifying an invalid padding on AES keys gives a failure
765 * somewhere along the way.
766 */
767TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
768 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
770 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000773 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800774 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000775 .AesEncryptionKey(key_size)
776 .BlockMode(block_mode)
777 .Padding(padding_mode)
778 .SetDefaultValidity();
779 if (block_mode == BlockMode::GCM) {
780 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
781 }
782
Tommy Chiu3950b452021-05-03 22:01:46 +0800783 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000784 if (result == ErrorCode::OK) {
785 // Key creation was OK but has generated a key that cannot be used.
786 auto params =
787 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800788 if (block_mode == BlockMode::GCM) {
789 params.Authorization(TAG_MAC_LENGTH, 128);
790 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000791 auto result = Begin(KeyPurpose::ENCRYPT, params);
792 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100793 result == ErrorCode::INVALID_KEY_BLOB)
794 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000795 } else {
796 // The KeyMint implementation detected that the generated key
797 // is unusable.
798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
799 }
800 }
801 }
802 }
803}
804
805/*
806 * NewKeyGenerationTest.AesGcmMissingMinMac
807 *
808 * Verifies that specifying an invalid key size for AES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
811TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
812 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
813 BlockMode block_mode = BlockMode::GCM;
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 // No MIN_MAC_LENGTH provided.
820 auto builder = AuthorizationSetBuilder()
821 .AesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .SetDefaultValidity();
825 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
826 GenerateKey(builder, &key_blob, &key_characteristics));
827 }
828 }
829}
830
831/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100832 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
833 *
834 * Verifies that specifying an invalid min MAC size for AES key generation returns
835 * UNSUPPORTED_MIN_MAC_LENGTH.
836 */
837TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
838 for (size_t min_mac_len : {88, 136}) {
839 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
840 BlockMode block_mode = BlockMode::GCM;
841 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
842 SCOPED_TRACE(testing::Message()
843 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
844 vector<uint8_t> key_blob;
845 vector<KeyCharacteristics> key_characteristics;
846 auto builder = AuthorizationSetBuilder()
847 .AesEncryptionKey(key_size)
848 .BlockMode(block_mode)
849 .Padding(padding_mode)
850 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
851 .SetDefaultValidity();
852 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
853 GenerateKey(builder, &key_blob, &key_characteristics));
854 }
855 }
856 }
857}
858
859/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000860 * NewKeyGenerationTest.TripleDes
861 *
862 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
863 * have correct characteristics.
864 */
865TEST_P(NewKeyGenerationTest, TripleDes) {
866 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
867 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
868 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
869 SCOPED_TRACE(testing::Message()
870 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
871 vector<uint8_t> key_blob;
872 vector<KeyCharacteristics> key_characteristics;
873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
874 .TripleDesEncryptionKey(key_size)
875 .BlockMode(block_mode)
876 .Padding(padding_mode)
877 .Authorization(TAG_NO_AUTH_REQUIRED)
878 .SetDefaultValidity(),
879 &key_blob, &key_characteristics));
880
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";
890
891 CheckedDeleteKey(&key_blob);
892 }
893 }
894 }
895}
896
897/*
898 * NewKeyGenerationTest.TripleDesWithAttestation
899 *
900 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
901 * have correct characteristics.
902 *
903 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
904 * put in a certificate) but which isn't an error.
905 */
906TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
907 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
908 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
909 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
910 SCOPED_TRACE(testing::Message()
911 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
912
913 auto challenge = "hello";
914 auto app_id = "foo";
915
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key_size)
920 .BlockMode(block_mode)
921 .Padding(padding_mode)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .AttestationChallenge(challenge)
924 .AttestationApplicationId(app_id)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
927
928 EXPECT_GT(key_blob.size(), 0U);
929 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937
938 CheckedDeleteKey(&key_blob);
939 }
940 }
941 }
942}
943
944/*
945 * NewKeyGenerationTest.TripleDesInvalidSize
946 *
947 * Verifies that specifying an invalid key size for 3-DES key generation returns
948 * UNSUPPORTED_KEY_SIZE.
949 */
950TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
951 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
952 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
953 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
954 SCOPED_TRACE(testing::Message()
955 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
956 vector<uint8_t> key_blob;
957 vector<KeyCharacteristics> key_characteristics;
958 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
959 GenerateKey(AuthorizationSetBuilder()
960 .TripleDesEncryptionKey(key_size)
961 .BlockMode(block_mode)
962 .Padding(padding_mode)
963 .Authorization(TAG_NO_AUTH_REQUIRED)
964 .SetDefaultValidity(),
965 &key_blob, &key_characteristics));
966 }
967 }
968 }
969
970 // Omitting the key size fails.
971 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
972 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
973 SCOPED_TRACE(testing::Message()
974 << "3DES-default-" << block_mode << "-" << padding_mode);
975 vector<uint8_t> key_blob;
976 vector<KeyCharacteristics> key_characteristics;
977 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
978 GenerateKey(AuthorizationSetBuilder()
979 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
980 .BlockMode(block_mode)
981 .Padding(padding_mode)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 &key_blob, &key_characteristics));
985 }
986 }
987}
988
989/*
Selene Huang31ab4042020-04-29 04:22:39 -0700990 * NewKeyGenerationTest.Rsa
991 *
992 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
993 * have correct characteristics.
994 */
995TEST_P(NewKeyGenerationTest, Rsa) {
996 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100997 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700998 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700999 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1001 .RsaSigningKey(key_size, 65537)
1002 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001003 .Padding(PaddingMode::NONE)
1004 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001005 &key_blob, &key_characteristics));
1006
1007 ASSERT_GT(key_blob.size(), 0U);
1008 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001009 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
Shawn Willden7f424372021-01-10 18:06:50 -07001011 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001012
1013 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1014 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1015 << "Key size " << key_size << "missing";
1016 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1017
1018 CheckedDeleteKey(&key_blob);
1019 }
1020}
1021
1022/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001023 * NewKeyGenerationTest.RsaWithMissingValidity
1024 *
1025 * Verifies that keymint returns an error while generating asymmetric key
1026 * without providing NOT_BEFORE and NOT_AFTER parameters.
1027 */
1028TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001029 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001030 /*
1031 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1032 * specified for asymmetric key generation. However, this was not
1033 * checked at the time so we can only be strict about checking this for
1034 * implementations of KeyMint version 2 and above.
1035 */
1036 GTEST_SKIP() << "Validity strict since KeyMint v2";
1037 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001038 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1039 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1040 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1041
1042 vector<uint8_t> key_blob;
1043 vector<KeyCharacteristics> key_characteristics;
1044 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1045 GenerateKey(AuthorizationSetBuilder()
1046 .RsaSigningKey(2048, 65537)
1047 .Digest(Digest::NONE)
1048 .Padding(PaddingMode::NONE)
1049 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1050 kUndefinedExpirationDateTime),
1051 &key_blob, &key_characteristics));
1052
1053 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1054 GenerateKey(AuthorizationSetBuilder()
1055 .RsaSigningKey(2048, 65537)
1056 .Digest(Digest::NONE)
1057 .Padding(PaddingMode::NONE)
1058 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1059 &key_blob, &key_characteristics));
1060}
1061
1062/*
David Drysdalead785f52023-03-27 19:53:01 +01001063 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1064 *
1065 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1066 */
1067TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
1070 ASSERT_EQ(ErrorCode::OK,
1071 GenerateKey(AuthorizationSetBuilder()
1072 .RsaSigningKey(2048, 65537)
1073 .Digest(Digest::NONE)
1074 .Padding(PaddingMode::NONE)
1075 .Authorization(TAG_CERTIFICATE_NOT_BEFORE,
1076 1183806000000 /* 2007-07-07T11:00:00Z */)
1077 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1078 1916049600000 /* 2030-09-19T12:00:00Z */),
1079 &key_blob, &key_characteristics));
1080 ASSERT_GT(cert_chain_.size(), 0);
1081
1082 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1083 ASSERT_TRUE(!!cert.get());
1084
1085 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1086 ASSERT_NE(not_before, nullptr);
1087 time_t not_before_time;
1088 ASSERT_EQ(ASN1_TIME_to_time_t(not_before, &not_before_time), 1);
1089 EXPECT_EQ(not_before_time, 1183806000);
1090
1091 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1092 ASSERT_NE(not_after, nullptr);
1093 time_t not_after_time;
1094 ASSERT_EQ(ASN1_TIME_to_time_t(not_after, &not_after_time), 1);
1095 EXPECT_EQ(not_after_time, 1916049600);
1096}
1097
1098/*
Qi Wud22ec842020-11-26 13:27:53 +08001099 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001100 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001101 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1102 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001103 */
1104TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001105 auto challenge = "hello";
1106 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107
Selene Huang6e46f142021-04-20 19:20:11 -07001108 auto subject = "cert subj 2";
1109 vector<uint8_t> subject_der(make_name_from_str(subject));
1110
1111 uint64_t serial_int = 66;
1112 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1113
Selene Huang4f64c222021-04-13 19:54:36 -07001114 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001115 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001116 vector<uint8_t> key_blob;
1117 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001118 auto builder = AuthorizationSetBuilder()
1119 .RsaSigningKey(key_size, 65537)
1120 .Digest(Digest::NONE)
1121 .Padding(PaddingMode::NONE)
1122 .AttestationChallenge(challenge)
1123 .AttestationApplicationId(app_id)
1124 .Authorization(TAG_NO_AUTH_REQUIRED)
1125 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1126 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1127 .SetDefaultValidity();
1128
1129 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001130 // Strongbox may not support factory provisioned attestation key.
1131 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001132 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1133 result = GenerateKeyWithSelfSignedAttestKey(
1134 AuthorizationSetBuilder()
1135 .RsaKey(key_size, 65537)
1136 .AttestKey()
1137 .SetDefaultValidity(), /* attest key params */
1138 builder, &key_blob, &key_characteristics);
1139 }
subrahmanyaman05642492022-02-05 07:10:56 +00001140 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001141 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001142 ASSERT_GT(key_blob.size(), 0U);
1143 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001144 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001145
1146 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1147
1148 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1149 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1150 << "Key size " << key_size << "missing";
1151 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1152
David Drysdalea8a888e2022-06-08 12:43:56 +01001153 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001154 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001155 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001156
1157 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1158 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001159 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001160 sw_enforced, hw_enforced, SecLevel(),
1161 cert_chain_[0].encodedCertificate));
1162
1163 CheckedDeleteKey(&key_blob);
1164 }
1165}
1166
1167/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001168 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001169 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001170 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001171 * that has been generated using an associate IRemotelyProvisionedComponent.
1172 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001173TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001174 if (!IsRkpSupportRequired()) {
1175 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001176 }
1177
Seth Moore5a0320f2023-03-24 12:29:08 -07001178 // Check for an IRemotelyProvisionedComponent instance associated with the
1179 // KeyMint instance.
1180 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1181 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1182 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1183 }
1184 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1185 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001186
1187 // Generate a P-256 keypair to use as an attestation key.
1188 MacedPublicKey macedPubKey;
1189 std::vector<uint8_t> privateKeyBlob;
1190 auto status =
1191 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1192 ASSERT_TRUE(status.isOk());
1193 vector<uint8_t> coseKeyData;
1194 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1195
1196 AttestationKey attestation_key;
1197 attestation_key.keyBlob = std::move(privateKeyBlob);
1198 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1199
1200 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001201 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001202 auto challenge = "hello";
1203 auto app_id = "foo";
1204
1205 vector<uint8_t> key_blob;
1206 vector<KeyCharacteristics> key_characteristics;
1207 ASSERT_EQ(ErrorCode::OK,
1208 GenerateKey(AuthorizationSetBuilder()
1209 .RsaSigningKey(key_size, 65537)
1210 .Digest(Digest::NONE)
1211 .Padding(PaddingMode::NONE)
1212 .AttestationChallenge(challenge)
1213 .AttestationApplicationId(app_id)
1214 .Authorization(TAG_NO_AUTH_REQUIRED)
1215 .SetDefaultValidity(),
1216 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1217
1218 ASSERT_GT(key_blob.size(), 0U);
1219 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001220 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001221
1222 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1223
1224 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1225 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1226 << "Key size " << key_size << "missing";
1227 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1228
1229 // Attestation by itself is not valid (last entry is not self-signed).
1230 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1231
1232 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001233 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001234 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1235 ASSERT_TRUE(key_cert.get());
1236 EVP_PKEY_Ptr signing_pubkey;
1237 p256_pub_key(coseKeyData, &signing_pubkey);
1238 ASSERT_TRUE(signing_pubkey.get());
1239
1240 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1241 << "Verification of attested certificate failed "
1242 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1243
1244 CheckedDeleteKey(&key_blob);
1245 }
1246}
1247
1248/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001249 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1250 *
1251 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1252 * that has been generated using an associate IRemotelyProvisionedComponent.
1253 */
1254TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001255 if (!IsRkpSupportRequired()) {
1256 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001257 }
1258
Seth Moore5a0320f2023-03-24 12:29:08 -07001259 // Check for an IRemotelyProvisionedComponent instance associated with the
1260 // KeyMint instance.
1261 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1262 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1263 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1264 }
1265 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1266 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001267
1268 // Generate a P-256 keypair to use as an attestation key.
1269 MacedPublicKey macedPubKey;
1270 std::vector<uint8_t> privateKeyBlob;
1271 auto status =
1272 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1273 ASSERT_TRUE(status.isOk());
1274 vector<uint8_t> coseKeyData;
1275 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1276
1277 AttestationKey attestation_key;
1278 attestation_key.keyBlob = std::move(privateKeyBlob);
1279 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1280
1281 for (auto curve : ValidCurves()) {
1282 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1283 auto challenge = "hello";
1284 auto app_id = "foo";
1285
1286 vector<uint8_t> key_blob;
1287 vector<KeyCharacteristics> key_characteristics;
1288 ASSERT_EQ(ErrorCode::OK,
1289 GenerateKey(AuthorizationSetBuilder()
1290 .EcdsaSigningKey(curve)
1291 .Digest(Digest::NONE)
1292 .AttestationChallenge(challenge)
1293 .AttestationApplicationId(app_id)
1294 .Authorization(TAG_NO_AUTH_REQUIRED)
1295 .SetDefaultValidity(),
1296 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1297
1298 ASSERT_GT(key_blob.size(), 0U);
1299 CheckBaseParams(key_characteristics);
1300 CheckCharacteristics(key_blob, key_characteristics);
1301
1302 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1303
1304 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1305 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1306
1307 // Attestation by itself is not valid (last entry is not self-signed).
1308 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1309
1310 // The signature over the attested key should correspond to the P256 public key.
1311 ASSERT_GT(cert_chain_.size(), 0);
1312 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1313 ASSERT_TRUE(key_cert.get());
1314 EVP_PKEY_Ptr signing_pubkey;
1315 p256_pub_key(coseKeyData, &signing_pubkey);
1316 ASSERT_TRUE(signing_pubkey.get());
1317
1318 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1319 << "Verification of attested certificate failed "
1320 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1321
1322 CheckedDeleteKey(&key_blob);
1323 }
1324}
1325
1326/*
Selene Huang4f64c222021-04-13 19:54:36 -07001327 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1328 *
1329 * Verifies that keymint attestation for RSA encryption keys with challenge and
1330 * app id is also successful.
1331 */
1332TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1333 auto key_size = 2048;
1334 auto challenge = "hello";
1335 auto app_id = "foo";
1336
Selene Huang6e46f142021-04-20 19:20:11 -07001337 auto subject = "subj 2";
1338 vector<uint8_t> subject_der(make_name_from_str(subject));
1339
1340 uint64_t serial_int = 111166;
1341 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1342
Selene Huang4f64c222021-04-13 19:54:36 -07001343 vector<uint8_t> key_blob;
1344 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001345 auto builder = AuthorizationSetBuilder()
1346 .RsaEncryptionKey(key_size, 65537)
1347 .Padding(PaddingMode::NONE)
1348 .AttestationChallenge(challenge)
1349 .AttestationApplicationId(app_id)
1350 .Authorization(TAG_NO_AUTH_REQUIRED)
1351 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1352 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1353 .SetDefaultValidity();
1354
1355 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001356 // Strongbox may not support factory provisioned attestation key.
1357 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001358 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1359 result = GenerateKeyWithSelfSignedAttestKey(
1360 AuthorizationSetBuilder()
1361 .RsaKey(key_size, 65537)
1362 .AttestKey()
1363 .SetDefaultValidity(), /* attest key params */
1364 builder, &key_blob, &key_characteristics);
1365 }
subrahmanyaman05642492022-02-05 07:10:56 +00001366 }
1367 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001368
1369 ASSERT_GT(key_blob.size(), 0U);
1370 AuthorizationSet auths;
1371 for (auto& entry : key_characteristics) {
1372 auths.push_back(AuthorizationSet(entry.authorizations));
1373 }
1374
1375 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1376 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1377
1378 // Verify that App data and ROT are NOT included.
1379 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1380 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1381
1382 // Check that some unexpected tags/values are NOT present.
1383 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1384 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1385
1386 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1387
1388 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1389 ASSERT_TRUE(os_ver);
1390 EXPECT_EQ(*os_ver, os_version());
1391
1392 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1393
1394 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1395 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1396 << "Key size " << key_size << "missing";
1397 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1398
David Drysdalea8a888e2022-06-08 12:43:56 +01001399 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001400 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001401 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001402
1403 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1404 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001405 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001406 sw_enforced, hw_enforced, SecLevel(),
1407 cert_chain_[0].encodedCertificate));
1408
1409 CheckedDeleteKey(&key_blob);
1410}
1411
1412/*
1413 * NewKeyGenerationTest.RsaWithSelfSign
1414 *
1415 * Verifies that attesting to RSA key generation is successful, and returns
1416 * self signed certificate if no challenge is provided. And signing etc
1417 * works as expected.
1418 */
1419TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001420 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1421 vector<uint8_t> subject_der(make_name_from_str(subject));
1422
1423 uint64_t serial_int = 0;
1424 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1425
Selene Huang4f64c222021-04-13 19:54:36 -07001426 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001427 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001428 vector<uint8_t> key_blob;
1429 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001430 ASSERT_EQ(ErrorCode::OK,
1431 GenerateKey(AuthorizationSetBuilder()
1432 .RsaSigningKey(key_size, 65537)
1433 .Digest(Digest::NONE)
1434 .Padding(PaddingMode::NONE)
1435 .Authorization(TAG_NO_AUTH_REQUIRED)
1436 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1437 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1438 .SetDefaultValidity(),
1439 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001440
1441 ASSERT_GT(key_blob.size(), 0U);
1442 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001443 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001444
1445 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1446
1447 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1448 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1449 << "Key size " << key_size << "missing";
1450 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1451
David Drysdalea8a888e2022-06-08 12:43:56 +01001452 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001453 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001454 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001455
1456 CheckedDeleteKey(&key_blob);
1457 }
1458}
1459
1460/*
1461 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1462 *
1463 * Verifies that attesting to RSA checks for missing app ID.
1464 */
1465TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1466 auto challenge = "hello";
1467 vector<uint8_t> key_blob;
1468 vector<KeyCharacteristics> key_characteristics;
1469
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001470 auto builder = AuthorizationSetBuilder()
1471 .RsaSigningKey(2048, 65537)
1472 .Digest(Digest::NONE)
1473 .Padding(PaddingMode::NONE)
1474 .AttestationChallenge(challenge)
1475 .Authorization(TAG_NO_AUTH_REQUIRED)
1476 .SetDefaultValidity();
1477
1478 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001479 // Strongbox may not support factory provisioned attestation key.
1480 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001481 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1482 result = GenerateKeyWithSelfSignedAttestKey(
1483 AuthorizationSetBuilder()
1484 .RsaKey(2048, 65537)
1485 .AttestKey()
1486 .SetDefaultValidity(), /* attest key params */
1487 builder, &key_blob, &key_characteristics);
1488 }
subrahmanyaman05642492022-02-05 07:10:56 +00001489 }
1490 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001491}
1492
1493/*
1494 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1495 *
1496 * Verifies that attesting to RSA ignores app id if challenge is missing.
1497 */
1498TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1499 auto key_size = 2048;
1500 auto app_id = "foo";
1501
Selene Huang6e46f142021-04-20 19:20:11 -07001502 auto subject = "cert subj 2";
1503 vector<uint8_t> subject_der(make_name_from_str(subject));
1504
1505 uint64_t serial_int = 1;
1506 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1507
Selene Huang4f64c222021-04-13 19:54:36 -07001508 vector<uint8_t> key_blob;
1509 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001510 ASSERT_EQ(ErrorCode::OK,
1511 GenerateKey(AuthorizationSetBuilder()
1512 .RsaSigningKey(key_size, 65537)
1513 .Digest(Digest::NONE)
1514 .Padding(PaddingMode::NONE)
1515 .AttestationApplicationId(app_id)
1516 .Authorization(TAG_NO_AUTH_REQUIRED)
1517 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1518 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1519 .SetDefaultValidity(),
1520 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001521
1522 ASSERT_GT(key_blob.size(), 0U);
1523 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001524 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001525
1526 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1527
1528 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1529 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1530 << "Key size " << key_size << "missing";
1531 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1532
David Drysdalea8a888e2022-06-08 12:43:56 +01001533 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001534 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001535 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1536 ASSERT_EQ(cert_chain_.size(), 1);
1537
1538 CheckedDeleteKey(&key_blob);
1539}
1540
1541/*
Qi Wud22ec842020-11-26 13:27:53 +08001542 * NewKeyGenerationTest.LimitedUsageRsa
1543 *
1544 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1545 * resulting keys have correct characteristics.
1546 */
1547TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1548 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001549 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001550 vector<uint8_t> key_blob;
1551 vector<KeyCharacteristics> key_characteristics;
1552 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1553 .RsaSigningKey(key_size, 65537)
1554 .Digest(Digest::NONE)
1555 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001556 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1557 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001558 &key_blob, &key_characteristics));
1559
1560 ASSERT_GT(key_blob.size(), 0U);
1561 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001562 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001563
1564 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1565
1566 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1567 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1568 << "Key size " << key_size << "missing";
1569 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1570
1571 // Check the usage count limit tag appears in the authorizations.
1572 AuthorizationSet auths;
1573 for (auto& entry : key_characteristics) {
1574 auths.push_back(AuthorizationSet(entry.authorizations));
1575 }
1576 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1577 << "key usage count limit " << 1U << " missing";
1578
1579 CheckedDeleteKey(&key_blob);
1580 }
1581}
1582
1583/*
Qi Wubeefae42021-01-28 23:16:37 +08001584 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1585 *
1586 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1587 * resulting keys have correct characteristics and attestation.
1588 */
1589TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001590 auto challenge = "hello";
1591 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001592
Selene Huang6e46f142021-04-20 19:20:11 -07001593 auto subject = "cert subj 2";
1594 vector<uint8_t> subject_der(make_name_from_str(subject));
1595
1596 uint64_t serial_int = 66;
1597 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1598
Selene Huang4f64c222021-04-13 19:54:36 -07001599 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001600 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001601 vector<uint8_t> key_blob;
1602 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001603 auto builder = AuthorizationSetBuilder()
1604 .RsaSigningKey(key_size, 65537)
1605 .Digest(Digest::NONE)
1606 .Padding(PaddingMode::NONE)
1607 .AttestationChallenge(challenge)
1608 .AttestationApplicationId(app_id)
1609 .Authorization(TAG_NO_AUTH_REQUIRED)
1610 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1611 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1612 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1613 .SetDefaultValidity();
1614
1615 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001616 // Strongbox may not support factory provisioned attestation key.
1617 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001618 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1619 result = GenerateKeyWithSelfSignedAttestKey(
1620 AuthorizationSetBuilder()
1621 .RsaKey(key_size, 65537)
1622 .AttestKey()
1623 .SetDefaultValidity(), /* attest key params */
1624 builder, &key_blob, &key_characteristics);
1625 }
subrahmanyaman05642492022-02-05 07:10:56 +00001626 }
1627 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001628
1629 ASSERT_GT(key_blob.size(), 0U);
1630 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001631 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001632
1633 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1634
1635 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1636 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1637 << "Key size " << key_size << "missing";
1638 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1639
1640 // Check the usage count limit tag appears in the authorizations.
1641 AuthorizationSet auths;
1642 for (auto& entry : key_characteristics) {
1643 auths.push_back(AuthorizationSet(entry.authorizations));
1644 }
1645 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1646 << "key usage count limit " << 1U << " missing";
1647
1648 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001649 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001650 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001651 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001652
1653 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1654 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001655 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001656 sw_enforced, hw_enforced, SecLevel(),
1657 cert_chain_[0].encodedCertificate));
1658
1659 CheckedDeleteKey(&key_blob);
1660 }
1661}
1662
1663/*
Selene Huang31ab4042020-04-29 04:22:39 -07001664 * NewKeyGenerationTest.NoInvalidRsaSizes
1665 *
1666 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1667 */
1668TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1669 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001670 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001671 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001672 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001673 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1674 GenerateKey(AuthorizationSetBuilder()
1675 .RsaSigningKey(key_size, 65537)
1676 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001677 .Padding(PaddingMode::NONE)
1678 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001679 &key_blob, &key_characteristics));
1680 }
1681}
1682
1683/*
1684 * NewKeyGenerationTest.RsaNoDefaultSize
1685 *
1686 * Verifies that failing to specify a key size for RSA key generation returns
1687 * UNSUPPORTED_KEY_SIZE.
1688 */
1689TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1690 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1691 GenerateKey(AuthorizationSetBuilder()
1692 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1693 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001694 .SigningKey()
1695 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001696}
1697
1698/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001699 * NewKeyGenerationTest.RsaMissingParams
1700 *
1701 * Verifies that omitting optional tags works.
1702 */
1703TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1704 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001705 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001706 ASSERT_EQ(ErrorCode::OK,
1707 GenerateKey(
1708 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1709 CheckedDeleteKey();
1710 }
1711}
1712
1713/*
Selene Huang31ab4042020-04-29 04:22:39 -07001714 * NewKeyGenerationTest.Ecdsa
1715 *
David Drysdale42fe1892021-10-14 14:43:46 +01001716 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001717 * have correct characteristics.
1718 */
1719TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001720 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001721 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001722 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001723 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001725 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001726 .Digest(Digest::NONE)
1727 .SetDefaultValidity(),
1728 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001729 ASSERT_GT(key_blob.size(), 0U);
1730 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001731 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001732
Shawn Willden7f424372021-01-10 18:06:50 -07001733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001734
1735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001736 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001737
1738 CheckedDeleteKey(&key_blob);
1739 }
1740}
1741
1742/*
David Drysdale42fe1892021-10-14 14:43:46 +01001743 * NewKeyGenerationTest.EcdsaCurve25519
1744 *
1745 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1746 * has correct characteristics.
1747 */
1748TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1749 if (!Curve25519Supported()) {
1750 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1751 }
1752
1753 EcCurve curve = EcCurve::CURVE_25519;
1754 vector<uint8_t> key_blob;
1755 vector<KeyCharacteristics> key_characteristics;
1756 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1757 .EcdsaSigningKey(curve)
1758 .Digest(Digest::NONE)
1759 .SetDefaultValidity(),
1760 &key_blob, &key_characteristics);
1761 ASSERT_EQ(result, ErrorCode::OK);
1762 ASSERT_GT(key_blob.size(), 0U);
1763
1764 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1765 ASSERT_GT(cert_chain_.size(), 0);
1766
1767 CheckBaseParams(key_characteristics);
1768 CheckCharacteristics(key_blob, key_characteristics);
1769
1770 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1771
1772 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1773 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1774
1775 CheckedDeleteKey(&key_blob);
1776}
1777
1778/*
1779 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1780 *
1781 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1782 * SIGN and AGREE_KEY.
1783 */
1784TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1785 if (!Curve25519Supported()) {
1786 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1787 }
1788
1789 EcCurve curve = EcCurve::CURVE_25519;
1790 vector<uint8_t> key_blob;
1791 vector<KeyCharacteristics> key_characteristics;
1792 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1793 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1794 .EcdsaSigningKey(curve)
1795 .Digest(Digest::NONE)
1796 .SetDefaultValidity(),
1797 &key_blob, &key_characteristics);
1798 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1799}
1800
1801/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001802 * NewKeyGenerationTest.EcdsaWithMissingValidity
1803 *
1804 * Verifies that keymint returns an error while generating asymmetric key
1805 * without providing NOT_BEFORE and NOT_AFTER parameters.
1806 */
1807TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001808 if (AidlVersion() < 2) {
1809 /*
1810 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1811 * specified for asymmetric key generation. However, this was not
1812 * checked at the time so we can only be strict about checking this for
1813 * implementations of KeyMint version 2 and above.
1814 */
1815 GTEST_SKIP() << "Validity strict since KeyMint v2";
1816 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001817 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1818 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1819 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1820
1821 vector<uint8_t> key_blob;
1822 vector<KeyCharacteristics> key_characteristics;
1823 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1824 GenerateKey(AuthorizationSetBuilder()
1825 .EcdsaSigningKey(EcCurve::P_256)
1826 .Digest(Digest::NONE)
1827 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1828 kUndefinedExpirationDateTime),
1829 &key_blob, &key_characteristics));
1830
1831 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1832 GenerateKey(AuthorizationSetBuilder()
1833 .EcdsaSigningKey(EcCurve::P_256)
1834 .Digest(Digest::NONE)
1835 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1836 &key_blob, &key_characteristics));
1837}
1838
1839/*
Selene Huang4f64c222021-04-13 19:54:36 -07001840 * NewKeyGenerationTest.EcdsaAttestation
1841 *
1842 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1843 * an attestation will be generated.
1844 */
1845TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1846 auto challenge = "hello";
1847 auto app_id = "foo";
1848
Selene Huang6e46f142021-04-20 19:20:11 -07001849 auto subject = "cert subj 2";
1850 vector<uint8_t> subject_der(make_name_from_str(subject));
1851
1852 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1853 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1854
David Drysdaledf09e542021-06-08 15:46:11 +01001855 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001856 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001857 vector<uint8_t> key_blob;
1858 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001859 auto builder = AuthorizationSetBuilder()
1860 .Authorization(TAG_NO_AUTH_REQUIRED)
1861 .EcdsaSigningKey(curve)
1862 .Digest(Digest::NONE)
1863 .AttestationChallenge(challenge)
1864 .AttestationApplicationId(app_id)
1865 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1866 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1867 .SetDefaultValidity();
1868
1869 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001870 // Strongbox may not support factory provisioned attestation key.
1871 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001872 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1873 result = GenerateKeyWithSelfSignedAttestKey(
1874 AuthorizationSetBuilder()
1875 .EcdsaKey(curve)
1876 .AttestKey()
1877 .SetDefaultValidity(), /* attest key params */
1878 builder, &key_blob, &key_characteristics);
1879 }
subrahmanyaman05642492022-02-05 07:10:56 +00001880 }
1881 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001882 ASSERT_GT(key_blob.size(), 0U);
1883 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001884 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001885
1886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1887
1888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001889 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001890
1891 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1892 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001893 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001894
1895 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1896 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001897 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001898 sw_enforced, hw_enforced, SecLevel(),
1899 cert_chain_[0].encodedCertificate));
1900
1901 CheckedDeleteKey(&key_blob);
1902 }
1903}
1904
1905/*
David Drysdale42fe1892021-10-14 14:43:46 +01001906 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1907 *
1908 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1909 * an attestation will be generated.
1910 */
1911TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1912 if (!Curve25519Supported()) {
1913 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1914 }
1915
1916 EcCurve curve = EcCurve::CURVE_25519;
1917 auto challenge = "hello";
1918 auto app_id = "foo";
1919
1920 auto subject = "cert subj 2";
1921 vector<uint8_t> subject_der(make_name_from_str(subject));
1922
1923 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1924 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1925
1926 vector<uint8_t> key_blob;
1927 vector<KeyCharacteristics> key_characteristics;
1928 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1929 .Authorization(TAG_NO_AUTH_REQUIRED)
1930 .EcdsaSigningKey(curve)
1931 .Digest(Digest::NONE)
1932 .AttestationChallenge(challenge)
1933 .AttestationApplicationId(app_id)
1934 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1935 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1936 .SetDefaultValidity(),
1937 &key_blob, &key_characteristics);
1938 ASSERT_EQ(ErrorCode::OK, result);
1939 ASSERT_GT(key_blob.size(), 0U);
1940 CheckBaseParams(key_characteristics);
1941 CheckCharacteristics(key_blob, key_characteristics);
1942
1943 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1944
1945 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1946 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1947
1948 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1949 ASSERT_GT(cert_chain_.size(), 0);
1950 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1951
1952 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1953 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1954 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1955 sw_enforced, hw_enforced, SecLevel(),
1956 cert_chain_[0].encodedCertificate));
1957
1958 CheckedDeleteKey(&key_blob);
1959}
1960
1961/*
David Drysdale37af4b32021-05-14 16:46:59 +01001962 * NewKeyGenerationTest.EcdsaAttestationTags
1963 *
1964 * Verifies that creation of an attested ECDSA key includes various tags in the
1965 * attestation extension.
1966 */
1967TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1968 auto challenge = "hello";
1969 auto app_id = "foo";
1970 auto subject = "cert subj 2";
1971 vector<uint8_t> subject_der(make_name_from_str(subject));
1972 uint64_t serial_int = 0x1010;
1973 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1974 const AuthorizationSetBuilder base_builder =
1975 AuthorizationSetBuilder()
1976 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001977 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001978 .Digest(Digest::NONE)
1979 .AttestationChallenge(challenge)
1980 .AttestationApplicationId(app_id)
1981 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1982 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1983 .SetDefaultValidity();
1984
1985 // Various tags that map to fields in the attestation extension ASN.1 schema.
1986 auto extra_tags = AuthorizationSetBuilder()
1987 .Authorization(TAG_ROLLBACK_RESISTANCE)
1988 .Authorization(TAG_EARLY_BOOT_ONLY)
1989 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1990 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1991 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1992 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1993 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1994 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1995 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1996 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1997 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1998 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001999
David Drysdale37af4b32021-05-14 16:46:59 +01002000 for (const KeyParameter& tag : extra_tags) {
2001 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2002 vector<uint8_t> key_blob;
2003 vector<KeyCharacteristics> key_characteristics;
2004 AuthorizationSetBuilder builder = base_builder;
2005 builder.push_back(tag);
2006 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2007 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
2008 tag.tag == TAG_ROLLBACK_RESISTANCE) {
2009 continue;
2010 }
Seth Mooreb393b082021-07-12 14:18:28 -07002011 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
2012 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01002013 continue;
2014 }
subrahmanyaman05642492022-02-05 07:10:56 +00002015 // Strongbox may not support factory provisioned attestation key.
2016 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002017 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2018 result = GenerateKeyWithSelfSignedAttestKey(
2019 AuthorizationSetBuilder()
2020 .EcdsaKey(EcCurve::P_256)
2021 .AttestKey()
2022 .SetDefaultValidity(), /* attest key params */
2023 builder, &key_blob, &key_characteristics);
2024 }
subrahmanyaman05642492022-02-05 07:10:56 +00002025 }
David Drysdale37af4b32021-05-14 16:46:59 +01002026 ASSERT_EQ(result, ErrorCode::OK);
2027 ASSERT_GT(key_blob.size(), 0U);
2028
2029 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2030 ASSERT_GT(cert_chain_.size(), 0);
2031 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2032
2033 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2034 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07002035 // Some tags are optional, so don't require them to be in the enforcements.
2036 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01002037 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2038 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2039 }
2040
2041 // Verifying the attestation record will check for the specific tag because
2042 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002043 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2044 hw_enforced, SecLevel(),
2045 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002046
2047 CheckedDeleteKey(&key_blob);
2048 }
2049
David Drysdalec53b7d92021-10-11 12:35:58 +01002050 // Collection of invalid attestation ID tags.
2051 auto invalid_tags =
2052 AuthorizationSetBuilder()
2053 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2054 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2055 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2056 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2057 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2058 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2059 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2060 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002061 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002062 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002063 vector<uint8_t> key_blob;
2064 vector<KeyCharacteristics> key_characteristics;
2065 AuthorizationSetBuilder builder =
2066 AuthorizationSetBuilder()
2067 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002068 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002069 .Digest(Digest::NONE)
2070 .AttestationChallenge(challenge)
2071 .AttestationApplicationId(app_id)
2072 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2073 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2074 .SetDefaultValidity();
2075 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002076
2077 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2078 // Strongbox may not support factory provisioned attestation key.
2079 if (SecLevel() == SecurityLevel::STRONGBOX) {
2080 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2081 error = GenerateKeyWithSelfSignedAttestKey(
2082 AuthorizationSetBuilder()
2083 .EcdsaKey(EcCurve::P_256)
2084 .AttestKey()
2085 .SetDefaultValidity(), /* attest key params */
2086 builder, &key_blob, &key_characteristics);
2087 }
2088 }
2089 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01002090 }
2091}
2092
2093/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002094 * NewKeyGenerationTest.EcdsaAttestationIdTags
2095 *
2096 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2097 * attestation extension.
2098 */
2099TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002100 if (is_gsi_image()) {
2101 // GSI sets up a standard set of device identifiers that may not match
2102 // the device identifiers held by the device.
2103 GTEST_SKIP() << "Test not applicable under GSI";
2104 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002105 auto challenge = "hello";
2106 auto app_id = "foo";
2107 auto subject = "cert subj 2";
2108 vector<uint8_t> subject_der(make_name_from_str(subject));
2109 uint64_t serial_int = 0x1010;
2110 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2111 const AuthorizationSetBuilder base_builder =
2112 AuthorizationSetBuilder()
2113 .Authorization(TAG_NO_AUTH_REQUIRED)
2114 .EcdsaSigningKey(EcCurve::P_256)
2115 .Digest(Digest::NONE)
2116 .AttestationChallenge(challenge)
2117 .AttestationApplicationId(app_id)
2118 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2119 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2120 .SetDefaultValidity();
2121
2122 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2123 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil8d779bf2022-09-28 16:09:29 +01002124 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2125 // to ro.product.brand
2126 std::string prop_value =
2127 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2128 if (!prop_value.empty()) {
2129 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2130 "ro.product.brand_for_attestation");
2131 } else {
2132 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2133 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002134 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002135 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2136 // to ro.product.name
2137 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2138 if (!prop_value.empty()) {
2139 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2140 "ro.product.name_for_attestation");
2141 } else {
2142 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2143 }
Tri Vo799e4352022-11-07 17:23:50 -08002144 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002145 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002146 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2147 // to ro.product.model
2148 prop_value =
2149 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2150 if (!prop_value.empty()) {
2151 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2152 "ro.product.model_for_attestation");
2153 } else {
2154 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2155 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002156
2157 for (const KeyParameter& tag : extra_tags) {
2158 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2159 vector<uint8_t> key_blob;
2160 vector<KeyCharacteristics> key_characteristics;
2161 AuthorizationSetBuilder builder = base_builder;
2162 builder.push_back(tag);
2163 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002164 // Strongbox may not support factory provisioned attestation key.
2165 if (SecLevel() == SecurityLevel::STRONGBOX) {
2166 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2167 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002168 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2169 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002170 continue;
2171 }
2172 ASSERT_EQ(result, ErrorCode::OK);
2173 ASSERT_GT(key_blob.size(), 0U);
2174
2175 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2176 ASSERT_GT(cert_chain_.size(), 0);
2177 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2178
2179 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2180 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2181
2182 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2183 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2184 // attestation extension should contain them, so make sure the extra tag is added.
2185 hw_enforced.push_back(tag);
2186
2187 // Verifying the attestation record will check for the specific tag because
2188 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002189 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2190 hw_enforced, SecLevel(),
2191 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002192
2193 CheckedDeleteKey(&key_blob);
2194 }
2195}
2196
2197/*
David Drysdale565ccc72021-10-11 12:49:50 +01002198 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2199 *
2200 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2201 */
2202TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2203 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002204 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002205 auto challenge = "hello";
2206 auto subject = "cert subj 2";
2207 vector<uint8_t> subject_der(make_name_from_str(subject));
2208 uint64_t serial_int = 0x1010;
2209 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002210 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002211 AuthorizationSetBuilder()
2212 .Authorization(TAG_NO_AUTH_REQUIRED)
2213 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2214 .EcdsaSigningKey(EcCurve::P_256)
2215 .Digest(Digest::NONE)
2216 .AttestationChallenge(challenge)
2217 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2218 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2219 .AttestationApplicationId(app_id)
2220 .Authorization(TAG_CREATION_DATETIME, datetime)
2221 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002222 if (reset) {
2223 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2224 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002225 auto result = GenerateKey(builder);
2226 if (SecLevel() == SecurityLevel::STRONGBOX) {
2227 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2228 result = GenerateKeyWithSelfSignedAttestKey(
2229 AuthorizationSetBuilder()
2230 .EcdsaKey(EcCurve::P_256)
2231 .AttestKey()
2232 .SetDefaultValidity(), /* attest key params */
2233 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2234 }
2235 }
2236 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002237 ASSERT_GT(key_blob_.size(), 0U);
2238
2239 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2240 ASSERT_GT(cert_chain_.size(), 0);
2241 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2242
2243 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2244 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2245
2246 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002247 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2248 hw_enforced, SecLevel(),
2249 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002250 EXPECT_GT(unique_id->size(), 0);
2251 CheckedDeleteKey();
2252 };
2253
2254 // Generate unique ID
2255 auto app_id = "foo";
2256 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2257 vector<uint8_t> unique_id;
2258 get_unique_id(app_id, cert_date, &unique_id);
2259
2260 // Generating a new key with the same parameters should give the same unique ID.
2261 vector<uint8_t> unique_id2;
2262 get_unique_id(app_id, cert_date, &unique_id2);
2263 EXPECT_EQ(unique_id, unique_id2);
2264
2265 // Generating a new key with a slightly different date should give the same unique ID.
2266 uint64_t rounded_date = cert_date / 2592000000LLU;
2267 uint64_t min_date = rounded_date * 2592000000LLU;
2268 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2269
2270 vector<uint8_t> unique_id3;
2271 get_unique_id(app_id, min_date, &unique_id3);
2272 EXPECT_EQ(unique_id, unique_id3);
2273
2274 vector<uint8_t> unique_id4;
2275 get_unique_id(app_id, max_date, &unique_id4);
2276 EXPECT_EQ(unique_id, unique_id4);
2277
2278 // A different attestation application ID should yield a different unique ID.
2279 auto app_id2 = "different_foo";
2280 vector<uint8_t> unique_id5;
2281 get_unique_id(app_id2, cert_date, &unique_id5);
2282 EXPECT_NE(unique_id, unique_id5);
2283
2284 // A radically different date should yield a different unique ID.
2285 vector<uint8_t> unique_id6;
2286 get_unique_id(app_id, 1611621648000, &unique_id6);
2287 EXPECT_NE(unique_id, unique_id6);
2288
2289 vector<uint8_t> unique_id7;
2290 get_unique_id(app_id, max_date + 1, &unique_id7);
2291 EXPECT_NE(unique_id, unique_id7);
2292
2293 vector<uint8_t> unique_id8;
2294 get_unique_id(app_id, min_date - 1, &unique_id8);
2295 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002296
2297 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2298 vector<uint8_t> unique_id9;
2299 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2300 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002301}
2302
2303/*
David Drysdale37af4b32021-05-14 16:46:59 +01002304 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2305 *
2306 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2307 */
2308TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2309 auto challenge = "hello";
2310 auto attest_app_id = "foo";
2311 auto subject = "cert subj 2";
2312 vector<uint8_t> subject_der(make_name_from_str(subject));
2313 uint64_t serial_int = 0x1010;
2314 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2315
2316 // Earlier versions of the attestation extension schema included a slot:
2317 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2318 // This should never have been included, and should never be filled in.
2319 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2320 // to confirm that this field never makes it into the attestation extension.
2321 vector<uint8_t> key_blob;
2322 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002323 auto builder = AuthorizationSetBuilder()
2324 .Authorization(TAG_NO_AUTH_REQUIRED)
2325 .EcdsaSigningKey(EcCurve::P_256)
2326 .Digest(Digest::NONE)
2327 .AttestationChallenge(challenge)
2328 .AttestationApplicationId(attest_app_id)
2329 .Authorization(TAG_APPLICATION_ID, "client_id")
2330 .Authorization(TAG_APPLICATION_DATA, "appdata")
2331 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2332 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2333 .SetDefaultValidity();
2334
2335 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002336 // Strongbox may not support factory provisioned attestation key.
2337 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002338 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2339 result = GenerateKeyWithSelfSignedAttestKey(
2340 AuthorizationSetBuilder()
2341 .EcdsaKey(EcCurve::P_256)
2342 .AttestKey()
2343 .SetDefaultValidity(), /* attest key params */
2344 builder, &key_blob, &key_characteristics);
2345 }
subrahmanyaman05642492022-02-05 07:10:56 +00002346 }
David Drysdale37af4b32021-05-14 16:46:59 +01002347 ASSERT_EQ(result, ErrorCode::OK);
2348 ASSERT_GT(key_blob.size(), 0U);
2349
2350 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2351 ASSERT_GT(cert_chain_.size(), 0);
2352 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2353
2354 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2355 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002356 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2357 hw_enforced, SecLevel(),
2358 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002359
2360 // Check that the app id is not in the cert.
2361 string app_id = "clientid";
2362 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2363 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2364 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2365 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2366 cert_chain_[0].encodedCertificate.end());
2367
2368 CheckedDeleteKey(&key_blob);
2369}
2370
2371/*
Selene Huang4f64c222021-04-13 19:54:36 -07002372 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2373 *
2374 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2375 * the key will generate a self signed attestation.
2376 */
2377TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002378 auto subject = "cert subj 2";
2379 vector<uint8_t> subject_der(make_name_from_str(subject));
2380
2381 uint64_t serial_int = 0x123456FFF1234;
2382 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2383
David Drysdaledf09e542021-06-08 15:46:11 +01002384 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002385 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002386 vector<uint8_t> key_blob;
2387 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002388 ASSERT_EQ(ErrorCode::OK,
2389 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002390 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002391 .Digest(Digest::NONE)
2392 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2393 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2394 .SetDefaultValidity(),
2395 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002396 ASSERT_GT(key_blob.size(), 0U);
2397 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002398 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002399
2400 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2401
2402 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002403 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002404
2405 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2406 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002407 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002408
2409 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2410 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2411
2412 CheckedDeleteKey(&key_blob);
2413 }
2414}
2415
2416/*
2417 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2418 *
2419 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2420 * app id must also be provided or else it will fail.
2421 */
2422TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2423 auto challenge = "hello";
2424 vector<uint8_t> key_blob;
2425 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002426 auto builder = AuthorizationSetBuilder()
2427 .EcdsaSigningKey(EcCurve::P_256)
2428 .Digest(Digest::NONE)
2429 .AttestationChallenge(challenge)
2430 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002431
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002432 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002433 // Strongbox may not support factory provisioned attestation key.
2434 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002435 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2436 result = GenerateKeyWithSelfSignedAttestKey(
2437 AuthorizationSetBuilder()
2438 .EcdsaKey(EcCurve::P_256)
2439 .AttestKey()
2440 .SetDefaultValidity(), /* attest key params */
2441 builder, &key_blob, &key_characteristics);
2442 }
subrahmanyaman05642492022-02-05 07:10:56 +00002443 }
2444 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002445}
2446
2447/*
2448 * NewKeyGenerationTest.EcdsaIgnoreAppId
2449 *
2450 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2451 * any appid will be ignored, and keymint will generate a self sign certificate.
2452 */
2453TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2454 auto app_id = "foo";
2455
David Drysdaledf09e542021-06-08 15:46:11 +01002456 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002457 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002458 vector<uint8_t> key_blob;
2459 vector<KeyCharacteristics> key_characteristics;
2460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002461 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002462 .Digest(Digest::NONE)
2463 .AttestationApplicationId(app_id)
2464 .SetDefaultValidity(),
2465 &key_blob, &key_characteristics));
2466
2467 ASSERT_GT(key_blob.size(), 0U);
2468 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002469 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002470
2471 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2472
2473 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002474 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002475
2476 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2477 ASSERT_EQ(cert_chain_.size(), 1);
2478
2479 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2480 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2481
2482 CheckedDeleteKey(&key_blob);
2483 }
2484}
2485
2486/*
2487 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2488 *
2489 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2490 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2491 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2492 * to specify how many following bytes will be used to encode the length.
2493 */
2494TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2495 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002496 std::vector<uint32_t> app_id_lengths{143, 258};
2497
2498 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002499 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002500 const string app_id(length, 'a');
2501 vector<uint8_t> key_blob;
2502 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002503 auto builder = AuthorizationSetBuilder()
2504 .Authorization(TAG_NO_AUTH_REQUIRED)
2505 .EcdsaSigningKey(EcCurve::P_256)
2506 .Digest(Digest::NONE)
2507 .AttestationChallenge(challenge)
2508 .AttestationApplicationId(app_id)
2509 .SetDefaultValidity();
2510
2511 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002512 // Strongbox may not support factory provisioned attestation key.
2513 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002514 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2515 result = GenerateKeyWithSelfSignedAttestKey(
2516 AuthorizationSetBuilder()
2517 .EcdsaKey(EcCurve::P_256)
2518 .AttestKey()
2519 .SetDefaultValidity(), /* attest key params */
2520 builder, &key_blob, &key_characteristics);
2521 }
subrahmanyaman05642492022-02-05 07:10:56 +00002522 }
2523 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002524 ASSERT_GT(key_blob.size(), 0U);
2525 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002526 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002527
2528 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2529
2530 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002531 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002532
2533 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2534 ASSERT_GT(cert_chain_.size(), 0);
2535
2536 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2537 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002538 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002539 sw_enforced, hw_enforced, SecLevel(),
2540 cert_chain_[0].encodedCertificate));
2541
2542 CheckedDeleteKey(&key_blob);
2543 }
2544}
2545
2546/*
Qi Wud22ec842020-11-26 13:27:53 +08002547 * NewKeyGenerationTest.LimitedUsageEcdsa
2548 *
2549 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2550 * resulting keys have correct characteristics.
2551 */
2552TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002553 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002554 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002555 vector<uint8_t> key_blob;
2556 vector<KeyCharacteristics> key_characteristics;
2557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002558 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002559 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002560 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2561 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002562 &key_blob, &key_characteristics));
2563
2564 ASSERT_GT(key_blob.size(), 0U);
2565 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002566 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002567
2568 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2569
2570 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002571 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002572
2573 // Check the usage count limit tag appears in the authorizations.
2574 AuthorizationSet auths;
2575 for (auto& entry : key_characteristics) {
2576 auths.push_back(AuthorizationSet(entry.authorizations));
2577 }
2578 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2579 << "key usage count limit " << 1U << " missing";
2580
2581 CheckedDeleteKey(&key_blob);
2582 }
2583}
2584
2585/*
Selene Huang31ab4042020-04-29 04:22:39 -07002586 * NewKeyGenerationTest.EcdsaDefaultSize
2587 *
David Drysdaledf09e542021-06-08 15:46:11 +01002588 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002589 * UNSUPPORTED_KEY_SIZE.
2590 */
2591TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2592 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2593 GenerateKey(AuthorizationSetBuilder()
2594 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2595 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002596 .Digest(Digest::NONE)
2597 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002598}
2599
2600/*
David Drysdale42fe1892021-10-14 14:43:46 +01002601 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002602 *
David Drysdale42fe1892021-10-14 14:43:46 +01002603 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002604 * UNSUPPORTED_KEY_SIZE.
2605 */
David Drysdale42fe1892021-10-14 14:43:46 +01002606TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002607 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002608 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002609 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002610 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002611 auto result = GenerateKey(AuthorizationSetBuilder()
2612 .EcdsaSigningKey(curve)
2613 .Digest(Digest::NONE)
2614 .SetDefaultValidity(),
2615 &key_blob, &key_characteristics);
2616 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2617 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002618 }
2619
David Drysdaledf09e542021-06-08 15:46:11 +01002620 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2621 GenerateKey(AuthorizationSetBuilder()
2622 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2623 .Authorization(TAG_KEY_SIZE, 190)
2624 .SigningKey()
2625 .Digest(Digest::NONE)
2626 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002627}
2628
2629/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002630 * NewKeyGenerationTest.EcdsaMissingCurve
2631 *
2632 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2633 */
2634TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2635 if (AidlVersion() < 2) {
2636 /*
2637 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2638 * However, this was not checked at the time so we can only be strict about checking this
2639 * for implementations of KeyMint version 2 and above.
2640 */
2641 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2642 }
2643 /* If EC_CURVE not provided, generateKey
2644 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2645 */
2646 auto result = GenerateKey(
2647 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2648 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2649 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2650}
2651
2652/*
Selene Huang31ab4042020-04-29 04:22:39 -07002653 * NewKeyGenerationTest.EcdsaMismatchKeySize
2654 *
2655 * Verifies that specifying mismatched key size and curve for EC key generation returns
2656 * INVALID_ARGUMENT.
2657 */
2658TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002659 if (SecLevel() == SecurityLevel::STRONGBOX) {
2660 GTEST_SKIP() << "Test not applicable to StrongBox device";
2661 }
Selene Huang31ab4042020-04-29 04:22:39 -07002662
David Drysdaledf09e542021-06-08 15:46:11 +01002663 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002664 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002665 .Authorization(TAG_KEY_SIZE, 224)
2666 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002667 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002668 .Digest(Digest::NONE)
2669 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002670 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002671}
2672
2673/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002674 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002675 *
2676 * Verifies that keymint does not support any curve designated as unsupported.
2677 */
2678TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2679 Digest digest;
2680 if (SecLevel() == SecurityLevel::STRONGBOX) {
2681 digest = Digest::SHA_2_256;
2682 } else {
2683 digest = Digest::SHA_2_512;
2684 }
2685 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002686 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002687 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2688 .EcdsaSigningKey(curve)
2689 .Digest(digest)
2690 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002691 << "Failed to generate key on curve: " << curve;
2692 CheckedDeleteKey();
2693 }
2694}
2695
2696/*
2697 * NewKeyGenerationTest.Hmac
2698 *
2699 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2700 * characteristics.
2701 */
2702TEST_P(NewKeyGenerationTest, Hmac) {
2703 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002704 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002705 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002706 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002707 constexpr size_t key_size = 128;
2708 ASSERT_EQ(ErrorCode::OK,
2709 GenerateKey(
2710 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2711 TAG_MIN_MAC_LENGTH, 128),
2712 &key_blob, &key_characteristics));
2713
2714 ASSERT_GT(key_blob.size(), 0U);
2715 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002716 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002717
Shawn Willden7f424372021-01-10 18:06:50 -07002718 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2719 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2720 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2721 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002722
2723 CheckedDeleteKey(&key_blob);
2724 }
2725}
2726
2727/*
Selene Huang4f64c222021-04-13 19:54:36 -07002728 * NewKeyGenerationTest.HmacNoAttestation
2729 *
2730 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2731 * and app id are provided.
2732 */
2733TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2734 auto challenge = "hello";
2735 auto app_id = "foo";
2736
2737 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002738 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002739 vector<uint8_t> key_blob;
2740 vector<KeyCharacteristics> key_characteristics;
2741 constexpr size_t key_size = 128;
2742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2743 .HmacKey(key_size)
2744 .Digest(digest)
2745 .AttestationChallenge(challenge)
2746 .AttestationApplicationId(app_id)
2747 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2748 &key_blob, &key_characteristics));
2749
2750 ASSERT_GT(key_blob.size(), 0U);
2751 ASSERT_EQ(cert_chain_.size(), 0);
2752 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002753 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002754
2755 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2756 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2757 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2758 << "Key size " << key_size << "missing";
2759
2760 CheckedDeleteKey(&key_blob);
2761 }
2762}
2763
2764/*
Qi Wud22ec842020-11-26 13:27:53 +08002765 * NewKeyGenerationTest.LimitedUsageHmac
2766 *
2767 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2768 * resulting keys have correct characteristics.
2769 */
2770TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2771 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002772 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002773 vector<uint8_t> key_blob;
2774 vector<KeyCharacteristics> key_characteristics;
2775 constexpr size_t key_size = 128;
2776 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2777 .HmacKey(key_size)
2778 .Digest(digest)
2779 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2780 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2781 &key_blob, &key_characteristics));
2782
2783 ASSERT_GT(key_blob.size(), 0U);
2784 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002785 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002786
2787 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2788 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2789 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2790 << "Key size " << key_size << "missing";
2791
2792 // Check the usage count limit tag appears in the authorizations.
2793 AuthorizationSet auths;
2794 for (auto& entry : key_characteristics) {
2795 auths.push_back(AuthorizationSet(entry.authorizations));
2796 }
2797 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2798 << "key usage count limit " << 1U << " missing";
2799
2800 CheckedDeleteKey(&key_blob);
2801 }
2802}
2803
2804/*
Selene Huang31ab4042020-04-29 04:22:39 -07002805 * NewKeyGenerationTest.HmacCheckKeySizes
2806 *
2807 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2808 */
2809TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2810 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002811 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002812 if (key_size < 64 || key_size % 8 != 0) {
2813 // To keep this test from being very slow, we only test a random fraction of
2814 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2815 // them, we expect to run ~40 of them in each run.
2816 if (key_size % 8 == 0 || random() % 10 == 0) {
2817 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2818 GenerateKey(AuthorizationSetBuilder()
2819 .HmacKey(key_size)
2820 .Digest(Digest::SHA_2_256)
2821 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2822 << "HMAC key size " << key_size << " invalid";
2823 }
2824 } else {
2825 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2826 .HmacKey(key_size)
2827 .Digest(Digest::SHA_2_256)
2828 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2829 << "Failed to generate HMAC key of size " << key_size;
2830 CheckedDeleteKey();
2831 }
2832 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002833 if (SecLevel() == SecurityLevel::STRONGBOX) {
2834 // STRONGBOX devices must not support keys larger than 512 bits.
2835 size_t key_size = 520;
2836 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2837 GenerateKey(AuthorizationSetBuilder()
2838 .HmacKey(key_size)
2839 .Digest(Digest::SHA_2_256)
2840 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2841 << "HMAC key size " << key_size << " unexpectedly valid";
2842 }
Selene Huang31ab4042020-04-29 04:22:39 -07002843}
2844
2845/*
2846 * NewKeyGenerationTest.HmacCheckMinMacLengths
2847 *
2848 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2849 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2850 * specific MAC length that failed, so reproducing a failed run will be easy.
2851 */
2852TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2853 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002854 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002855 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2856 // To keep this test from being very long, we only test a random fraction of
2857 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2858 // we expect to run ~17 of them in each run.
2859 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2860 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2861 GenerateKey(AuthorizationSetBuilder()
2862 .HmacKey(128)
2863 .Digest(Digest::SHA_2_256)
2864 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2865 << "HMAC min mac length " << min_mac_length << " invalid.";
2866 }
2867 } else {
2868 EXPECT_EQ(ErrorCode::OK,
2869 GenerateKey(AuthorizationSetBuilder()
2870 .HmacKey(128)
2871 .Digest(Digest::SHA_2_256)
2872 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2873 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2874 CheckedDeleteKey();
2875 }
2876 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002877
2878 // Minimum MAC length must be no more than 512 bits.
2879 size_t min_mac_length = 520;
2880 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2881 GenerateKey(AuthorizationSetBuilder()
2882 .HmacKey(128)
2883 .Digest(Digest::SHA_2_256)
2884 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2885 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002886}
2887
2888/*
2889 * NewKeyGenerationTest.HmacMultipleDigests
2890 *
2891 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2892 */
2893TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002894 if (SecLevel() == SecurityLevel::STRONGBOX) {
2895 GTEST_SKIP() << "Test not applicable to StrongBox device";
2896 }
Selene Huang31ab4042020-04-29 04:22:39 -07002897
2898 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2899 GenerateKey(AuthorizationSetBuilder()
2900 .HmacKey(128)
2901 .Digest(Digest::SHA1)
2902 .Digest(Digest::SHA_2_256)
2903 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2904}
2905
2906/*
2907 * NewKeyGenerationTest.HmacDigestNone
2908 *
2909 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2910 */
2911TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2912 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2913 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2914 128)));
2915
2916 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2917 GenerateKey(AuthorizationSetBuilder()
2918 .HmacKey(128)
2919 .Digest(Digest::NONE)
2920 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2921}
2922
Selene Huang4f64c222021-04-13 19:54:36 -07002923/*
2924 * NewKeyGenerationTest.AesNoAttestation
2925 *
2926 * Verifies that attestation parameters to AES keys are ignored and generateKey
2927 * will succeed.
2928 */
2929TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2930 auto challenge = "hello";
2931 auto app_id = "foo";
2932
2933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2934 .Authorization(TAG_NO_AUTH_REQUIRED)
2935 .AesEncryptionKey(128)
2936 .EcbMode()
2937 .Padding(PaddingMode::PKCS7)
2938 .AttestationChallenge(challenge)
2939 .AttestationApplicationId(app_id)));
2940
2941 ASSERT_EQ(cert_chain_.size(), 0);
2942}
2943
2944/*
2945 * NewKeyGenerationTest.TripleDesNoAttestation
2946 *
2947 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2948 * will be successful. No attestation should be generated.
2949 */
2950TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2951 auto challenge = "hello";
2952 auto app_id = "foo";
2953
2954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2955 .TripleDesEncryptionKey(168)
2956 .BlockMode(BlockMode::ECB)
2957 .Authorization(TAG_NO_AUTH_REQUIRED)
2958 .Padding(PaddingMode::NONE)
2959 .AttestationChallenge(challenge)
2960 .AttestationApplicationId(app_id)));
2961 ASSERT_EQ(cert_chain_.size(), 0);
2962}
2963
Selene Huang31ab4042020-04-29 04:22:39 -07002964INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2965
2966typedef KeyMintAidlTestBase SigningOperationsTest;
2967
2968/*
2969 * SigningOperationsTest.RsaSuccess
2970 *
2971 * Verifies that raw RSA signature operations succeed.
2972 */
2973TEST_P(SigningOperationsTest, RsaSuccess) {
2974 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2975 .RsaSigningKey(2048, 65537)
2976 .Digest(Digest::NONE)
2977 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002978 .Authorization(TAG_NO_AUTH_REQUIRED)
2979 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002980 string message = "12345678901234567890123456789012";
2981 string signature = SignMessage(
2982 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002983 LocalVerifyMessage(message, signature,
2984 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2985}
2986
2987/*
2988 * SigningOperationsTest.RsaAllPaddingsAndDigests
2989 *
2990 * Verifies RSA signature/verification for all padding modes and digests.
2991 */
2992TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2993 auto authorizations = AuthorizationSetBuilder()
2994 .Authorization(TAG_NO_AUTH_REQUIRED)
2995 .RsaSigningKey(2048, 65537)
2996 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2997 .Padding(PaddingMode::NONE)
2998 .Padding(PaddingMode::RSA_PSS)
2999 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3000 .SetDefaultValidity();
3001
3002 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
3003
3004 string message(128, 'a');
3005 string corrupt_message(message);
3006 ++corrupt_message[corrupt_message.size() / 2];
3007
3008 for (auto padding :
3009 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
3010 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003011 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003012 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
3013 // Digesting only makes sense with padding.
3014 continue;
3015 }
3016
3017 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
3018 // PSS requires digesting.
3019 continue;
3020 }
3021
3022 string signature =
3023 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
3024 LocalVerifyMessage(message, signature,
3025 AuthorizationSetBuilder().Digest(digest).Padding(padding));
3026 }
3027 }
Selene Huang31ab4042020-04-29 04:22:39 -07003028}
3029
3030/*
3031 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3032 *
Shawn Willden7f424372021-01-10 18:06:50 -07003033 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003034 */
3035TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3037 .Authorization(TAG_NO_AUTH_REQUIRED)
3038 .RsaSigningKey(2048, 65537)
3039 .Digest(Digest::NONE)
3040 .Padding(PaddingMode::NONE)
3041 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003042 .Authorization(TAG_APPLICATION_DATA, "appdata")
3043 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003044
3045 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3046
Selene Huang31ab4042020-04-29 04:22:39 -07003047 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3048 Begin(KeyPurpose::SIGN,
3049 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3050 AbortIfNeeded();
3051 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3052 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3053 .Digest(Digest::NONE)
3054 .Padding(PaddingMode::NONE)
3055 .Authorization(TAG_APPLICATION_ID, "clientid")));
3056 AbortIfNeeded();
3057 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3058 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3059 .Digest(Digest::NONE)
3060 .Padding(PaddingMode::NONE)
3061 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3062 AbortIfNeeded();
3063 EXPECT_EQ(ErrorCode::OK,
3064 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3065 .Digest(Digest::NONE)
3066 .Padding(PaddingMode::NONE)
3067 .Authorization(TAG_APPLICATION_DATA, "appdata")
3068 .Authorization(TAG_APPLICATION_ID, "clientid")));
3069 AbortIfNeeded();
3070}
3071
3072/*
3073 * SigningOperationsTest.RsaPssSha256Success
3074 *
3075 * Verifies that RSA-PSS signature operations succeed.
3076 */
3077TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3079 .RsaSigningKey(2048, 65537)
3080 .Digest(Digest::SHA_2_256)
3081 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003082 .Authorization(TAG_NO_AUTH_REQUIRED)
3083 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003084 // Use large message, which won't work without digesting.
3085 string message(1024, 'a');
3086 string signature = SignMessage(
3087 message,
3088 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3089}
3090
3091/*
3092 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3093 *
3094 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3095 * supports only unpadded operations.
3096 */
3097TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3099 .RsaSigningKey(2048, 65537)
3100 .Digest(Digest::NONE)
3101 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003102 .Padding(PaddingMode::NONE)
3103 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003104 string message = "12345678901234567890123456789012";
3105 string signature;
3106
3107 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3108 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3109 .Digest(Digest::NONE)
3110 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3111}
3112
3113/*
3114 * SigningOperationsTest.NoUserConfirmation
3115 *
3116 * Verifies that keymint rejects signing operations for keys with
3117 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3118 * presented.
3119 */
3120TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003121 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyaman9d1d8b72023-04-28 23:37:02 +00003122 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003123 .Digest(Digest::NONE)
3124 .Padding(PaddingMode::NONE)
3125 .Authorization(TAG_NO_AUTH_REQUIRED)
3126 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3127 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003128
3129 const string message = "12345678901234567890123456789012";
3130 EXPECT_EQ(ErrorCode::OK,
3131 Begin(KeyPurpose::SIGN,
3132 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3133 string signature;
3134 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3135}
3136
3137/*
3138 * SigningOperationsTest.RsaPkcs1Sha256Success
3139 *
3140 * Verifies that digested RSA-PKCS1 signature operations succeed.
3141 */
3142TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3144 .RsaSigningKey(2048, 65537)
3145 .Digest(Digest::SHA_2_256)
3146 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003147 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3148 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003149 string message(1024, 'a');
3150 string signature = SignMessage(message, AuthorizationSetBuilder()
3151 .Digest(Digest::SHA_2_256)
3152 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3153}
3154
3155/*
3156 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3157 *
3158 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3159 */
3160TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3161 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3162 .RsaSigningKey(2048, 65537)
3163 .Digest(Digest::NONE)
3164 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003165 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3166 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003167 string message(53, 'a');
3168 string signature = SignMessage(message, AuthorizationSetBuilder()
3169 .Digest(Digest::NONE)
3170 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3171}
3172
3173/*
3174 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3175 *
3176 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3177 * given a too-long message.
3178 */
3179TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
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 string message(257, 'a');
3187
3188 EXPECT_EQ(ErrorCode::OK,
3189 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3190 .Digest(Digest::NONE)
3191 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3192 string signature;
3193 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3194}
3195
3196/*
3197 * SigningOperationsTest.RsaPssSha512TooSmallKey
3198 *
3199 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3200 * used with a key that is too small for the message.
3201 *
3202 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3203 * keymint specification requires that salt_size == digest_size, so the message will be
3204 * digest_size * 2 +
3205 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3206 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3207 * for a 1024-bit key.
3208 */
3209TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003210 if (SecLevel() == SecurityLevel::STRONGBOX) {
3211 GTEST_SKIP() << "Test not applicable to StrongBox device";
3212 }
Selene Huang31ab4042020-04-29 04:22:39 -07003213 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3214 .RsaSigningKey(1024, 65537)
3215 .Digest(Digest::SHA_2_512)
3216 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003217 .Padding(PaddingMode::RSA_PSS)
3218 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003219 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3220 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3221 .Digest(Digest::SHA_2_512)
3222 .Padding(PaddingMode::RSA_PSS)));
3223}
3224
3225/*
3226 * SigningOperationsTest.RsaNoPaddingTooLong
3227 *
3228 * Verifies that raw RSA signature operations fail with the correct error code when
3229 * given a too-long message.
3230 */
3231TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3232 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3233 .RsaSigningKey(2048, 65537)
3234 .Digest(Digest::NONE)
3235 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003236 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3237 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003238 // One byte too long
3239 string message(2048 / 8 + 1, 'a');
3240 ASSERT_EQ(ErrorCode::OK,
3241 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3242 .Digest(Digest::NONE)
3243 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3244 string result;
3245 ErrorCode finish_error_code = Finish(message, &result);
3246 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3247 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3248
3249 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3250 message = string(128 * 1024, 'a');
3251 ASSERT_EQ(ErrorCode::OK,
3252 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3253 .Digest(Digest::NONE)
3254 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3255 finish_error_code = Finish(message, &result);
3256 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3257 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3258}
3259
3260/*
3261 * SigningOperationsTest.RsaAbort
3262 *
3263 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3264 * test, but the behavior should be algorithm and purpose-independent.
3265 */
3266TEST_P(SigningOperationsTest, RsaAbort) {
3267 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3268 .RsaSigningKey(2048, 65537)
3269 .Digest(Digest::NONE)
3270 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003271 .Padding(PaddingMode::NONE)
3272 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003273
3274 ASSERT_EQ(ErrorCode::OK,
3275 Begin(KeyPurpose::SIGN,
3276 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3277 EXPECT_EQ(ErrorCode::OK, Abort());
3278
3279 // Another abort should fail
3280 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3281
3282 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003283 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003284}
3285
3286/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003287 * SigningOperationsTest.RsaNonUniqueParams
3288 *
3289 * Verifies that an operation with multiple padding modes is rejected.
3290 */
3291TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3292 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3293 .RsaSigningKey(2048, 65537)
3294 .Digest(Digest::NONE)
3295 .Digest(Digest::SHA1)
3296 .Authorization(TAG_NO_AUTH_REQUIRED)
3297 .Padding(PaddingMode::NONE)
3298 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3299 .SetDefaultValidity()));
3300
3301 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3302 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3303 .Digest(Digest::NONE)
3304 .Padding(PaddingMode::NONE)
3305 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3306
Tommy Chiuc93c4392021-05-11 18:36:50 +08003307 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3308 .Digest(Digest::NONE)
3309 .Digest(Digest::SHA1)
3310 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3311 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003312
3313 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3314 Begin(KeyPurpose::SIGN,
3315 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3316}
3317
3318/*
Selene Huang31ab4042020-04-29 04:22:39 -07003319 * SigningOperationsTest.RsaUnsupportedPadding
3320 *
3321 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3322 * with a padding mode inappropriate for RSA.
3323 */
3324TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3326 .RsaSigningKey(2048, 65537)
3327 .Authorization(TAG_NO_AUTH_REQUIRED)
3328 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003329 .Padding(PaddingMode::PKCS7)
3330 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003331 ASSERT_EQ(
3332 ErrorCode::UNSUPPORTED_PADDING_MODE,
3333 Begin(KeyPurpose::SIGN,
3334 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003335 CheckedDeleteKey();
3336
3337 ASSERT_EQ(ErrorCode::OK,
3338 GenerateKey(
3339 AuthorizationSetBuilder()
3340 .RsaSigningKey(2048, 65537)
3341 .Authorization(TAG_NO_AUTH_REQUIRED)
3342 .Digest(Digest::SHA_2_256 /* supported digest */)
3343 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3344 .SetDefaultValidity()));
3345 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3346 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3347 .Digest(Digest::SHA_2_256)
3348 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003349}
3350
3351/*
3352 * SigningOperationsTest.RsaPssNoDigest
3353 *
3354 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3355 */
3356TEST_P(SigningOperationsTest, RsaNoDigest) {
3357 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3358 .RsaSigningKey(2048, 65537)
3359 .Authorization(TAG_NO_AUTH_REQUIRED)
3360 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003361 .Padding(PaddingMode::RSA_PSS)
3362 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003363 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3364 Begin(KeyPurpose::SIGN,
3365 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3366
3367 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3368 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3369}
3370
3371/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003372 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003373 *
3374 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3375 * supported in some cases (as validated in other tests), but a mode must be specified.
3376 */
3377TEST_P(SigningOperationsTest, RsaNoPadding) {
3378 // Padding must be specified
3379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3380 .RsaKey(2048, 65537)
3381 .Authorization(TAG_NO_AUTH_REQUIRED)
3382 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003383 .Digest(Digest::NONE)
3384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003385 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3386 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3387}
3388
3389/*
3390 * SigningOperationsTest.RsaShortMessage
3391 *
3392 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3393 */
3394TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3396 .Authorization(TAG_NO_AUTH_REQUIRED)
3397 .RsaSigningKey(2048, 65537)
3398 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003399 .Padding(PaddingMode::NONE)
3400 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003401
3402 // Barely shorter
3403 string message(2048 / 8 - 1, 'a');
3404 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3405
3406 // Much shorter
3407 message = "a";
3408 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3409}
3410
3411/*
3412 * SigningOperationsTest.RsaSignWithEncryptionKey
3413 *
3414 * Verifies that RSA encryption keys cannot be used to sign.
3415 */
3416TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3417 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3418 .Authorization(TAG_NO_AUTH_REQUIRED)
3419 .RsaEncryptionKey(2048, 65537)
3420 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003421 .Padding(PaddingMode::NONE)
3422 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003423 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3424 Begin(KeyPurpose::SIGN,
3425 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3426}
3427
3428/*
3429 * SigningOperationsTest.RsaSignTooLargeMessage
3430 *
3431 * Verifies that attempting a raw signature of a message which is the same length as the key,
3432 * but numerically larger than the public modulus, fails with the correct error.
3433 */
3434TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3435 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3436 .Authorization(TAG_NO_AUTH_REQUIRED)
3437 .RsaSigningKey(2048, 65537)
3438 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003439 .Padding(PaddingMode::NONE)
3440 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003441
3442 // Largest possible message will always be larger than the public modulus.
3443 string message(2048 / 8, static_cast<char>(0xff));
3444 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3445 .Authorization(TAG_NO_AUTH_REQUIRED)
3446 .Digest(Digest::NONE)
3447 .Padding(PaddingMode::NONE)));
3448 string signature;
3449 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3450}
3451
3452/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003453 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3454 *
David Drysdale42fe1892021-10-14 14:43:46 +01003455 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003456 */
3457TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003458
3459 string message = "1234567890";
3460 string corrupt_message = "2234567890";
3461 for (auto curve : ValidCurves()) {
3462 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003463 // Ed25519 only allows Digest::NONE.
3464 auto digests = (curve == EcCurve::CURVE_25519)
3465 ? std::vector<Digest>(1, Digest::NONE)
3466 : ValidDigests(true /* withNone */, false /* withMD5 */);
3467
David Drysdaledf8f52e2021-05-06 08:10:58 +01003468 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3469 .Authorization(TAG_NO_AUTH_REQUIRED)
3470 .EcdsaSigningKey(curve)
3471 .Digest(digests)
3472 .SetDefaultValidity());
3473 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3474 if (error != ErrorCode::OK) {
3475 continue;
3476 }
3477
3478 for (auto digest : digests) {
3479 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3480 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3481 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3482 }
3483
3484 auto rc = DeleteKey();
3485 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3486 }
3487}
3488
3489/*
Selene Huang31ab4042020-04-29 04:22:39 -07003490 * SigningOperationsTest.EcdsaAllCurves
3491 *
David Drysdale42fe1892021-10-14 14:43:46 +01003492 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003493 */
3494TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3495 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003496 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3497 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003498 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3499 .Authorization(TAG_NO_AUTH_REQUIRED)
3500 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003501 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003502 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003503 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3504 if (error != ErrorCode::OK) continue;
3505
3506 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003507 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003508 CheckedDeleteKey();
3509 }
3510}
3511
3512/*
David Drysdale42fe1892021-10-14 14:43:46 +01003513 * SigningOperationsTest.EcdsaCurve25519
3514 *
3515 * Verifies that ECDSA operations succeed with curve25519.
3516 */
3517TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3518 if (!Curve25519Supported()) {
3519 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3520 }
3521
3522 EcCurve curve = EcCurve::CURVE_25519;
3523 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3524 .Authorization(TAG_NO_AUTH_REQUIRED)
3525 .EcdsaSigningKey(curve)
3526 .Digest(Digest::NONE)
3527 .SetDefaultValidity());
3528 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3529
3530 string message(1024, 'a');
3531 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3532 CheckedDeleteKey();
3533}
3534
3535/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003536 * SigningOperationsTest.EcdsaCurve25519MaxSize
3537 *
3538 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3539 */
3540TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3541 if (!Curve25519Supported()) {
3542 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3543 }
3544
3545 EcCurve curve = EcCurve::CURVE_25519;
3546 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3547 .Authorization(TAG_NO_AUTH_REQUIRED)
3548 .EcdsaSigningKey(curve)
3549 .Digest(Digest::NONE)
3550 .SetDefaultValidity());
3551 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3552
3553 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3554
3555 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3556 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3557 string message(msg_size, 'a');
3558
3559 // Attempt to sign via Begin+Finish.
3560 AuthorizationSet out_params;
3561 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3562 EXPECT_TRUE(out_params.empty());
3563 string signature;
3564 auto result = Finish(message, &signature);
3565 EXPECT_EQ(result, ErrorCode::OK);
3566 LocalVerifyMessage(message, signature, params);
3567
3568 // Attempt to sign via Begin+Update+Finish
3569 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3570 EXPECT_TRUE(out_params.empty());
3571 string output;
3572 result = Update(message, &output);
3573 EXPECT_EQ(result, ErrorCode::OK);
3574 EXPECT_EQ(output.size(), 0);
3575 string signature2;
3576 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3577 LocalVerifyMessage(message, signature2, params);
3578 }
3579
3580 CheckedDeleteKey();
3581}
3582
3583/*
3584 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3585 *
3586 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3587 */
3588TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3589 if (!Curve25519Supported()) {
3590 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3591 }
3592
3593 EcCurve curve = EcCurve::CURVE_25519;
3594 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3595 .Authorization(TAG_NO_AUTH_REQUIRED)
3596 .EcdsaSigningKey(curve)
3597 .Digest(Digest::NONE)
3598 .SetDefaultValidity());
3599 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3600
3601 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3602
3603 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3604 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3605 string message(msg_size, 'a');
3606
3607 // Attempt to sign via Begin+Finish.
3608 AuthorizationSet out_params;
3609 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3610 EXPECT_TRUE(out_params.empty());
3611 string signature;
3612 auto result = Finish(message, &signature);
3613 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3614
3615 // Attempt to sign via Begin+Update (but never get to Finish)
3616 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3617 EXPECT_TRUE(out_params.empty());
3618 string output;
3619 result = Update(message, &output);
3620 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3621 }
3622
3623 CheckedDeleteKey();
3624}
3625
3626/*
Selene Huang31ab4042020-04-29 04:22:39 -07003627 * SigningOperationsTest.EcdsaNoDigestHugeData
3628 *
3629 * Verifies that ECDSA operations support very large messages, even without digesting. This
3630 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3631 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3632 * the framework.
3633 */
3634TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3636 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003637 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003638 .Digest(Digest::NONE)
3639 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003640 string message(1 * 1024, 'a');
3641 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3642}
3643
3644/*
3645 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3646 *
3647 * Verifies that using an EC key requires the correct app ID/data.
3648 */
3649TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3651 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003652 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003653 .Digest(Digest::NONE)
3654 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003655 .Authorization(TAG_APPLICATION_DATA, "appdata")
3656 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003657
3658 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3659
Selene Huang31ab4042020-04-29 04:22:39 -07003660 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3661 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3662 AbortIfNeeded();
3663 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3664 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3665 .Digest(Digest::NONE)
3666 .Authorization(TAG_APPLICATION_ID, "clientid")));
3667 AbortIfNeeded();
3668 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3669 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3670 .Digest(Digest::NONE)
3671 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3672 AbortIfNeeded();
3673 EXPECT_EQ(ErrorCode::OK,
3674 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3675 .Digest(Digest::NONE)
3676 .Authorization(TAG_APPLICATION_DATA, "appdata")
3677 .Authorization(TAG_APPLICATION_ID, "clientid")));
3678 AbortIfNeeded();
3679}
3680
3681/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003682 * SigningOperationsTest.EcdsaIncompatibleDigest
3683 *
3684 * Verifies that using an EC key requires compatible digest.
3685 */
3686TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3688 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003689 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003690 .Digest(Digest::NONE)
3691 .Digest(Digest::SHA1)
3692 .SetDefaultValidity()));
3693 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3694 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3695 AbortIfNeeded();
3696}
3697
3698/*
Selene Huang31ab4042020-04-29 04:22:39 -07003699 * SigningOperationsTest.AesEcbSign
3700 *
3701 * Verifies that attempts to use AES keys to sign fail in the correct way.
3702 */
3703TEST_P(SigningOperationsTest, AesEcbSign) {
3704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3705 .Authorization(TAG_NO_AUTH_REQUIRED)
3706 .SigningKey()
3707 .AesEncryptionKey(128)
3708 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3709
3710 AuthorizationSet out_params;
3711 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3712 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3713 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3714 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3715}
3716
3717/*
3718 * SigningOperationsTest.HmacAllDigests
3719 *
3720 * Verifies that HMAC works with all digests.
3721 */
3722TEST_P(SigningOperationsTest, HmacAllDigests) {
3723 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003724 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3726 .Authorization(TAG_NO_AUTH_REQUIRED)
3727 .HmacKey(128)
3728 .Digest(digest)
3729 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3730 << "Failed to create HMAC key with digest " << digest;
3731 string message = "12345678901234567890123456789012";
3732 string signature = MacMessage(message, digest, 160);
3733 EXPECT_EQ(160U / 8U, signature.size())
3734 << "Failed to sign with HMAC key with digest " << digest;
3735 CheckedDeleteKey();
3736 }
3737}
3738
3739/*
3740 * SigningOperationsTest.HmacSha256TooLargeMacLength
3741 *
3742 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3743 * digest size.
3744 */
3745TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3747 .Authorization(TAG_NO_AUTH_REQUIRED)
3748 .HmacKey(128)
3749 .Digest(Digest::SHA_2_256)
3750 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3751 AuthorizationSet output_params;
3752 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3753 AuthorizationSetBuilder()
3754 .Digest(Digest::SHA_2_256)
3755 .Authorization(TAG_MAC_LENGTH, 264),
3756 &output_params));
3757}
3758
3759/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003760 * SigningOperationsTest.HmacSha256InvalidMacLength
3761 *
3762 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3763 * not a multiple of 8.
3764 */
3765TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3767 .Authorization(TAG_NO_AUTH_REQUIRED)
3768 .HmacKey(128)
3769 .Digest(Digest::SHA_2_256)
3770 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3771 AuthorizationSet output_params;
3772 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3773 AuthorizationSetBuilder()
3774 .Digest(Digest::SHA_2_256)
3775 .Authorization(TAG_MAC_LENGTH, 161),
3776 &output_params));
3777}
3778
3779/*
Selene Huang31ab4042020-04-29 04:22:39 -07003780 * SigningOperationsTest.HmacSha256TooSmallMacLength
3781 *
3782 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3783 * specified minimum MAC length.
3784 */
3785TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3787 .Authorization(TAG_NO_AUTH_REQUIRED)
3788 .HmacKey(128)
3789 .Digest(Digest::SHA_2_256)
3790 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3791 AuthorizationSet output_params;
3792 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3793 AuthorizationSetBuilder()
3794 .Digest(Digest::SHA_2_256)
3795 .Authorization(TAG_MAC_LENGTH, 120),
3796 &output_params));
3797}
3798
3799/*
3800 * SigningOperationsTest.HmacRfc4231TestCase3
3801 *
3802 * Validates against the test vectors from RFC 4231 test case 3.
3803 */
3804TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3805 string key(20, 0xaa);
3806 string message(50, 0xdd);
3807 uint8_t sha_224_expected[] = {
3808 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3809 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3810 };
3811 uint8_t sha_256_expected[] = {
3812 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3813 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3814 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3815 };
3816 uint8_t sha_384_expected[] = {
3817 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3818 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3819 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3820 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3821 };
3822 uint8_t sha_512_expected[] = {
3823 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3824 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3825 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3826 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3827 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3828 };
3829
3830 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3831 if (SecLevel() != SecurityLevel::STRONGBOX) {
3832 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3833 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3834 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3835 }
3836}
3837
3838/*
3839 * SigningOperationsTest.HmacRfc4231TestCase5
3840 *
3841 * Validates against the test vectors from RFC 4231 test case 5.
3842 */
3843TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3844 string key(20, 0x0c);
3845 string message = "Test With Truncation";
3846
3847 uint8_t sha_224_expected[] = {
3848 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3849 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3850 };
3851 uint8_t sha_256_expected[] = {
3852 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3853 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3854 };
3855 uint8_t sha_384_expected[] = {
3856 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3857 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3858 };
3859 uint8_t sha_512_expected[] = {
3860 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3861 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3862 };
3863
3864 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3865 if (SecLevel() != SecurityLevel::STRONGBOX) {
3866 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3867 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3868 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3869 }
3870}
3871
3872INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3873
3874typedef KeyMintAidlTestBase VerificationOperationsTest;
3875
3876/*
Selene Huang31ab4042020-04-29 04:22:39 -07003877 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3878 *
3879 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3880 */
3881TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3882 string key_material = "HelloThisIsAKey";
3883
3884 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003885 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003886 EXPECT_EQ(ErrorCode::OK,
3887 ImportKey(AuthorizationSetBuilder()
3888 .Authorization(TAG_NO_AUTH_REQUIRED)
3889 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3890 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3891 .Digest(Digest::SHA_2_256)
3892 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3893 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3894 EXPECT_EQ(ErrorCode::OK,
3895 ImportKey(AuthorizationSetBuilder()
3896 .Authorization(TAG_NO_AUTH_REQUIRED)
3897 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3898 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3899 .Digest(Digest::SHA_2_256)
3900 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3901 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3902
3903 string message = "This is a message.";
3904 string signature = SignMessage(
3905 signing_key, message,
3906 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3907
3908 // Signing key should not work.
3909 AuthorizationSet out_params;
3910 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3911 Begin(KeyPurpose::VERIFY, signing_key,
3912 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3913
3914 // Verification key should work.
3915 VerifyMessage(verification_key, message, signature,
3916 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3917
3918 CheckedDeleteKey(&signing_key);
3919 CheckedDeleteKey(&verification_key);
3920}
3921
Prashant Patildec9fdc2021-12-08 15:25:47 +00003922/*
3923 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3924 *
3925 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3926 */
3927TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3928 string key_material = "HelloThisIsAKey";
3929
3930 vector<uint8_t> signing_key, verification_key;
3931 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3932 EXPECT_EQ(ErrorCode::OK,
3933 ImportKey(AuthorizationSetBuilder()
3934 .Authorization(TAG_NO_AUTH_REQUIRED)
3935 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3936 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3937 .Digest(Digest::SHA_2_256)
3938 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3939 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3940 EXPECT_EQ(ErrorCode::OK,
3941 ImportKey(AuthorizationSetBuilder()
3942 .Authorization(TAG_NO_AUTH_REQUIRED)
3943 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3944 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3945 .Digest(Digest::SHA_2_256)
3946 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3947 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3948
3949 string message = "This is a message.";
3950 string signature = SignMessage(
3951 signing_key, message,
3952 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3953
3954 AuthorizationSet begin_out_params;
3955 ASSERT_EQ(ErrorCode::OK,
3956 Begin(KeyPurpose::VERIFY, verification_key,
3957 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3958
3959 string corruptMessage = "This is b message."; // Corrupted message
3960 string output;
3961 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3962
3963 ASSERT_EQ(ErrorCode::OK,
3964 Begin(KeyPurpose::VERIFY, verification_key,
3965 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3966
3967 signature[0] += 1; // Corrupt a signature
3968 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3969
3970 CheckedDeleteKey(&signing_key);
3971 CheckedDeleteKey(&verification_key);
3972}
3973
Selene Huang31ab4042020-04-29 04:22:39 -07003974INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3975
3976typedef KeyMintAidlTestBase ExportKeyTest;
3977
3978/*
3979 * ExportKeyTest.RsaUnsupportedKeyFormat
3980 *
3981 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3982 */
3983// TODO(seleneh) add ExportKey to GenerateKey
3984// check result
3985
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003986class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003987 public:
3988 template <TagType tag_type, Tag tag, typename ValueT>
3989 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3990 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003991 for (auto& entry : key_characteristics_) {
3992 if (entry.securityLevel == SecLevel()) {
3993 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3994 << "Tag " << tag << " with value " << expected
3995 << " not found at security level" << entry.securityLevel;
3996 } else {
3997 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3998 << "Tag " << tag << " found at security level " << entry.securityLevel;
3999 }
Selene Huang31ab4042020-04-29 04:22:39 -07004000 }
4001 }
4002
4003 void CheckOrigin() {
4004 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07004005 // Origin isn't a crypto param, but it always lives with them.
4006 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07004007 }
4008};
4009
4010/*
4011 * ImportKeyTest.RsaSuccess
4012 *
4013 * Verifies that importing and using an RSA key pair works correctly.
4014 */
4015TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07004016 uint32_t key_size;
4017 string key;
4018
4019 if (SecLevel() == SecurityLevel::STRONGBOX) {
4020 key_size = 2048;
4021 key = rsa_2048_key;
4022 } else {
4023 key_size = 1024;
4024 key = rsa_key;
4025 }
4026
Selene Huang31ab4042020-04-29 04:22:39 -07004027 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4028 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004029 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004030 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004031 .Padding(PaddingMode::RSA_PSS)
4032 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004033 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004034
4035 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004036 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004037 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4038 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4039 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4040 CheckOrigin();
4041
4042 string message(1024 / 8, 'a');
4043 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4044 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004045 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004046}
4047
4048/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004049 * ImportKeyTest.RsaSuccessWithoutParams
4050 *
4051 * Verifies that importing and using an RSA key pair without specifying parameters
4052 * works correctly.
4053 */
4054TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4055 uint32_t key_size;
4056 string key;
4057
4058 if (SecLevel() == SecurityLevel::STRONGBOX) {
4059 key_size = 2048;
4060 key = rsa_2048_key;
4061 } else {
4062 key_size = 1024;
4063 key = rsa_key;
4064 }
4065
4066 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4067 .Authorization(TAG_NO_AUTH_REQUIRED)
4068 .SigningKey()
4069 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4070 .Digest(Digest::SHA_2_256)
4071 .Padding(PaddingMode::RSA_PSS)
4072 .SetDefaultValidity(),
4073 KeyFormat::PKCS8, key));
4074
4075 // Key size and public exponent are determined from the imported key material.
4076 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4077 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4078
4079 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4080 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4081 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4082 CheckOrigin();
4083
4084 string message(1024 / 8, 'a');
4085 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4086 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004087 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004088}
4089
4090/*
Selene Huang31ab4042020-04-29 04:22:39 -07004091 * ImportKeyTest.RsaKeySizeMismatch
4092 *
4093 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4094 * correct way.
4095 */
4096TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4097 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4098 ImportKey(AuthorizationSetBuilder()
4099 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4100 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004101 .Padding(PaddingMode::NONE)
4102 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004103 KeyFormat::PKCS8, rsa_key));
4104}
4105
4106/*
4107 * ImportKeyTest.RsaPublicExponentMismatch
4108 *
4109 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4110 * fails in the correct way.
4111 */
4112TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4113 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4114 ImportKey(AuthorizationSetBuilder()
4115 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4116 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004117 .Padding(PaddingMode::NONE)
4118 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004119 KeyFormat::PKCS8, rsa_key));
4120}
4121
4122/*
David Drysdalee60248c2021-10-04 12:54:13 +01004123 * ImportKeyTest.RsaAttestMultiPurposeFail
4124 *
4125 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4126 */
4127TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004128 if (AidlVersion() < 2) {
4129 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4130 // with other key purposes. However, this was not checked at the time
4131 // so we can only be strict about checking this for implementations of KeyMint
4132 // version 2 and above.
4133 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4134 }
David Drysdalee60248c2021-10-04 12:54:13 +01004135 uint32_t key_size = 2048;
4136 string key = rsa_2048_key;
4137
4138 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4139 ImportKey(AuthorizationSetBuilder()
4140 .Authorization(TAG_NO_AUTH_REQUIRED)
4141 .RsaSigningKey(key_size, 65537)
4142 .AttestKey()
4143 .Digest(Digest::SHA_2_256)
4144 .Padding(PaddingMode::RSA_PSS)
4145 .SetDefaultValidity(),
4146 KeyFormat::PKCS8, key));
4147}
4148
4149/*
Selene Huang31ab4042020-04-29 04:22:39 -07004150 * ImportKeyTest.EcdsaSuccess
4151 *
4152 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4153 */
4154TEST_P(ImportKeyTest, EcdsaSuccess) {
4155 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4156 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004157 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004158 .Digest(Digest::SHA_2_256)
4159 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004160 KeyFormat::PKCS8, ec_256_key));
4161
4162 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004163 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4164 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4165
4166 CheckOrigin();
4167
4168 string message(32, 'a');
4169 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4170 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004171 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004172}
4173
4174/*
4175 * ImportKeyTest.EcdsaP256RFC5915Success
4176 *
4177 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4178 * correctly.
4179 */
4180TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4181 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4182 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004183 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004184 .Digest(Digest::SHA_2_256)
4185 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004186 KeyFormat::PKCS8, ec_256_key_rfc5915));
4187
4188 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004189 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4190 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4191
4192 CheckOrigin();
4193
4194 string message(32, 'a');
4195 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4196 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004197 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004198}
4199
4200/*
4201 * ImportKeyTest.EcdsaP256SEC1Success
4202 *
4203 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4204 */
4205TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4206 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4207 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004208 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004209 .Digest(Digest::SHA_2_256)
4210 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004211 KeyFormat::PKCS8, ec_256_key_sec1));
4212
4213 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004214 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4215 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4216
4217 CheckOrigin();
4218
4219 string message(32, 'a');
4220 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4221 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004222 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004223}
4224
4225/*
4226 * ImportKeyTest.Ecdsa521Success
4227 *
4228 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4229 */
4230TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004231 if (SecLevel() == SecurityLevel::STRONGBOX) {
4232 GTEST_SKIP() << "Test not applicable to StrongBox device";
4233 }
Selene Huang31ab4042020-04-29 04:22:39 -07004234 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4235 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004236 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004237 .Digest(Digest::SHA_2_256)
4238 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004239 KeyFormat::PKCS8, ec_521_key));
4240
4241 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004242 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4243 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4244 CheckOrigin();
4245
4246 string message(32, 'a');
4247 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4248 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004249 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004250}
4251
4252/*
Selene Huang31ab4042020-04-29 04:22:39 -07004253 * ImportKeyTest.EcdsaCurveMismatch
4254 *
4255 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4256 * the correct way.
4257 */
4258TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4259 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4260 ImportKey(AuthorizationSetBuilder()
4261 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004262 .Digest(Digest::NONE)
4263 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004264 KeyFormat::PKCS8, ec_256_key));
4265}
4266
4267/*
David Drysdalee60248c2021-10-04 12:54:13 +01004268 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4269 *
4270 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4271 */
4272TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004273 if (AidlVersion() < 2) {
4274 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4275 // with other key purposes. However, this was not checked at the time
4276 // so we can only be strict about checking this for implementations of KeyMint
4277 // version 2 and above.
4278 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4279 }
David Drysdalee60248c2021-10-04 12:54:13 +01004280 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4281 ImportKey(AuthorizationSetBuilder()
4282 .Authorization(TAG_NO_AUTH_REQUIRED)
4283 .EcdsaSigningKey(EcCurve::P_256)
4284 .AttestKey()
4285 .Digest(Digest::SHA_2_256)
4286 .SetDefaultValidity(),
4287 KeyFormat::PKCS8, ec_256_key));
4288}
4289
4290/*
David Drysdale42fe1892021-10-14 14:43:46 +01004291 * ImportKeyTest.Ed25519RawSuccess
4292 *
4293 * Verifies that importing and using a raw Ed25519 private key works correctly.
4294 */
4295TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4296 if (!Curve25519Supported()) {
4297 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4298 }
4299
4300 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4301 .Authorization(TAG_NO_AUTH_REQUIRED)
4302 .EcdsaSigningKey(EcCurve::CURVE_25519)
4303 .Digest(Digest::NONE)
4304 .SetDefaultValidity(),
4305 KeyFormat::RAW, ed25519_key));
4306 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4307 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4308 CheckOrigin();
4309
4310 // The returned cert should hold the correct public key.
4311 ASSERT_GT(cert_chain_.size(), 0);
4312 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4313 ASSERT_NE(kmKeyCert, nullptr);
4314 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4315 ASSERT_NE(kmPubKey.get(), nullptr);
4316 size_t kmPubKeySize = 32;
4317 uint8_t kmPubKeyData[32];
4318 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4319 ASSERT_EQ(kmPubKeySize, 32);
4320 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4321
4322 string message(32, 'a');
4323 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4324 string signature = SignMessage(message, params);
4325 LocalVerifyMessage(message, signature, params);
4326}
4327
4328/*
4329 * ImportKeyTest.Ed25519Pkcs8Success
4330 *
4331 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4332 */
4333TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4334 if (!Curve25519Supported()) {
4335 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4336 }
4337
4338 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4339 .Authorization(TAG_NO_AUTH_REQUIRED)
4340 .EcdsaSigningKey(EcCurve::CURVE_25519)
4341 .Digest(Digest::NONE)
4342 .SetDefaultValidity(),
4343 KeyFormat::PKCS8, ed25519_pkcs8_key));
4344 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4345 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4346 CheckOrigin();
4347
4348 // The returned cert should hold the correct public key.
4349 ASSERT_GT(cert_chain_.size(), 0);
4350 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4351 ASSERT_NE(kmKeyCert, nullptr);
4352 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4353 ASSERT_NE(kmPubKey.get(), nullptr);
4354 size_t kmPubKeySize = 32;
4355 uint8_t kmPubKeyData[32];
4356 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4357 ASSERT_EQ(kmPubKeySize, 32);
4358 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4359
4360 string message(32, 'a');
4361 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4362 string signature = SignMessage(message, params);
4363 LocalVerifyMessage(message, signature, params);
4364}
4365
4366/*
4367 * ImportKeyTest.Ed25519CurveMismatch
4368 *
4369 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4370 * the correct way.
4371 */
4372TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4373 if (!Curve25519Supported()) {
4374 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4375 }
4376
4377 ASSERT_NE(ErrorCode::OK,
4378 ImportKey(AuthorizationSetBuilder()
4379 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4380 .Digest(Digest::NONE)
4381 .SetDefaultValidity(),
4382 KeyFormat::RAW, ed25519_key));
4383}
4384
4385/*
4386 * ImportKeyTest.Ed25519FormatMismatch
4387 *
4388 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4389 */
4390TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4391 if (!Curve25519Supported()) {
4392 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4393 }
4394
4395 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4396 .EcdsaSigningKey(EcCurve::CURVE_25519)
4397 .Digest(Digest::NONE)
4398 .SetDefaultValidity(),
4399 KeyFormat::PKCS8, ed25519_key));
4400 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4401 .EcdsaSigningKey(EcCurve::CURVE_25519)
4402 .Digest(Digest::NONE)
4403 .SetDefaultValidity(),
4404 KeyFormat::RAW, ed25519_pkcs8_key));
4405}
4406
4407/*
4408 * ImportKeyTest.Ed25519PurposeMismatch
4409 *
4410 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4411 */
4412TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4413 if (!Curve25519Supported()) {
4414 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4415 }
4416
4417 // Can't have both SIGN and ATTEST_KEY
4418 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4419 .EcdsaSigningKey(EcCurve::CURVE_25519)
4420 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4421 .Digest(Digest::NONE)
4422 .SetDefaultValidity(),
4423 KeyFormat::RAW, ed25519_key));
4424 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4425 // PKCS#8 format and so includes an OID).
4426 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4427 .EcdsaKey(EcCurve::CURVE_25519)
4428 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4429 .Digest(Digest::NONE)
4430 .SetDefaultValidity(),
4431 KeyFormat::PKCS8, ed25519_pkcs8_key));
4432}
4433
4434/*
4435 * ImportKeyTest.X25519RawSuccess
4436 *
4437 * Verifies that importing and using a raw X25519 private key works correctly.
4438 */
4439TEST_P(ImportKeyTest, X25519RawSuccess) {
4440 if (!Curve25519Supported()) {
4441 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4442 }
4443
4444 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4445 .Authorization(TAG_NO_AUTH_REQUIRED)
4446 .EcdsaKey(EcCurve::CURVE_25519)
4447 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4448 .SetDefaultValidity(),
4449 KeyFormat::RAW, x25519_key));
4450
4451 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4452 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4453 CheckOrigin();
4454}
4455
4456/*
4457 * ImportKeyTest.X25519Pkcs8Success
4458 *
4459 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4460 */
4461TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4462 if (!Curve25519Supported()) {
4463 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4464 }
4465
4466 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4467 .Authorization(TAG_NO_AUTH_REQUIRED)
4468 .EcdsaKey(EcCurve::CURVE_25519)
4469 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4470 .SetDefaultValidity(),
4471 KeyFormat::PKCS8, x25519_pkcs8_key));
4472
4473 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4474 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4475 CheckOrigin();
4476}
4477
4478/*
4479 * ImportKeyTest.X25519CurveMismatch
4480 *
4481 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4482 * the correct way.
4483 */
4484TEST_P(ImportKeyTest, X25519CurveMismatch) {
4485 if (!Curve25519Supported()) {
4486 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4487 }
4488
4489 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4490 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4491 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4492 .SetDefaultValidity(),
4493 KeyFormat::RAW, x25519_key));
4494}
4495
4496/*
4497 * ImportKeyTest.X25519FormatMismatch
4498 *
4499 * Verifies that importing an X25519 key with an invalid format fails.
4500 */
4501TEST_P(ImportKeyTest, X25519FormatMismatch) {
4502 if (!Curve25519Supported()) {
4503 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4504 }
4505
4506 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4507 .EcdsaKey(EcCurve::CURVE_25519)
4508 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4509 .SetDefaultValidity(),
4510 KeyFormat::PKCS8, x25519_key));
4511 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4512 .EcdsaKey(EcCurve::CURVE_25519)
4513 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4514 .SetDefaultValidity(),
4515 KeyFormat::RAW, x25519_pkcs8_key));
4516}
4517
4518/*
4519 * ImportKeyTest.X25519PurposeMismatch
4520 *
4521 * Verifies that importing an X25519 key pair with an invalid format fails.
4522 */
4523TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4524 if (!Curve25519Supported()) {
4525 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4526 }
4527
4528 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4529 .EcdsaKey(EcCurve::CURVE_25519)
4530 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4531 .SetDefaultValidity(),
4532 KeyFormat::PKCS8, x25519_pkcs8_key));
4533 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4534 .EcdsaSigningKey(EcCurve::CURVE_25519)
4535 .SetDefaultValidity(),
4536 KeyFormat::PKCS8, x25519_pkcs8_key));
4537}
4538
4539/*
Selene Huang31ab4042020-04-29 04:22:39 -07004540 * ImportKeyTest.AesSuccess
4541 *
4542 * Verifies that importing and using an AES key works.
4543 */
4544TEST_P(ImportKeyTest, AesSuccess) {
4545 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4546 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4547 .Authorization(TAG_NO_AUTH_REQUIRED)
4548 .AesEncryptionKey(key.size() * 8)
4549 .EcbMode()
4550 .Padding(PaddingMode::PKCS7),
4551 KeyFormat::RAW, key));
4552
4553 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4554 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4555 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4556 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4557 CheckOrigin();
4558
4559 string message = "Hello World!";
4560 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4561 string ciphertext = EncryptMessage(message, params);
4562 string plaintext = DecryptMessage(ciphertext, params);
4563 EXPECT_EQ(message, plaintext);
4564}
4565
4566/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004567 * ImportKeyTest.AesFailure
4568 *
4569 * Verifies that importing an invalid AES key fails.
4570 */
4571TEST_P(ImportKeyTest, AesFailure) {
4572 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4573 uint32_t bitlen = key.size() * 8;
4574 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004575 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004576 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004577 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004578 .Authorization(TAG_NO_AUTH_REQUIRED)
4579 .AesEncryptionKey(key_size)
4580 .EcbMode()
4581 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004582 KeyFormat::RAW, key);
4583 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004584 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4585 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004586 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004587
4588 // Explicit key size matches that of the provided key, but it's not a valid size.
4589 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4590 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4591 ImportKey(AuthorizationSetBuilder()
4592 .Authorization(TAG_NO_AUTH_REQUIRED)
4593 .AesEncryptionKey(long_key.size() * 8)
4594 .EcbMode()
4595 .Padding(PaddingMode::PKCS7),
4596 KeyFormat::RAW, long_key));
4597 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4598 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4599 ImportKey(AuthorizationSetBuilder()
4600 .Authorization(TAG_NO_AUTH_REQUIRED)
4601 .AesEncryptionKey(short_key.size() * 8)
4602 .EcbMode()
4603 .Padding(PaddingMode::PKCS7),
4604 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004605}
4606
4607/*
4608 * ImportKeyTest.TripleDesSuccess
4609 *
4610 * Verifies that importing and using a 3DES key works.
4611 */
4612TEST_P(ImportKeyTest, TripleDesSuccess) {
4613 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4614 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4615 .Authorization(TAG_NO_AUTH_REQUIRED)
4616 .TripleDesEncryptionKey(168)
4617 .EcbMode()
4618 .Padding(PaddingMode::PKCS7),
4619 KeyFormat::RAW, key));
4620
4621 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4622 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4623 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4624 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4625 CheckOrigin();
4626
4627 string message = "Hello World!";
4628 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4629 string ciphertext = EncryptMessage(message, params);
4630 string plaintext = DecryptMessage(ciphertext, params);
4631 EXPECT_EQ(message, plaintext);
4632}
4633
4634/*
4635 * ImportKeyTest.TripleDesFailure
4636 *
4637 * Verifies that importing an invalid 3DES key fails.
4638 */
4639TEST_P(ImportKeyTest, TripleDesFailure) {
4640 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004641 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004642 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004643 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004644 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004645 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004646 .Authorization(TAG_NO_AUTH_REQUIRED)
4647 .TripleDesEncryptionKey(key_size)
4648 .EcbMode()
4649 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004650 KeyFormat::RAW, key);
4651 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004652 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4653 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004654 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004655 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004656 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004657 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4658 ImportKey(AuthorizationSetBuilder()
4659 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004660 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004661 .EcbMode()
4662 .Padding(PaddingMode::PKCS7),
4663 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004664 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004665 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4666 ImportKey(AuthorizationSetBuilder()
4667 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004668 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004669 .EcbMode()
4670 .Padding(PaddingMode::PKCS7),
4671 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004672}
4673
4674/*
4675 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004676 *
4677 * Verifies that importing and using an HMAC key works.
4678 */
4679TEST_P(ImportKeyTest, HmacKeySuccess) {
4680 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4681 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4682 .Authorization(TAG_NO_AUTH_REQUIRED)
4683 .HmacKey(key.size() * 8)
4684 .Digest(Digest::SHA_2_256)
4685 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4686 KeyFormat::RAW, key));
4687
4688 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4689 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4690 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4691 CheckOrigin();
4692
4693 string message = "Hello World!";
4694 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4695 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4696}
4697
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004698/*
4699 * ImportKeyTest.GetKeyCharacteristics
4700 *
4701 * Verifies that imported keys have the correct characteristics.
4702 */
4703TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4704 vector<uint8_t> key_blob;
4705 vector<KeyCharacteristics> key_characteristics;
4706 auto base_builder = AuthorizationSetBuilder()
4707 .Padding(PaddingMode::NONE)
4708 .Authorization(TAG_NO_AUTH_REQUIRED)
4709 .SetDefaultValidity();
4710 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4711 Algorithm::TRIPLE_DES};
4712 ErrorCode result;
4713 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4714 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4715 for (auto alg : algorithms) {
4716 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4717 AuthorizationSetBuilder builder(base_builder);
4718 switch (alg) {
4719 case Algorithm::RSA:
4720 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4721
4722 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4723 &key_characteristics);
4724 break;
4725 case Algorithm::EC:
4726 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4727 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4728 &key_characteristics);
4729 break;
4730 case Algorithm::HMAC:
4731 builder.HmacKey(128)
4732 .Digest(Digest::SHA_2_256)
4733 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4734 result =
4735 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4736 break;
4737 case Algorithm::AES:
4738 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4739 result =
4740 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4741 break;
4742 case Algorithm::TRIPLE_DES:
4743 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4744 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4745 &key_characteristics);
4746 break;
4747 default:
4748 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4749 continue;
4750 }
4751 ASSERT_EQ(ErrorCode::OK, result);
4752 CheckCharacteristics(key_blob, key_characteristics);
4753 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4754 }
4755}
4756
Selene Huang31ab4042020-04-29 04:22:39 -07004757INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4758
4759auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004760 // IKeyMintDevice.aidl
4761 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4762 "020100" // INTEGER length 1 value 0x00 (version)
4763 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4764 "934bf94e2aa28a3f83c9f79297250262"
4765 "fbe3276b5a1c91159bbfa3ef8957aac8"
4766 "4b59b30b455a79c2973480823d8b3863"
4767 "c3deef4a8e243590268d80e18751a0e1"
4768 "30f67ce6a1ace9f79b95e097474febc9"
4769 "81195b1d13a69086c0863f66a7b7fdb4"
4770 "8792227b1ac5e2489febdf087ab54864"
4771 "83033a6f001ca5d1ec1e27f5c30f4cec"
4772 "2642074a39ae68aee552e196627a8e3d"
4773 "867e67a8c01b11e75f13cca0a97ab668"
4774 "b50cda07a8ecb7cd8e3dd7009c963653"
4775 "4f6f239cffe1fc8daa466f78b676c711"
4776 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4777 "99b801597d5220e307eaa5bee507fb94"
4778 "d1fa69f9e519b2de315bac92c36f2ea1"
4779 "fa1df4478c0ddedeae8c70e0233cd098"
4780 "040c" // OCTET STRING length 0x0c (initializationVector)
4781 "d796b02c370f1fa4cc0124f1"
4782 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4783 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4784 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4785 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4786 "3106" // SET length 0x06
4787 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4788 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4789 // } end SET
4790 // } end [1]
4791 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4792 "020120" // INTEGER length 1 value 0x20 (AES)
4793 // } end [2]
4794 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4795 "02020100" // INTEGER length 2 value 0x100
4796 // } end [3]
4797 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4798 "3103" // SET length 0x03 {
4799 "020101" // INTEGER length 1 value 0x01 (ECB)
4800 // } end SET
4801 // } end [4]
4802 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4803 "3103" // SET length 0x03 {
4804 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4805 // } end SET
4806 // } end [5]
4807 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4808 // (noAuthRequired)
4809 "0500" // NULL
4810 // } end [503]
4811 // } end SEQUENCE (AuthorizationList)
4812 // } end SEQUENCE (KeyDescription)
4813 "0420" // OCTET STRING length 0x20 (encryptedKey)
4814 "ccd540855f833a5e1480bfd2d36faf3a"
4815 "eee15df5beabe2691bc82dde2a7aa910"
4816 "0410" // OCTET STRING length 0x10 (tag)
4817 "64c9f689c60ff6223ab6e6999e0eb6e5"
4818 // } SEQUENCE (SecureKeyWrapper)
4819);
Selene Huang31ab4042020-04-29 04:22:39 -07004820
4821auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004822 // IKeyMintDevice.aidl
4823 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4824 "020100" // INTEGER length 1 value 0x00 (version)
4825 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4826 "aad93ed5924f283b4bb5526fbe7a1412"
4827 "f9d9749ec30db9062b29e574a8546f33"
4828 "c88732452f5b8e6a391ee76c39ed1712"
4829 "c61d8df6213dec1cffbc17a8c6d04c7b"
4830 "30893d8daa9b2015213e219468215532"
4831 "07f8f9931c4caba23ed3bee28b36947e"
4832 "47f10e0a5c3dc51c988a628daad3e5e1"
4833 "f4005e79c2d5a96c284b4b8d7e4948f3"
4834 "31e5b85dd5a236f85579f3ea1d1b8484"
4835 "87470bdb0ab4f81a12bee42c99fe0df4"
4836 "bee3759453e69ad1d68a809ce06b949f"
4837 "7694a990429b2fe81e066ff43e56a216"
4838 "02db70757922a4bcc23ab89f1e35da77"
4839 "586775f423e519c2ea394caf48a28d0c"
4840 "8020f1dcf6b3a68ec246f615ae96dae9"
4841 "a079b1f6eb959033c1af5c125fd94168"
4842 "040c" // OCTET STRING length 0x0c (initializationVector)
4843 "6d9721d08589581ab49204a3"
4844 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4845 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4846 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4847 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4848 "3106" // SET length 0x06
4849 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4850 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4851 // } end SET
4852 // } end [1]
4853 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4854 "020120" // INTEGER length 1 value 0x20 (AES)
4855 // } end [2]
4856 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4857 "02020100" // INTEGER length 2 value 0x100
4858 // } end [3]
4859 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4860 "3103" // SET length 0x03 {
4861 "020101" // INTEGER length 1 value 0x01 (ECB)
4862 // } end SET
4863 // } end [4]
4864 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4865 "3103" // SET length 0x03 {
4866 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4867 // } end SET
4868 // } end [5]
4869 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4870 // (noAuthRequired)
4871 "0500" // NULL
4872 // } end [503]
4873 // } end SEQUENCE (AuthorizationList)
4874 // } end SEQUENCE (KeyDescription)
4875 "0420" // OCTET STRING length 0x20 (encryptedKey)
4876 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4877 "c20d1f99a9a024a76f35c8e2cab9b68d"
4878 "0410" // OCTET STRING length 0x10 (tag)
4879 "2560c70109ae67c030f00b98b512a670"
4880 // } SEQUENCE (SecureKeyWrapper)
4881);
Selene Huang31ab4042020-04-29 04:22:39 -07004882
4883auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004884 // RFC 5208 s5
4885 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4886 "020100" // INTEGER length 1 value 0x00 (version)
4887 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4888 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4889 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4890 "0500" // NULL (parameters)
4891 // } SEQUENCE (AlgorithmIdentifier)
4892 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4893 // RFC 8017 A.1.2
4894 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4895 "020100" // INTEGER length 1 value 0x00 (version)
4896 "02820101" // INTEGER length 0x0101 (modulus) value...
4897 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4898 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4899 "7b06e673a837313d56b1c725150a3fef" // 0x30
4900 "86acbddc41bb759c2854eae32d35841e" // 0x40
4901 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4902 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4903 "312d7bd5921ffaea1347c157406fef71" // 0x70
4904 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4905 "f4645c11f5c1374c3886427411c44979" // 0x90
4906 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4907 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4908 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4909 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4910 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4911 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4912 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4913 "55" // 0x101
4914 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4915 "02820100" // INTEGER length 0x100 (privateExponent) value...
4916 "431447b6251908112b1ee76f99f3711a" // 0x10
4917 "52b6630960046c2de70de188d833f8b8" // 0x20
4918 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4919 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4920 "e710b630a03adc683b5d2c43080e52be" // 0x50
4921 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4922 "822bccff087d63c940ba8a45f670feb2" // 0x70
4923 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4924 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4925 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4926 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4927 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4928 "52659d5a5ba05b663737a8696281865b" // 0xd0
4929 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4930 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4931 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4932 "028181" // INTEGER length 0x81 (prime1) value...
4933 "00de392e18d682c829266cc3454e1d61" // 0x10
4934 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4935 "ff841be5bac82a164c5970007047b8c5" // 0x30
4936 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4937 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4938 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4939 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4940 "9e91346130748a6e3c124f9149d71c74" // 0x80
4941 "35"
4942 "028181" // INTEGER length 0x81 (prime2) value...
4943 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4944 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4945 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4946 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4947 "9ed39a2d934c880440aed8832f984316" // 0x50
4948 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4949 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4950 "b880677c068e1be936e81288815252a8" // 0x80
4951 "a1"
4952 "028180" // INTEGER length 0x80 (exponent1) value...
4953 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4954 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4955 "5a063212a4f105a3764743e53281988a" // 0x30
4956 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4957 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4958 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4959 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4960 "4719d6e2b9439823719cd08bcd031781" // 0x80
4961 "028181" // INTEGER length 0x81 (exponent2) value...
4962 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4963 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4964 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4965 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4966 "1254186af30b22c10582a8a43e34fe94" // 0x50
4967 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4968 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4969 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4970 "61"
4971 "028181" // INTEGER length 0x81 (coefficient) value...
4972 "00c931617c77829dfb1270502be9195c" // 0x10
4973 "8f2830885f57dba869536811e6864236" // 0x20
4974 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4975 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4976 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4977 "959356210723287b0affcc9f727044d4" // 0x60
4978 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4979 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4980 "22"
4981 // } SEQUENCE
4982 // } SEQUENCE ()
4983);
Selene Huang31ab4042020-04-29 04:22:39 -07004984
4985string zero_masking_key =
4986 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4987string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4988
4989class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4990
4991TEST_P(ImportWrappedKeyTest, Success) {
4992 auto wrapping_key_desc = AuthorizationSetBuilder()
4993 .RsaEncryptionKey(2048, 65537)
4994 .Digest(Digest::SHA_2_256)
4995 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004996 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4997 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004998
4999 ASSERT_EQ(ErrorCode::OK,
5000 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5001 AuthorizationSetBuilder()
5002 .Digest(Digest::SHA_2_256)
5003 .Padding(PaddingMode::RSA_OAEP)));
5004
5005 string message = "Hello World!";
5006 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5007 string ciphertext = EncryptMessage(message, params);
5008 string plaintext = DecryptMessage(ciphertext, params);
5009 EXPECT_EQ(message, plaintext);
5010}
5011
David Drysdaled2cc8c22021-04-15 13:29:45 +01005012/*
5013 * ImportWrappedKeyTest.SuccessSidsIgnored
5014 *
5015 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5016 * include Tag:USER_SECURE_ID.
5017 */
5018TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5019 auto wrapping_key_desc = AuthorizationSetBuilder()
5020 .RsaEncryptionKey(2048, 65537)
5021 .Digest(Digest::SHA_2_256)
5022 .Padding(PaddingMode::RSA_OAEP)
5023 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5024 .SetDefaultValidity();
5025
5026 int64_t password_sid = 42;
5027 int64_t biometric_sid = 24;
5028 ASSERT_EQ(ErrorCode::OK,
5029 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5030 AuthorizationSetBuilder()
5031 .Digest(Digest::SHA_2_256)
5032 .Padding(PaddingMode::RSA_OAEP),
5033 password_sid, biometric_sid));
5034
5035 string message = "Hello World!";
5036 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5037 string ciphertext = EncryptMessage(message, params);
5038 string plaintext = DecryptMessage(ciphertext, params);
5039 EXPECT_EQ(message, plaintext);
5040}
5041
Selene Huang31ab4042020-04-29 04:22:39 -07005042TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5043 auto wrapping_key_desc = AuthorizationSetBuilder()
5044 .RsaEncryptionKey(2048, 65537)
5045 .Digest(Digest::SHA_2_256)
5046 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005047 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5048 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005049
5050 ASSERT_EQ(ErrorCode::OK,
5051 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5052 AuthorizationSetBuilder()
5053 .Digest(Digest::SHA_2_256)
5054 .Padding(PaddingMode::RSA_OAEP)));
5055}
5056
5057TEST_P(ImportWrappedKeyTest, WrongMask) {
5058 auto wrapping_key_desc = AuthorizationSetBuilder()
5059 .RsaEncryptionKey(2048, 65537)
5060 .Digest(Digest::SHA_2_256)
5061 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005062 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5063 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005064
5065 ASSERT_EQ(
5066 ErrorCode::VERIFICATION_FAILED,
5067 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5068 AuthorizationSetBuilder()
5069 .Digest(Digest::SHA_2_256)
5070 .Padding(PaddingMode::RSA_OAEP)));
5071}
5072
5073TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5074 auto wrapping_key_desc = AuthorizationSetBuilder()
5075 .RsaEncryptionKey(2048, 65537)
5076 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005077 .Padding(PaddingMode::RSA_OAEP)
5078 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005079
5080 ASSERT_EQ(
5081 ErrorCode::INCOMPATIBLE_PURPOSE,
5082 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5083 AuthorizationSetBuilder()
5084 .Digest(Digest::SHA_2_256)
5085 .Padding(PaddingMode::RSA_OAEP)));
5086}
5087
David Drysdaled2cc8c22021-04-15 13:29:45 +01005088TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5089 auto wrapping_key_desc = AuthorizationSetBuilder()
5090 .RsaEncryptionKey(2048, 65537)
5091 .Digest(Digest::SHA_2_256)
5092 .Padding(PaddingMode::RSA_PSS)
5093 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5094 .SetDefaultValidity();
5095
5096 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5097 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5098 AuthorizationSetBuilder()
5099 .Digest(Digest::SHA_2_256)
5100 .Padding(PaddingMode::RSA_OAEP)));
5101}
5102
5103TEST_P(ImportWrappedKeyTest, WrongDigest) {
5104 auto wrapping_key_desc = AuthorizationSetBuilder()
5105 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005106 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005107 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005108 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5109 .SetDefaultValidity();
5110
5111 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5112 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5113 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005114 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005115 .Padding(PaddingMode::RSA_OAEP)));
5116}
5117
Selene Huang31ab4042020-04-29 04:22:39 -07005118INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5119
5120typedef KeyMintAidlTestBase EncryptionOperationsTest;
5121
5122/*
5123 * EncryptionOperationsTest.RsaNoPaddingSuccess
5124 *
David Drysdale59cae642021-05-12 13:52:03 +01005125 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005126 */
5127TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005128 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005129 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005130 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5131 .Authorization(TAG_NO_AUTH_REQUIRED)
5132 .RsaEncryptionKey(2048, exponent)
5133 .Padding(PaddingMode::NONE)
5134 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005135
David Drysdaled2cc8c22021-04-15 13:29:45 +01005136 string message = string(2048 / 8, 'a');
5137 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005138 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005139 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005140
David Drysdale59cae642021-05-12 13:52:03 +01005141 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005142 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005143
David Drysdaled2cc8c22021-04-15 13:29:45 +01005144 // Unpadded RSA is deterministic
5145 EXPECT_EQ(ciphertext1, ciphertext2);
5146
5147 CheckedDeleteKey();
5148 }
Selene Huang31ab4042020-04-29 04:22:39 -07005149}
5150
5151/*
5152 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5153 *
David Drysdale59cae642021-05-12 13:52:03 +01005154 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005155 */
5156TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5157 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5158 .Authorization(TAG_NO_AUTH_REQUIRED)
5159 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005160 .Padding(PaddingMode::NONE)
5161 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005162
5163 string message = "1";
5164 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5165
David Drysdale59cae642021-05-12 13:52:03 +01005166 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005167 EXPECT_EQ(2048U / 8, ciphertext.size());
5168
5169 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5170 string plaintext = DecryptMessage(ciphertext, params);
5171
5172 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005173}
5174
5175/*
Selene Huang31ab4042020-04-29 04:22:39 -07005176 * EncryptionOperationsTest.RsaOaepSuccess
5177 *
David Drysdale59cae642021-05-12 13:52:03 +01005178 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005179 */
5180TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5181 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5182
5183 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005184 ASSERT_EQ(ErrorCode::OK,
5185 GenerateKey(AuthorizationSetBuilder()
5186 .Authorization(TAG_NO_AUTH_REQUIRED)
5187 .RsaEncryptionKey(key_size, 65537)
5188 .Padding(PaddingMode::RSA_OAEP)
5189 .Digest(digests)
5190 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5191 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005192
5193 string message = "Hello";
5194
5195 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005196 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5197
5198 auto params = AuthorizationSetBuilder()
5199 .Digest(digest)
5200 .Padding(PaddingMode::RSA_OAEP)
5201 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5202 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005203 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5204 EXPECT_EQ(key_size / 8, ciphertext1.size());
5205
David Drysdale59cae642021-05-12 13:52:03 +01005206 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005207 EXPECT_EQ(key_size / 8, ciphertext2.size());
5208
5209 // OAEP randomizes padding so every result should be different (with astronomically high
5210 // probability).
5211 EXPECT_NE(ciphertext1, ciphertext2);
5212
5213 string plaintext1 = DecryptMessage(ciphertext1, params);
5214 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5215 string plaintext2 = DecryptMessage(ciphertext2, params);
5216 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5217
5218 // Decrypting corrupted ciphertext should fail.
5219 size_t offset_to_corrupt = random() % ciphertext1.size();
5220 char corrupt_byte;
5221 do {
5222 corrupt_byte = static_cast<char>(random() % 256);
5223 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5224 ciphertext1[offset_to_corrupt] = corrupt_byte;
5225
5226 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5227 string result;
5228 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5229 EXPECT_EQ(0U, result.size());
5230 }
5231}
5232
5233/*
5234 * EncryptionOperationsTest.RsaOaepInvalidDigest
5235 *
David Drysdale59cae642021-05-12 13:52:03 +01005236 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005237 * without a digest.
5238 */
5239TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5241 .Authorization(TAG_NO_AUTH_REQUIRED)
5242 .RsaEncryptionKey(2048, 65537)
5243 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005244 .Digest(Digest::NONE)
5245 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005246
5247 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005248 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005249}
5250
5251/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005252 * EncryptionOperationsTest.RsaOaepInvalidPadding
5253 *
David Drysdale59cae642021-05-12 13:52:03 +01005254 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005255 * with a padding value that is only suitable for signing/verifying.
5256 */
5257TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5258 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5259 .Authorization(TAG_NO_AUTH_REQUIRED)
5260 .RsaEncryptionKey(2048, 65537)
5261 .Padding(PaddingMode::RSA_PSS)
5262 .Digest(Digest::NONE)
5263 .SetDefaultValidity()));
5264
5265 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005266 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005267}
5268
5269/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005270 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005271 *
David Drysdale59cae642021-05-12 13:52:03 +01005272 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005273 * with a different digest than was used to encrypt.
5274 */
5275TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005276 if (SecLevel() == SecurityLevel::STRONGBOX) {
5277 GTEST_SKIP() << "Test not applicable to StrongBox device";
5278 }
Selene Huang31ab4042020-04-29 04:22:39 -07005279
5280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5281 .Authorization(TAG_NO_AUTH_REQUIRED)
5282 .RsaEncryptionKey(1024, 65537)
5283 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005284 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5285 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005286 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005287 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005288 message,
5289 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5290
5291 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5292 .Digest(Digest::SHA_2_256)
5293 .Padding(PaddingMode::RSA_OAEP)));
5294 string result;
5295 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5296 EXPECT_EQ(0U, result.size());
5297}
5298
5299/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005300 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5301 *
David Drysdale59cae642021-05-12 13:52:03 +01005302 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005303 * digests.
5304 */
5305TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5306 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5307
5308 size_t key_size = 2048; // Need largish key for SHA-512 test.
5309 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5310 .OaepMGFDigest(digests)
5311 .Authorization(TAG_NO_AUTH_REQUIRED)
5312 .RsaEncryptionKey(key_size, 65537)
5313 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005314 .Digest(Digest::SHA_2_256)
5315 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005316
5317 string message = "Hello";
5318
5319 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005320 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005321 auto params = AuthorizationSetBuilder()
5322 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5323 .Digest(Digest::SHA_2_256)
5324 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005325 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005326 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5327 EXPECT_EQ(key_size / 8, ciphertext1.size());
5328
David Drysdale59cae642021-05-12 13:52:03 +01005329 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005330 EXPECT_EQ(key_size / 8, ciphertext2.size());
5331
5332 // OAEP randomizes padding so every result should be different (with astronomically high
5333 // probability).
5334 EXPECT_NE(ciphertext1, ciphertext2);
5335
5336 string plaintext1 = DecryptMessage(ciphertext1, params);
5337 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5338 string plaintext2 = DecryptMessage(ciphertext2, params);
5339 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5340
5341 // Decrypting corrupted ciphertext should fail.
5342 size_t offset_to_corrupt = random() % ciphertext1.size();
5343 char corrupt_byte;
5344 do {
5345 corrupt_byte = static_cast<char>(random() % 256);
5346 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5347 ciphertext1[offset_to_corrupt] = corrupt_byte;
5348
5349 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5350 string result;
5351 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5352 EXPECT_EQ(0U, result.size());
5353 }
5354}
5355
5356/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005357 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5358 *
5359 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5360 * specified, defaulting to SHA-1.
5361 */
5362TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5363 size_t key_size = 2048;
5364 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5365 .Authorization(TAG_NO_AUTH_REQUIRED)
5366 .RsaEncryptionKey(key_size, 65537)
5367 .Padding(PaddingMode::RSA_OAEP)
5368 .Digest(Digest::SHA_2_256)
5369 .SetDefaultValidity()));
5370
5371 // Do local RSA encryption using the default MGF digest of SHA-1.
5372 string message = "Hello";
5373 auto params =
5374 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5375 string ciphertext = LocalRsaEncryptMessage(message, params);
5376 EXPECT_EQ(key_size / 8, ciphertext.size());
5377
5378 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5379 string plaintext = DecryptMessage(ciphertext, params);
5380 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5381
5382 // Decrypting corrupted ciphertext should fail.
5383 size_t offset_to_corrupt = random() % ciphertext.size();
5384 char corrupt_byte;
5385 do {
5386 corrupt_byte = static_cast<char>(random() % 256);
5387 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5388 ciphertext[offset_to_corrupt] = corrupt_byte;
5389
5390 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5391 string result;
5392 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5393 EXPECT_EQ(0U, result.size());
5394}
5395
5396/*
5397 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5398 *
5399 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5400 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5401 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5402 */
5403TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5404 size_t key_size = 2048;
5405 ASSERT_EQ(ErrorCode::OK,
5406 GenerateKey(AuthorizationSetBuilder()
5407 .Authorization(TAG_NO_AUTH_REQUIRED)
5408 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5409 .RsaEncryptionKey(key_size, 65537)
5410 .Padding(PaddingMode::RSA_OAEP)
5411 .Digest(Digest::SHA_2_256)
5412 .SetDefaultValidity()));
5413
5414 // Do local RSA encryption using the default MGF digest of SHA-1.
5415 string message = "Hello";
5416 auto params =
5417 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5418 string ciphertext = LocalRsaEncryptMessage(message, params);
5419 EXPECT_EQ(key_size / 8, ciphertext.size());
5420
5421 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5422 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5423 // is checked against those values, and found absent.
5424 auto result = Begin(KeyPurpose::DECRYPT, params);
5425 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5426 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5427}
5428
5429/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005430 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5431 *
David Drysdale59cae642021-05-12 13:52:03 +01005432 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005433 * with incompatible MGF digest.
5434 */
5435TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5436 ASSERT_EQ(ErrorCode::OK,
5437 GenerateKey(AuthorizationSetBuilder()
5438 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5439 .Authorization(TAG_NO_AUTH_REQUIRED)
5440 .RsaEncryptionKey(2048, 65537)
5441 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005442 .Digest(Digest::SHA_2_256)
5443 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005444 string message = "Hello World!";
5445
5446 auto params = AuthorizationSetBuilder()
5447 .Padding(PaddingMode::RSA_OAEP)
5448 .Digest(Digest::SHA_2_256)
5449 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005450 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005451}
5452
5453/*
5454 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5455 *
5456 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5457 * with unsupported MGF digest.
5458 */
5459TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5460 ASSERT_EQ(ErrorCode::OK,
5461 GenerateKey(AuthorizationSetBuilder()
5462 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5463 .Authorization(TAG_NO_AUTH_REQUIRED)
5464 .RsaEncryptionKey(2048, 65537)
5465 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005466 .Digest(Digest::SHA_2_256)
5467 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005468 string message = "Hello World!";
5469
5470 auto params = AuthorizationSetBuilder()
5471 .Padding(PaddingMode::RSA_OAEP)
5472 .Digest(Digest::SHA_2_256)
5473 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005474 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005475}
5476
5477/*
Selene Huang31ab4042020-04-29 04:22:39 -07005478 * EncryptionOperationsTest.RsaPkcs1Success
5479 *
5480 * Verifies that RSA PKCS encryption/decrypts works.
5481 */
5482TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5484 .Authorization(TAG_NO_AUTH_REQUIRED)
5485 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005486 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5487 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005488
5489 string message = "Hello World!";
5490 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005491 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005492 EXPECT_EQ(2048U / 8, ciphertext1.size());
5493
David Drysdale59cae642021-05-12 13:52:03 +01005494 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005495 EXPECT_EQ(2048U / 8, ciphertext2.size());
5496
5497 // PKCS1 v1.5 randomizes padding so every result should be different.
5498 EXPECT_NE(ciphertext1, ciphertext2);
5499
5500 string plaintext = DecryptMessage(ciphertext1, params);
5501 EXPECT_EQ(message, plaintext);
5502
5503 // Decrypting corrupted ciphertext should fail.
5504 size_t offset_to_corrupt = random() % ciphertext1.size();
5505 char corrupt_byte;
5506 do {
5507 corrupt_byte = static_cast<char>(random() % 256);
5508 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5509 ciphertext1[offset_to_corrupt] = corrupt_byte;
5510
5511 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5512 string result;
5513 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5514 EXPECT_EQ(0U, result.size());
5515}
5516
5517/*
Selene Huang31ab4042020-04-29 04:22:39 -07005518 * EncryptionOperationsTest.EcdsaEncrypt
5519 *
5520 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5521 */
5522TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5523 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5524 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005525 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005526 .Digest(Digest::NONE)
5527 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005528 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5529 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5530 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5531}
5532
5533/*
5534 * EncryptionOperationsTest.HmacEncrypt
5535 *
5536 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5537 */
5538TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5539 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5540 .Authorization(TAG_NO_AUTH_REQUIRED)
5541 .HmacKey(128)
5542 .Digest(Digest::SHA_2_256)
5543 .Padding(PaddingMode::NONE)
5544 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5545 auto params = AuthorizationSetBuilder()
5546 .Digest(Digest::SHA_2_256)
5547 .Padding(PaddingMode::NONE)
5548 .Authorization(TAG_MAC_LENGTH, 128);
5549 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5550 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5551}
5552
5553/*
5554 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5555 *
5556 * Verifies that AES ECB mode works.
5557 */
5558TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5560 .Authorization(TAG_NO_AUTH_REQUIRED)
5561 .AesEncryptionKey(128)
5562 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5563 .Padding(PaddingMode::NONE)));
5564
5565 ASSERT_GT(key_blob_.size(), 0U);
5566 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5567
5568 // Two-block message.
5569 string message = "12345678901234567890123456789012";
5570 string ciphertext1 = EncryptMessage(message, params);
5571 EXPECT_EQ(message.size(), ciphertext1.size());
5572
5573 string ciphertext2 = EncryptMessage(string(message), params);
5574 EXPECT_EQ(message.size(), ciphertext2.size());
5575
5576 // ECB is deterministic.
5577 EXPECT_EQ(ciphertext1, ciphertext2);
5578
5579 string plaintext = DecryptMessage(ciphertext1, params);
5580 EXPECT_EQ(message, plaintext);
5581}
5582
5583/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005584 * EncryptionOperationsTest.AesEcbUnknownTag
5585 *
5586 * Verifies that AES ECB operations ignore unknown tags.
5587 */
5588TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5589 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5590 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5591 KeyParameter unknown_param;
5592 unknown_param.tag = unknown_tag;
5593
5594 vector<KeyCharacteristics> key_characteristics;
5595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5596 .Authorization(TAG_NO_AUTH_REQUIRED)
5597 .AesEncryptionKey(128)
5598 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5599 .Padding(PaddingMode::NONE)
5600 .Authorization(unknown_param),
5601 &key_blob_, &key_characteristics));
5602 ASSERT_GT(key_blob_.size(), 0U);
5603
5604 // Unknown tags should not be returned in key characteristics.
5605 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5606 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5607 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5608 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5609
5610 // Encrypt without mentioning the unknown parameter.
5611 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5612 string message = "12345678901234567890123456789012";
5613 string ciphertext = EncryptMessage(message, params);
5614 EXPECT_EQ(message.size(), ciphertext.size());
5615
5616 // Decrypt including the unknown parameter.
5617 auto decrypt_params = AuthorizationSetBuilder()
5618 .BlockMode(BlockMode::ECB)
5619 .Padding(PaddingMode::NONE)
5620 .Authorization(unknown_param);
5621 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5622 EXPECT_EQ(message, plaintext);
5623}
5624
5625/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005626 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005627 *
5628 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5629 */
5630TEST_P(EncryptionOperationsTest, AesWrongMode) {
5631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5632 .Authorization(TAG_NO_AUTH_REQUIRED)
5633 .AesEncryptionKey(128)
5634 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5635 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005636 ASSERT_GT(key_blob_.size(), 0U);
5637
Selene Huang31ab4042020-04-29 04:22:39 -07005638 EXPECT_EQ(
5639 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5640 Begin(KeyPurpose::ENCRYPT,
5641 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5642}
5643
5644/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005645 * EncryptionOperationsTest.AesWrongPadding
5646 *
5647 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5648 */
5649TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5651 .Authorization(TAG_NO_AUTH_REQUIRED)
5652 .AesEncryptionKey(128)
5653 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5654 .Padding(PaddingMode::NONE)));
5655 ASSERT_GT(key_blob_.size(), 0U);
5656
5657 EXPECT_EQ(
5658 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5659 Begin(KeyPurpose::ENCRYPT,
5660 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5661}
5662
5663/*
5664 * EncryptionOperationsTest.AesInvalidParams
5665 *
5666 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5667 */
5668TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5670 .Authorization(TAG_NO_AUTH_REQUIRED)
5671 .AesEncryptionKey(128)
5672 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5673 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5674 .Padding(PaddingMode::NONE)
5675 .Padding(PaddingMode::PKCS7)));
5676 ASSERT_GT(key_blob_.size(), 0U);
5677
5678 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5679 .BlockMode(BlockMode::CBC)
5680 .BlockMode(BlockMode::ECB)
5681 .Padding(PaddingMode::NONE));
5682 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5683 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5684
5685 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5686 .BlockMode(BlockMode::ECB)
5687 .Padding(PaddingMode::NONE)
5688 .Padding(PaddingMode::PKCS7));
5689 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5690 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5691}
5692
5693/*
Selene Huang31ab4042020-04-29 04:22:39 -07005694 * EncryptionOperationsTest.AesWrongPurpose
5695 *
5696 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5697 * specified.
5698 */
5699TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5700 auto err = GenerateKey(AuthorizationSetBuilder()
5701 .Authorization(TAG_NO_AUTH_REQUIRED)
5702 .AesKey(128)
5703 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5704 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5705 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5706 .Padding(PaddingMode::NONE));
5707 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5708 ASSERT_GT(key_blob_.size(), 0U);
5709
5710 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5711 .BlockMode(BlockMode::GCM)
5712 .Padding(PaddingMode::NONE)
5713 .Authorization(TAG_MAC_LENGTH, 128));
5714 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5715
5716 CheckedDeleteKey();
5717
5718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5719 .Authorization(TAG_NO_AUTH_REQUIRED)
5720 .AesKey(128)
5721 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5722 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5723 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5724 .Padding(PaddingMode::NONE)));
5725
5726 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5727 .BlockMode(BlockMode::GCM)
5728 .Padding(PaddingMode::NONE)
5729 .Authorization(TAG_MAC_LENGTH, 128));
5730 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5731}
5732
5733/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005734 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005735 *
5736 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5737 * multiple of the block size and no padding is specified.
5738 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005739TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5740 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005741 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5743 .Authorization(TAG_NO_AUTH_REQUIRED)
5744 .AesEncryptionKey(128)
5745 .Authorization(TAG_BLOCK_MODE, blockMode)
5746 .Padding(PaddingMode::NONE)));
5747 // Message is slightly shorter than two blocks.
5748 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005749
David Drysdaled2cc8c22021-04-15 13:29:45 +01005750 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5751 AuthorizationSet out_params;
5752 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5753 string ciphertext;
5754 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5755 EXPECT_EQ(0U, ciphertext.size());
5756
5757 CheckedDeleteKey();
5758 }
Selene Huang31ab4042020-04-29 04:22:39 -07005759}
5760
5761/*
5762 * EncryptionOperationsTest.AesEcbPkcs7Padding
5763 *
5764 * Verifies that AES PKCS7 padding works for any message length.
5765 */
5766TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5768 .Authorization(TAG_NO_AUTH_REQUIRED)
5769 .AesEncryptionKey(128)
5770 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5771 .Padding(PaddingMode::PKCS7)));
5772
5773 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5774
5775 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005776 for (size_t i = 0; i <= 48; i++) {
5777 SCOPED_TRACE(testing::Message() << "i = " << i);
5778 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5779 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005780 string ciphertext = EncryptMessage(message, params);
5781 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5782 string plaintext = DecryptMessage(ciphertext, params);
5783 EXPECT_EQ(message, plaintext);
5784 }
5785}
5786
5787/*
5788 * EncryptionOperationsTest.AesEcbWrongPadding
5789 *
5790 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5791 * specified.
5792 */
5793TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5794 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5795 .Authorization(TAG_NO_AUTH_REQUIRED)
5796 .AesEncryptionKey(128)
5797 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5798 .Padding(PaddingMode::NONE)));
5799
5800 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5801
5802 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005803 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005804 string message(i, 'a');
5805 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5806 }
5807}
5808
5809/*
5810 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5811 *
5812 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5813 */
5814TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5815 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5816 .Authorization(TAG_NO_AUTH_REQUIRED)
5817 .AesEncryptionKey(128)
5818 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5819 .Padding(PaddingMode::PKCS7)));
5820
5821 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5822
5823 string message = "a";
5824 string ciphertext = EncryptMessage(message, params);
5825 EXPECT_EQ(16U, ciphertext.size());
5826 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005827
Seth Moore7a55ae32021-06-23 14:28:11 -07005828 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5829 ++ciphertext[ciphertext.size() / 2];
5830
5831 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5832 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005833 ErrorCode error = Finish(ciphertext, &plaintext);
5834 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005835 // This is the expected error, we can exit the test now.
5836 return;
5837 } else {
5838 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005839 ASSERT_EQ(error, ErrorCode::OK)
5840 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005841 }
5842 }
5843 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005844}
5845
David Drysdaleb8093292022-04-08 12:22:35 +01005846/*
5847 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5848 *
5849 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5850 */
5851TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5852 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5853 .Authorization(TAG_NO_AUTH_REQUIRED)
5854 .AesEncryptionKey(128)
5855 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5856 .Padding(PaddingMode::PKCS7)));
5857
5858 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5859
5860 string message = "a";
5861 string ciphertext = EncryptMessage(message, params);
5862 EXPECT_EQ(16U, ciphertext.size());
5863 EXPECT_NE(ciphertext, message);
5864
5865 // Shorten the ciphertext.
5866 ciphertext.resize(ciphertext.size() - 1);
5867 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5868 string plaintext;
5869 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5870}
5871
Selene Huang31ab4042020-04-29 04:22:39 -07005872vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5873 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005874 EXPECT_TRUE(iv);
5875 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005876}
5877
5878/*
5879 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5880 *
5881 * Verifies that AES CTR mode works.
5882 */
5883TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5885 .Authorization(TAG_NO_AUTH_REQUIRED)
5886 .AesEncryptionKey(128)
5887 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5888 .Padding(PaddingMode::NONE)));
5889
5890 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5891
5892 string message = "123";
5893 AuthorizationSet out_params;
5894 string ciphertext1 = EncryptMessage(message, params, &out_params);
5895 vector<uint8_t> iv1 = CopyIv(out_params);
5896 EXPECT_EQ(16U, iv1.size());
5897
5898 EXPECT_EQ(message.size(), ciphertext1.size());
5899
5900 out_params.Clear();
5901 string ciphertext2 = EncryptMessage(message, params, &out_params);
5902 vector<uint8_t> iv2 = CopyIv(out_params);
5903 EXPECT_EQ(16U, iv2.size());
5904
5905 // IVs should be random, so ciphertexts should differ.
5906 EXPECT_NE(ciphertext1, ciphertext2);
5907
5908 auto params_iv1 =
5909 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5910 auto params_iv2 =
5911 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5912
5913 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5914 EXPECT_EQ(message, plaintext);
5915 plaintext = DecryptMessage(ciphertext2, params_iv2);
5916 EXPECT_EQ(message, plaintext);
5917
5918 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5919 plaintext = DecryptMessage(ciphertext1, params_iv2);
5920 EXPECT_NE(message, plaintext);
5921 plaintext = DecryptMessage(ciphertext2, params_iv1);
5922 EXPECT_NE(message, plaintext);
5923}
5924
5925/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305926 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005927 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305928 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005929 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305930TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5931 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5932}
Selene Huang31ab4042020-04-29 04:22:39 -07005933
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305934/*
5935 * EncryptionOperationsTest.AesCbcIncremental
5936 *
5937 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5938 */
5939TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5940 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5941}
Selene Huang31ab4042020-04-29 04:22:39 -07005942
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305943/*
5944 * EncryptionOperationsTest.AesCtrIncremental
5945 *
5946 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5947 */
5948TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5949 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5950}
Selene Huang31ab4042020-04-29 04:22:39 -07005951
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305952/*
5953 * EncryptionOperationsTest.AesGcmIncremental
5954 *
5955 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5956 */
5957TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5958 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005959}
5960
Prashant Patildd5f7f02022-07-06 18:58:07 +00005961/*
5962 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5963 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5964 */
5965TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5966 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5967 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5968 string kat_plaintext =
5969 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5970 "809FFF37081C22EF278F896AB213A2A631");
5971 string kat_ciphertext =
5972 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5973 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5974 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5975 kat_ciphertext);
5976}
5977
5978/*
5979 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5980 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5981 */
5982TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5983 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5984 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5985 string kat_plaintext =
5986 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5987 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5988 string kat_ciphertext =
5989 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5990 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5991 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5992 kat_plaintext, kat_ciphertext);
5993}
5994
5995/*
5996 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5997 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5998 */
5999TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6000 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6001 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6002 string kat_plaintext =
6003 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6004 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6005 string kat_ciphertext =
6006 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6007 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6008 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6009 kat_ciphertext);
6010}
6011
6012/*
6013 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6014 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6015 */
6016TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6017 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6018 string kat_plaintext =
6019 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6020 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6021 string kat_ciphertext =
6022 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6023 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6024 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6025 kat_ciphertext);
6026}
6027
6028/*
6029 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6030 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6031 */
6032TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6033 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6034 string kat_plaintext =
6035 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6036 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6037 string kat_ciphertext =
6038 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6039 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6040 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6041 kat_ciphertext);
6042}
6043
6044/*
6045 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6046 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6047 */
6048TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6049 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6050 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6051 string kat_plaintext =
6052 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6053 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6054 string kat_ciphertext =
6055 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6056 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6057 "bdfcc0cba0");
6058
6059 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6060 kat_ciphertext);
6061}
6062
6063/*
6064 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6065 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6066 */
6067TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6068 if (SecLevel() == SecurityLevel::STRONGBOX) {
6069 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6070 }
6071 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6072 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6073 string kat_plaintext =
6074 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6075 "167f2497c994bd496eb80bfb2ba2c9d5af");
6076 string kat_ciphertext =
6077 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6078 "72c134552f3a138e726fbe493b3a839598");
6079 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6080 kat_ciphertext);
6081}
6082
6083/*
6084 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6085 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6086 */
6087TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6088 if (SecLevel() == SecurityLevel::STRONGBOX) {
6089 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6090 }
6091 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6092 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6093 string kat_plaintext =
6094 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6095 "b170");
6096 string kat_ciphertext =
6097 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6098 "4e3884138ff403a41fd99818708ada301c");
6099 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6100 kat_plaintext, kat_ciphertext);
6101}
6102
6103/*
6104 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6105 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6106 */
6107TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6108 if (SecLevel() == SecurityLevel::STRONGBOX) {
6109 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6110 }
6111 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6112 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6113 string kat_plaintext =
6114 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6115 "28091e09cdbbd3b42b");
6116 string kat_ciphertext =
6117 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6118 "2ae0f90f0c19f42b4a");
6119 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6120 kat_ciphertext);
6121}
6122
6123/*
6124 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6125 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6126 */
6127TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6128 if (SecLevel() == SecurityLevel::STRONGBOX) {
6129 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6130 }
6131 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6132 string kat_plaintext =
6133 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6134 "44ab");
6135 string kat_ciphertext =
6136 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6137 "2453");
6138 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6139 kat_ciphertext);
6140}
6141
6142/*
6143 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6144 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6145 */
6146TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6147 if (SecLevel() == SecurityLevel::STRONGBOX) {
6148 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6149 }
6150 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6151 string kat_plaintext =
6152 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6153 "e2c7");
6154 string kat_ciphertext =
6155 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6156 "bb7e3a889dd4a9589098b44acf1056e7aa");
6157 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6158 kat_ciphertext);
6159}
6160
6161/*
6162 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6163 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6164 */
6165TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6166 if (SecLevel() == SecurityLevel::STRONGBOX) {
6167 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6168 }
6169 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6170 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6171 string kat_plaintext =
6172 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6173 "ff52");
6174 string kat_ciphertext =
6175 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6176 "1413ad70fb0e1970669095ad77ebb5974ae8");
6177
6178 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6179 kat_ciphertext);
6180}
6181
6182/*
6183 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6184 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6185 */
6186TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6187 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6188 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6189 string kat_plaintext =
6190 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6191 "494cb53caca353e4b637ba05687be20f8d");
6192 string kat_ciphertext =
6193 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6194 "6047da1e4fd7c4e1cf2656097f75ae8685");
6195 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6196 kat_ciphertext);
6197}
6198
6199/*
6200 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6201 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6202 */
6203TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6204 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6205 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6206 string kat_plaintext =
6207 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6208 "2545a82b73c48078b9dae62261c65909");
6209 string kat_ciphertext =
6210 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6211 "9403a71987b95124073d69f2a3cb95b0ab");
6212 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6213 kat_plaintext, kat_ciphertext);
6214}
6215
6216/*
6217 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6218 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6219 */
6220TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6221 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6222 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6223 string kat_plaintext =
6224 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6225 "1f6db3c884");
6226 string kat_ciphertext =
6227 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6228 "a7be30d4c3");
6229 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6230 kat_ciphertext);
6231}
6232
6233/*
6234 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6235 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6236 */
6237TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6238 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6239 string kat_plaintext =
6240 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6241 "31a476d6806b8116089c6ec50bb543200f");
6242 string kat_ciphertext =
6243 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6244 "c83e377faf246288931136bef2a07c0be4");
6245 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6246 kat_ciphertext);
6247}
6248
6249/*
6250 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6251 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6252 */
6253TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6254 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6255 string kat_plaintext =
6256 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6257 "6f");
6258 string kat_ciphertext =
6259 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6260 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6261 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6262 kat_ciphertext);
6263}
6264
6265/*
6266 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6267 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6268 */
6269TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6270 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6271 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6272 string kat_plaintext =
6273 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6274 "f0");
6275 string kat_ciphertext =
6276 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6277 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6278
6279 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6280 kat_ciphertext);
6281}
6282
Selene Huang31ab4042020-04-29 04:22:39 -07006283struct AesCtrSp80038aTestVector {
6284 const char* key;
6285 const char* nonce;
6286 const char* plaintext;
6287 const char* ciphertext;
6288};
6289
6290// These test vectors are taken from
6291// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6292static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6293 // AES-128
6294 {
6295 "2b7e151628aed2a6abf7158809cf4f3c",
6296 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6297 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6298 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6299 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6300 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6301 },
6302 // AES-192
6303 {
6304 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6305 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6306 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6307 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6308 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6309 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6310 },
6311 // AES-256
6312 {
6313 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6314 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6315 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6316 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6317 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6318 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6319 },
6320};
6321
6322/*
6323 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6324 *
6325 * Verifies AES CTR implementation against SP800-38A test vectors.
6326 */
6327TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6328 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6329 for (size_t i = 0; i < 3; i++) {
6330 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6331 const string key = hex2str(test.key);
6332 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6333 InvalidSizes.end())
6334 continue;
6335 const string nonce = hex2str(test.nonce);
6336 const string plaintext = hex2str(test.plaintext);
6337 const string ciphertext = hex2str(test.ciphertext);
6338 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6339 }
6340}
6341
6342/*
6343 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6344 *
6345 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6346 */
6347TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6348 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6349 .Authorization(TAG_NO_AUTH_REQUIRED)
6350 .AesEncryptionKey(128)
6351 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6352 .Padding(PaddingMode::PKCS7)));
6353 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6354 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6355}
6356
6357/*
6358 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6359 *
6360 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6361 */
6362TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6363 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6364 .Authorization(TAG_NO_AUTH_REQUIRED)
6365 .AesEncryptionKey(128)
6366 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6367 .Authorization(TAG_CALLER_NONCE)
6368 .Padding(PaddingMode::NONE)));
6369
6370 auto params = AuthorizationSetBuilder()
6371 .BlockMode(BlockMode::CTR)
6372 .Padding(PaddingMode::NONE)
6373 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6374 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6375
6376 params = AuthorizationSetBuilder()
6377 .BlockMode(BlockMode::CTR)
6378 .Padding(PaddingMode::NONE)
6379 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6380 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6381
6382 params = AuthorizationSetBuilder()
6383 .BlockMode(BlockMode::CTR)
6384 .Padding(PaddingMode::NONE)
6385 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6386 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6387}
6388
6389/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006390 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006391 *
6392 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6393 */
6394TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6396 .Authorization(TAG_NO_AUTH_REQUIRED)
6397 .AesEncryptionKey(128)
6398 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6399 .Padding(PaddingMode::NONE)));
6400 // Two-block message.
6401 string message = "12345678901234567890123456789012";
6402 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6403 AuthorizationSet out_params;
6404 string ciphertext1 = EncryptMessage(message, params, &out_params);
6405 vector<uint8_t> iv1 = CopyIv(out_params);
6406 EXPECT_EQ(message.size(), ciphertext1.size());
6407
6408 out_params.Clear();
6409
6410 string ciphertext2 = EncryptMessage(message, params, &out_params);
6411 vector<uint8_t> iv2 = CopyIv(out_params);
6412 EXPECT_EQ(message.size(), ciphertext2.size());
6413
6414 // IVs should be random, so ciphertexts should differ.
6415 EXPECT_NE(ciphertext1, ciphertext2);
6416
6417 params.push_back(TAG_NONCE, iv1);
6418 string plaintext = DecryptMessage(ciphertext1, params);
6419 EXPECT_EQ(message, plaintext);
6420}
6421
6422/*
Tommy Chiuee705692021-09-23 20:09:13 +08006423 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6424 *
6425 * Verifies that keymaster generates correct output on zero-input with
6426 * NonePadding mode
6427 */
6428TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6429 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6430 .Authorization(TAG_NO_AUTH_REQUIRED)
6431 .AesEncryptionKey(128)
6432 .BlockMode(BlockMode::CBC)
6433 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6434
6435 // Zero input message
6436 string message = "";
6437 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006438 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006439 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6440 AuthorizationSet out_params;
6441 string ciphertext1 = EncryptMessage(message, params, &out_params);
6442 vector<uint8_t> iv1 = CopyIv(out_params);
6443 if (padding == PaddingMode::NONE)
6444 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6445 else
6446 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6447
6448 out_params.Clear();
6449
6450 string ciphertext2 = EncryptMessage(message, params, &out_params);
6451 vector<uint8_t> iv2 = CopyIv(out_params);
6452 if (padding == PaddingMode::NONE)
6453 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6454 else
6455 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6456
6457 // IVs should be random
6458 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6459
6460 params.push_back(TAG_NONCE, iv1);
6461 string plaintext = DecryptMessage(ciphertext1, params);
6462 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6463 }
6464}
6465
6466/*
Selene Huang31ab4042020-04-29 04:22:39 -07006467 * EncryptionOperationsTest.AesCallerNonce
6468 *
6469 * Verifies that AES caller-provided nonces work correctly.
6470 */
6471TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6472 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6473 .Authorization(TAG_NO_AUTH_REQUIRED)
6474 .AesEncryptionKey(128)
6475 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6476 .Authorization(TAG_CALLER_NONCE)
6477 .Padding(PaddingMode::NONE)));
6478
6479 string message = "12345678901234567890123456789012";
6480
6481 // Don't specify nonce, should get a random one.
6482 AuthorizationSetBuilder params =
6483 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6484 AuthorizationSet out_params;
6485 string ciphertext = EncryptMessage(message, params, &out_params);
6486 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006487 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006488
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006489 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006490 string plaintext = DecryptMessage(ciphertext, params);
6491 EXPECT_EQ(message, plaintext);
6492
6493 // Now specify a nonce, should also work.
6494 params = AuthorizationSetBuilder()
6495 .BlockMode(BlockMode::CBC)
6496 .Padding(PaddingMode::NONE)
6497 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6498 out_params.Clear();
6499 ciphertext = EncryptMessage(message, params, &out_params);
6500
6501 // Decrypt with correct nonce.
6502 plaintext = DecryptMessage(ciphertext, params);
6503 EXPECT_EQ(message, plaintext);
6504
6505 // Try with wrong nonce.
6506 params = AuthorizationSetBuilder()
6507 .BlockMode(BlockMode::CBC)
6508 .Padding(PaddingMode::NONE)
6509 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6510 plaintext = DecryptMessage(ciphertext, params);
6511 EXPECT_NE(message, plaintext);
6512}
6513
6514/*
6515 * EncryptionOperationsTest.AesCallerNonceProhibited
6516 *
6517 * Verifies that caller-provided nonces are not permitted when not specified in the key
6518 * authorizations.
6519 */
6520TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6521 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6522 .Authorization(TAG_NO_AUTH_REQUIRED)
6523 .AesEncryptionKey(128)
6524 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6525 .Padding(PaddingMode::NONE)));
6526
6527 string message = "12345678901234567890123456789012";
6528
6529 // Don't specify nonce, should get a random one.
6530 AuthorizationSetBuilder params =
6531 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6532 AuthorizationSet out_params;
6533 string ciphertext = EncryptMessage(message, params, &out_params);
6534 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006535 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006536
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006537 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006538 string plaintext = DecryptMessage(ciphertext, params);
6539 EXPECT_EQ(message, plaintext);
6540
6541 // Now specify a nonce, should fail
6542 params = AuthorizationSetBuilder()
6543 .BlockMode(BlockMode::CBC)
6544 .Padding(PaddingMode::NONE)
6545 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6546 out_params.Clear();
6547 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6548}
6549
6550/*
6551 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6552 *
6553 * Verifies that AES GCM mode works.
6554 */
6555TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6556 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6557 .Authorization(TAG_NO_AUTH_REQUIRED)
6558 .AesEncryptionKey(128)
6559 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6560 .Padding(PaddingMode::NONE)
6561 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6562
6563 string aad = "foobar";
6564 string message = "123456789012345678901234567890123456";
6565
6566 auto begin_params = AuthorizationSetBuilder()
6567 .BlockMode(BlockMode::GCM)
6568 .Padding(PaddingMode::NONE)
6569 .Authorization(TAG_MAC_LENGTH, 128);
6570
Selene Huang31ab4042020-04-29 04:22:39 -07006571 // Encrypt
6572 AuthorizationSet begin_out_params;
6573 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6574 << "Begin encrypt";
6575 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006576 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6577 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006578 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6579
6580 // Grab nonce
6581 begin_params.push_back(begin_out_params);
6582
6583 // Decrypt.
6584 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006585 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006586 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006587 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006588 EXPECT_EQ(message.length(), plaintext.length());
6589 EXPECT_EQ(message, plaintext);
6590}
6591
6592/*
6593 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6594 *
6595 * Verifies that AES GCM mode works, even when there's a long delay
6596 * between operations.
6597 */
6598TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6599 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6600 .Authorization(TAG_NO_AUTH_REQUIRED)
6601 .AesEncryptionKey(128)
6602 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6603 .Padding(PaddingMode::NONE)
6604 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6605
6606 string aad = "foobar";
6607 string message = "123456789012345678901234567890123456";
6608
6609 auto begin_params = AuthorizationSetBuilder()
6610 .BlockMode(BlockMode::GCM)
6611 .Padding(PaddingMode::NONE)
6612 .Authorization(TAG_MAC_LENGTH, 128);
6613
Selene Huang31ab4042020-04-29 04:22:39 -07006614 // Encrypt
6615 AuthorizationSet begin_out_params;
6616 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6617 << "Begin encrypt";
6618 string ciphertext;
6619 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006620 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006621 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006622 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006623
6624 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6625
6626 // Grab nonce
6627 begin_params.push_back(begin_out_params);
6628
6629 // Decrypt.
6630 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6631 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006632 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006633 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006634 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006635 sleep(5);
6636 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6637 EXPECT_EQ(message.length(), plaintext.length());
6638 EXPECT_EQ(message, plaintext);
6639}
6640
6641/*
6642 * EncryptionOperationsTest.AesGcmDifferentNonces
6643 *
6644 * Verifies that encrypting the same data with different nonces produces different outputs.
6645 */
6646TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6647 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6648 .Authorization(TAG_NO_AUTH_REQUIRED)
6649 .AesEncryptionKey(128)
6650 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6651 .Padding(PaddingMode::NONE)
6652 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6653 .Authorization(TAG_CALLER_NONCE)));
6654
6655 string aad = "foobar";
6656 string message = "123456789012345678901234567890123456";
6657 string nonce1 = "000000000000";
6658 string nonce2 = "111111111111";
6659 string nonce3 = "222222222222";
6660
6661 string ciphertext1 =
6662 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6663 string ciphertext2 =
6664 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6665 string ciphertext3 =
6666 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6667
6668 ASSERT_NE(ciphertext1, ciphertext2);
6669 ASSERT_NE(ciphertext1, ciphertext3);
6670 ASSERT_NE(ciphertext2, ciphertext3);
6671}
6672
6673/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006674 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6675 *
6676 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6677 */
6678TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6680 .Authorization(TAG_NO_AUTH_REQUIRED)
6681 .AesEncryptionKey(128)
6682 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6683 .Padding(PaddingMode::NONE)
6684 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6685
6686 string aad = "foobar";
6687 string message = "123456789012345678901234567890123456";
6688
6689 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6690 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6691 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6692
6693 ASSERT_NE(ciphertext1, ciphertext2);
6694 ASSERT_NE(ciphertext1, ciphertext3);
6695 ASSERT_NE(ciphertext2, ciphertext3);
6696}
6697
6698/*
Selene Huang31ab4042020-04-29 04:22:39 -07006699 * EncryptionOperationsTest.AesGcmTooShortTag
6700 *
6701 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6702 */
6703TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6705 .Authorization(TAG_NO_AUTH_REQUIRED)
6706 .AesEncryptionKey(128)
6707 .BlockMode(BlockMode::GCM)
6708 .Padding(PaddingMode::NONE)
6709 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6710 string message = "123456789012345678901234567890123456";
6711 auto params = AuthorizationSetBuilder()
6712 .BlockMode(BlockMode::GCM)
6713 .Padding(PaddingMode::NONE)
6714 .Authorization(TAG_MAC_LENGTH, 96);
6715
6716 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6717}
6718
6719/*
6720 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6721 *
6722 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6723 */
6724TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6726 .Authorization(TAG_NO_AUTH_REQUIRED)
6727 .AesEncryptionKey(128)
6728 .BlockMode(BlockMode::GCM)
6729 .Padding(PaddingMode::NONE)
6730 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6731 string aad = "foobar";
6732 string message = "123456789012345678901234567890123456";
6733 auto params = AuthorizationSetBuilder()
6734 .BlockMode(BlockMode::GCM)
6735 .Padding(PaddingMode::NONE)
6736 .Authorization(TAG_MAC_LENGTH, 128);
6737
Selene Huang31ab4042020-04-29 04:22:39 -07006738 // Encrypt
6739 AuthorizationSet begin_out_params;
6740 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6741 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006742 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006743
6744 AuthorizationSet finish_out_params;
6745 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006746 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6747 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006748
6749 params = AuthorizationSetBuilder()
6750 .Authorizations(begin_out_params)
6751 .BlockMode(BlockMode::GCM)
6752 .Padding(PaddingMode::NONE)
6753 .Authorization(TAG_MAC_LENGTH, 96);
6754
6755 // Decrypt.
6756 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6757}
6758
6759/*
6760 * EncryptionOperationsTest.AesGcmCorruptKey
6761 *
6762 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6763 */
6764TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6765 const uint8_t nonce_bytes[] = {
6766 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6767 };
6768 string nonce = make_string(nonce_bytes);
6769 const uint8_t ciphertext_bytes[] = {
6770 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6771 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6772 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6773 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6774 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6775 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6776 };
6777 string ciphertext = make_string(ciphertext_bytes);
6778
6779 auto params = AuthorizationSetBuilder()
6780 .BlockMode(BlockMode::GCM)
6781 .Padding(PaddingMode::NONE)
6782 .Authorization(TAG_MAC_LENGTH, 128)
6783 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6784
6785 auto import_params = AuthorizationSetBuilder()
6786 .Authorization(TAG_NO_AUTH_REQUIRED)
6787 .AesEncryptionKey(128)
6788 .BlockMode(BlockMode::GCM)
6789 .Padding(PaddingMode::NONE)
6790 .Authorization(TAG_CALLER_NONCE)
6791 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6792
6793 // Import correct key and decrypt
6794 const uint8_t key_bytes[] = {
6795 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6796 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6797 };
6798 string key = make_string(key_bytes);
6799 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6800 string plaintext = DecryptMessage(ciphertext, params);
6801 CheckedDeleteKey();
6802
6803 // Corrupt key and attempt to decrypt
6804 key[0] = 0;
6805 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6806 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6807 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6808 CheckedDeleteKey();
6809}
6810
6811/*
6812 * EncryptionOperationsTest.AesGcmAadNoData
6813 *
6814 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6815 * encrypt.
6816 */
6817TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6819 .Authorization(TAG_NO_AUTH_REQUIRED)
6820 .AesEncryptionKey(128)
6821 .BlockMode(BlockMode::GCM)
6822 .Padding(PaddingMode::NONE)
6823 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6824
6825 string aad = "1234567890123456";
6826 auto params = AuthorizationSetBuilder()
6827 .BlockMode(BlockMode::GCM)
6828 .Padding(PaddingMode::NONE)
6829 .Authorization(TAG_MAC_LENGTH, 128);
6830
Selene Huang31ab4042020-04-29 04:22:39 -07006831 // Encrypt
6832 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006833 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006834 string ciphertext;
6835 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006836 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6837 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006838 EXPECT_TRUE(finish_out_params.empty());
6839
6840 // Grab nonce
6841 params.push_back(begin_out_params);
6842
6843 // Decrypt.
6844 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006845 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006846 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006847 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006848
6849 EXPECT_TRUE(finish_out_params.empty());
6850
6851 EXPECT_EQ("", plaintext);
6852}
6853
6854/*
6855 * EncryptionOperationsTest.AesGcmMultiPartAad
6856 *
6857 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6858 * chunks.
6859 */
6860TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6861 const size_t tag_bits = 128;
6862 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6863 .Authorization(TAG_NO_AUTH_REQUIRED)
6864 .AesEncryptionKey(128)
6865 .BlockMode(BlockMode::GCM)
6866 .Padding(PaddingMode::NONE)
6867 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6868
6869 string message = "123456789012345678901234567890123456";
6870 auto begin_params = AuthorizationSetBuilder()
6871 .BlockMode(BlockMode::GCM)
6872 .Padding(PaddingMode::NONE)
6873 .Authorization(TAG_MAC_LENGTH, tag_bits);
6874 AuthorizationSet begin_out_params;
6875
David Drysdale7fc26b92022-05-13 09:54:24 +01006876 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006877
6878 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006879 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6880 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006881 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006882 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6883 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006884
Selene Huang31ab4042020-04-29 04:22:39 -07006885 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006886 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006887
6888 // Grab nonce.
6889 begin_params.push_back(begin_out_params);
6890
6891 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006892 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006893 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006894 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006895 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006896 EXPECT_EQ(message, plaintext);
6897}
6898
6899/*
6900 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6901 *
6902 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6903 */
6904TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6905 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6906 .Authorization(TAG_NO_AUTH_REQUIRED)
6907 .AesEncryptionKey(128)
6908 .BlockMode(BlockMode::GCM)
6909 .Padding(PaddingMode::NONE)
6910 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6911
6912 string message = "123456789012345678901234567890123456";
6913 auto begin_params = AuthorizationSetBuilder()
6914 .BlockMode(BlockMode::GCM)
6915 .Padding(PaddingMode::NONE)
6916 .Authorization(TAG_MAC_LENGTH, 128);
6917 AuthorizationSet begin_out_params;
6918
David Drysdale7fc26b92022-05-13 09:54:24 +01006919 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006920
Shawn Willden92d79c02021-02-19 07:31:55 -07006921 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006922 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006923 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6924 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006925
David Drysdaled2cc8c22021-04-15 13:29:45 +01006926 // The failure should have already cancelled the operation.
6927 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6928
Shawn Willden92d79c02021-02-19 07:31:55 -07006929 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006930}
6931
6932/*
6933 * EncryptionOperationsTest.AesGcmBadAad
6934 *
6935 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6936 */
6937TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6938 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6939 .Authorization(TAG_NO_AUTH_REQUIRED)
6940 .AesEncryptionKey(128)
6941 .BlockMode(BlockMode::GCM)
6942 .Padding(PaddingMode::NONE)
6943 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6944
6945 string message = "12345678901234567890123456789012";
6946 auto begin_params = AuthorizationSetBuilder()
6947 .BlockMode(BlockMode::GCM)
6948 .Padding(PaddingMode::NONE)
6949 .Authorization(TAG_MAC_LENGTH, 128);
6950
Selene Huang31ab4042020-04-29 04:22:39 -07006951 // Encrypt
6952 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006953 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006954 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006955 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006956 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006957
6958 // Grab nonce
6959 begin_params.push_back(begin_out_params);
6960
Selene Huang31ab4042020-04-29 04:22:39 -07006961 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006962 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006963 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006964 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006965 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006966}
6967
6968/*
6969 * EncryptionOperationsTest.AesGcmWrongNonce
6970 *
6971 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6972 */
6973TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6974 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6975 .Authorization(TAG_NO_AUTH_REQUIRED)
6976 .AesEncryptionKey(128)
6977 .BlockMode(BlockMode::GCM)
6978 .Padding(PaddingMode::NONE)
6979 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6980
6981 string message = "12345678901234567890123456789012";
6982 auto begin_params = AuthorizationSetBuilder()
6983 .BlockMode(BlockMode::GCM)
6984 .Padding(PaddingMode::NONE)
6985 .Authorization(TAG_MAC_LENGTH, 128);
6986
Selene Huang31ab4042020-04-29 04:22:39 -07006987 // Encrypt
6988 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006989 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006990 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006991 string ciphertext;
6992 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006993 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006994
6995 // Wrong nonce
6996 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6997
6998 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006999 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007000 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007001 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007002 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007003
7004 // With wrong nonce, should have gotten garbage plaintext (or none).
7005 EXPECT_NE(message, plaintext);
7006}
7007
7008/*
7009 * EncryptionOperationsTest.AesGcmCorruptTag
7010 *
7011 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7012 */
7013TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7015 .Authorization(TAG_NO_AUTH_REQUIRED)
7016 .AesEncryptionKey(128)
7017 .BlockMode(BlockMode::GCM)
7018 .Padding(PaddingMode::NONE)
7019 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7020
7021 string aad = "1234567890123456";
7022 string message = "123456789012345678901234567890123456";
7023
7024 auto params = AuthorizationSetBuilder()
7025 .BlockMode(BlockMode::GCM)
7026 .Padding(PaddingMode::NONE)
7027 .Authorization(TAG_MAC_LENGTH, 128);
7028
Selene Huang31ab4042020-04-29 04:22:39 -07007029 // Encrypt
7030 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007031 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007032 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007033 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007034 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007035
7036 // Corrupt tag
7037 ++(*ciphertext.rbegin());
7038
7039 // Grab nonce
7040 params.push_back(begin_out_params);
7041
7042 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007043 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007044 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007045 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007046 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007047}
7048
7049/*
7050 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7051 *
7052 * Verifies that 3DES is basically functional.
7053 */
7054TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7055 auto auths = AuthorizationSetBuilder()
7056 .TripleDesEncryptionKey(168)
7057 .BlockMode(BlockMode::ECB)
7058 .Authorization(TAG_NO_AUTH_REQUIRED)
7059 .Padding(PaddingMode::NONE);
7060
7061 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7062 // Two-block message.
7063 string message = "1234567890123456";
7064 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7065 string ciphertext1 = EncryptMessage(message, inParams);
7066 EXPECT_EQ(message.size(), ciphertext1.size());
7067
7068 string ciphertext2 = EncryptMessage(string(message), inParams);
7069 EXPECT_EQ(message.size(), ciphertext2.size());
7070
7071 // ECB is deterministic.
7072 EXPECT_EQ(ciphertext1, ciphertext2);
7073
7074 string plaintext = DecryptMessage(ciphertext1, inParams);
7075 EXPECT_EQ(message, plaintext);
7076}
7077
7078/*
7079 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7080 *
7081 * Verifies that CBC keys reject ECB usage.
7082 */
7083TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7085 .TripleDesEncryptionKey(168)
7086 .BlockMode(BlockMode::CBC)
7087 .Authorization(TAG_NO_AUTH_REQUIRED)
7088 .Padding(PaddingMode::NONE)));
7089
7090 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7091 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7092}
7093
7094/*
7095 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7096 *
7097 * Tests ECB mode with PKCS#7 padding, various message sizes.
7098 */
7099TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7101 .TripleDesEncryptionKey(168)
7102 .BlockMode(BlockMode::ECB)
7103 .Authorization(TAG_NO_AUTH_REQUIRED)
7104 .Padding(PaddingMode::PKCS7)));
7105
7106 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007107 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007108 string message(i, 'a');
7109 auto inParams =
7110 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7111 string ciphertext = EncryptMessage(message, inParams);
7112 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7113 string plaintext = DecryptMessage(ciphertext, inParams);
7114 EXPECT_EQ(message, plaintext);
7115 }
7116}
7117
7118/*
7119 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7120 *
7121 * Verifies that keys configured for no padding reject PKCS7 padding
7122 */
7123TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7124 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7125 .TripleDesEncryptionKey(168)
7126 .BlockMode(BlockMode::ECB)
7127 .Authorization(TAG_NO_AUTH_REQUIRED)
7128 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007129 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7130 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007131}
7132
7133/*
7134 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7135 *
7136 * Verifies that corrupted padding is detected.
7137 */
7138TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7139 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7140 .TripleDesEncryptionKey(168)
7141 .BlockMode(BlockMode::ECB)
7142 .Authorization(TAG_NO_AUTH_REQUIRED)
7143 .Padding(PaddingMode::PKCS7)));
7144
7145 string message = "a";
7146 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7147 EXPECT_EQ(8U, ciphertext.size());
7148 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007149
7150 AuthorizationSetBuilder begin_params;
7151 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7152 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007153
7154 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7155 ++ciphertext[ciphertext.size() / 2];
7156
David Drysdale7fc26b92022-05-13 09:54:24 +01007157 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007158 string plaintext;
7159 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7160 ErrorCode error = Finish(&plaintext);
7161 if (error == ErrorCode::INVALID_ARGUMENT) {
7162 // This is the expected error, we can exit the test now.
7163 return;
7164 } else {
7165 // Very small chance we got valid decryption, so try again.
7166 ASSERT_EQ(error, ErrorCode::OK);
7167 }
7168 }
7169 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007170}
7171
7172struct TripleDesTestVector {
7173 const char* name;
7174 const KeyPurpose purpose;
7175 const BlockMode block_mode;
7176 const PaddingMode padding_mode;
7177 const char* key;
7178 const char* iv;
7179 const char* input;
7180 const char* output;
7181};
7182
7183// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7184// of the NIST vectors are multiples of the block size.
7185static const TripleDesTestVector kTripleDesTestVectors[] = {
7186 {
7187 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7188 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7189 "", // IV
7190 "329d86bdf1bc5af4", // input
7191 "d946c2756d78633f", // output
7192 },
7193 {
7194 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7195 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7196 "", // IV
7197 "6b1540781b01ce1997adae102dbf3c5b", // input
7198 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7199 },
7200 {
7201 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7202 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7203 "", // IV
7204 "6daad94ce08acfe7", // input
7205 "660e7d32dcc90e79", // output
7206 },
7207 {
7208 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7209 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7210 "", // IV
7211 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7212 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7213 },
7214 {
7215 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7216 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7217 "43f791134c5647ba", // IV
7218 "dcc153cef81d6f24", // input
7219 "92538bd8af18d3ba", // output
7220 },
7221 {
7222 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7223 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7224 "c2e999cb6249023c", // IV
7225 "c689aee38a301bb316da75db36f110b5", // input
7226 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7227 },
7228 {
7229 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7230 PaddingMode::PKCS7,
7231 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7232 "c2e999cb6249023c", // IV
7233 "c689aee38a301bb316da75db36f110b500", // input
7234 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7235 },
7236 {
7237 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7238 PaddingMode::PKCS7,
7239 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7240 "c2e999cb6249023c", // IV
7241 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7242 "c689aee38a301bb316da75db36f110b500", // output
7243 },
7244 {
7245 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7246 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7247 "41746c7e442d3681", // IV
7248 "c53a7b0ec40600fe", // input
7249 "d4f00eb455de1034", // output
7250 },
7251 {
7252 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7253 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7254 "3982bc02c3727d45", // IV
7255 "6006f10adef52991fcc777a1238bbb65", // input
7256 "edae09288e9e3bc05746d872b48e3b29", // output
7257 },
7258};
7259
7260/*
7261 * EncryptionOperationsTest.TripleDesTestVector
7262 *
7263 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7264 */
7265TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7266 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7267 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7268 SCOPED_TRACE(test->name);
7269 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7270 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7271 hex2str(test->output));
7272 }
7273}
7274
7275/*
7276 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7277 *
7278 * Validates CBC mode functionality.
7279 */
7280TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7281 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7282 .TripleDesEncryptionKey(168)
7283 .BlockMode(BlockMode::CBC)
7284 .Authorization(TAG_NO_AUTH_REQUIRED)
7285 .Padding(PaddingMode::NONE)));
7286
7287 ASSERT_GT(key_blob_.size(), 0U);
7288
Brian J Murray734c8412022-01-13 14:55:30 -08007289 // Four-block message.
7290 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007291 vector<uint8_t> iv1;
7292 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7293 EXPECT_EQ(message.size(), ciphertext1.size());
7294
7295 vector<uint8_t> iv2;
7296 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7297 EXPECT_EQ(message.size(), ciphertext2.size());
7298
7299 // IVs should be random, so ciphertexts should differ.
7300 EXPECT_NE(iv1, iv2);
7301 EXPECT_NE(ciphertext1, ciphertext2);
7302
7303 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7304 EXPECT_EQ(message, plaintext);
7305}
7306
7307/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007308 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7309 *
7310 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7311 */
7312TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7314 .TripleDesEncryptionKey(168)
7315 .BlockMode(BlockMode::CBC)
7316 .Authorization(TAG_NO_AUTH_REQUIRED)
7317 .Authorization(TAG_CALLER_NONCE)
7318 .Padding(PaddingMode::NONE)));
7319 auto params = AuthorizationSetBuilder()
7320 .BlockMode(BlockMode::CBC)
7321 .Padding(PaddingMode::NONE)
7322 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7323 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7324}
7325
7326/*
Selene Huang31ab4042020-04-29 04:22:39 -07007327 * EncryptionOperationsTest.TripleDesCallerIv
7328 *
7329 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7330 */
7331TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7333 .TripleDesEncryptionKey(168)
7334 .BlockMode(BlockMode::CBC)
7335 .Authorization(TAG_NO_AUTH_REQUIRED)
7336 .Authorization(TAG_CALLER_NONCE)
7337 .Padding(PaddingMode::NONE)));
7338 string message = "1234567890123456";
7339 vector<uint8_t> iv;
7340 // Don't specify IV, should get a random one.
7341 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7342 EXPECT_EQ(message.size(), ciphertext1.size());
7343 EXPECT_EQ(8U, iv.size());
7344
7345 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7346 EXPECT_EQ(message, plaintext);
7347
7348 // Now specify an IV, should also work.
7349 iv = AidlBuf("abcdefgh");
7350 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7351
7352 // Decrypt with correct IV.
7353 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7354 EXPECT_EQ(message, plaintext);
7355
7356 // Now try with wrong IV.
7357 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7358 EXPECT_NE(message, plaintext);
7359}
7360
7361/*
7362 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7363 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007364 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007365 */
7366TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7368 .TripleDesEncryptionKey(168)
7369 .BlockMode(BlockMode::CBC)
7370 .Authorization(TAG_NO_AUTH_REQUIRED)
7371 .Padding(PaddingMode::NONE)));
7372
7373 string message = "12345678901234567890123456789012";
7374 vector<uint8_t> iv;
7375 // Don't specify nonce, should get a random one.
7376 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7377 EXPECT_EQ(message.size(), ciphertext1.size());
7378 EXPECT_EQ(8U, iv.size());
7379
7380 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7381 EXPECT_EQ(message, plaintext);
7382
7383 // Now specify a nonce, should fail.
7384 auto input_params = AuthorizationSetBuilder()
7385 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7386 .BlockMode(BlockMode::CBC)
7387 .Padding(PaddingMode::NONE);
7388 AuthorizationSet output_params;
7389 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7390 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7391}
7392
7393/*
7394 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7395 *
7396 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7397 */
7398TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7399 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7400 .TripleDesEncryptionKey(168)
7401 .BlockMode(BlockMode::ECB)
7402 .Authorization(TAG_NO_AUTH_REQUIRED)
7403 .Padding(PaddingMode::NONE)));
7404 // Two-block message.
7405 string message = "1234567890123456";
7406 auto begin_params =
7407 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7408 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7409}
7410
7411/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007412 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007413 *
7414 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7415 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007416TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7417 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007418 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007419 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7420 .TripleDesEncryptionKey(168)
7421 .BlockMode(blockMode)
7422 .Authorization(TAG_NO_AUTH_REQUIRED)
7423 .Padding(PaddingMode::NONE)));
7424 // Message is slightly shorter than two blocks.
7425 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007426
David Drysdaled2cc8c22021-04-15 13:29:45 +01007427 auto begin_params =
7428 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7429 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007430 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007431 string ciphertext;
7432 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7433
7434 CheckedDeleteKey();
7435 }
Selene Huang31ab4042020-04-29 04:22:39 -07007436}
7437
7438/*
7439 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7440 *
7441 * Verifies that PKCS7 padding works correctly in CBC mode.
7442 */
7443TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7444 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7445 .TripleDesEncryptionKey(168)
7446 .BlockMode(BlockMode::CBC)
7447 .Authorization(TAG_NO_AUTH_REQUIRED)
7448 .Padding(PaddingMode::PKCS7)));
7449
7450 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007451 for (size_t i = 0; i <= 32; i++) {
7452 SCOPED_TRACE(testing::Message() << "i = " << i);
7453 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7454 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007455 vector<uint8_t> iv;
7456 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7457 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7458 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7459 EXPECT_EQ(message, plaintext);
7460 }
7461}
7462
7463/*
7464 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7465 *
7466 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7467 */
7468TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7470 .TripleDesEncryptionKey(168)
7471 .BlockMode(BlockMode::CBC)
7472 .Authorization(TAG_NO_AUTH_REQUIRED)
7473 .Padding(PaddingMode::NONE)));
7474
7475 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007476 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007477 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007478 auto begin_params =
7479 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7480 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7481 }
7482}
7483
7484/*
7485 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7486 *
7487 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7488 */
7489TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7491 .TripleDesEncryptionKey(168)
7492 .BlockMode(BlockMode::CBC)
7493 .Authorization(TAG_NO_AUTH_REQUIRED)
7494 .Padding(PaddingMode::PKCS7)));
7495
7496 string message = "a";
7497 vector<uint8_t> iv;
7498 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7499 EXPECT_EQ(8U, ciphertext.size());
7500 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007501
7502 auto begin_params = AuthorizationSetBuilder()
7503 .BlockMode(BlockMode::CBC)
7504 .Padding(PaddingMode::PKCS7)
7505 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007506
7507 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007508 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007509 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007510 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007511 string plaintext;
7512 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7513 ErrorCode error = Finish(&plaintext);
7514 if (error == ErrorCode::INVALID_ARGUMENT) {
7515 // This is the expected error, we can exit the test now.
7516 return;
7517 } else {
7518 // Very small chance we got valid decryption, so try again.
7519 ASSERT_EQ(error, ErrorCode::OK);
7520 }
7521 }
7522 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007523}
7524
7525/*
7526 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7527 *
7528 * Verifies that 3DES CBC works with many different input sizes.
7529 */
7530TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7532 .TripleDesEncryptionKey(168)
7533 .BlockMode(BlockMode::CBC)
7534 .Authorization(TAG_NO_AUTH_REQUIRED)
7535 .Padding(PaddingMode::NONE)));
7536
7537 int increment = 7;
7538 string message(240, 'a');
7539 AuthorizationSet input_params =
7540 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7541 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007542 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007543
7544 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007545 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007546 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007547 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7548 EXPECT_EQ(message.size(), ciphertext.size());
7549
7550 // Move TAG_NONCE into input_params
7551 input_params = output_params;
7552 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7553 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7554 output_params.Clear();
7555
David Drysdale7fc26b92022-05-13 09:54:24 +01007556 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007557 string plaintext;
7558 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007559 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007560 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7561 EXPECT_EQ(ciphertext.size(), plaintext.size());
7562 EXPECT_EQ(message, plaintext);
7563}
7564
7565INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7566
7567typedef KeyMintAidlTestBase MaxOperationsTest;
7568
7569/*
7570 * MaxOperationsTest.TestLimitAes
7571 *
7572 * Verifies that the max uses per boot tag works correctly with AES keys.
7573 */
7574TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007575 if (SecLevel() == SecurityLevel::STRONGBOX) {
7576 GTEST_SKIP() << "Test not applicable to StrongBox device";
7577 }
Selene Huang31ab4042020-04-29 04:22:39 -07007578
7579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7580 .Authorization(TAG_NO_AUTH_REQUIRED)
7581 .AesEncryptionKey(128)
7582 .EcbMode()
7583 .Padding(PaddingMode::NONE)
7584 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7585
7586 string message = "1234567890123456";
7587
7588 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7589
7590 EncryptMessage(message, params);
7591 EncryptMessage(message, params);
7592 EncryptMessage(message, params);
7593
7594 // Fourth time should fail.
7595 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7596}
7597
7598/*
Qi Wud22ec842020-11-26 13:27:53 +08007599 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007600 *
7601 * Verifies that the max uses per boot tag works correctly with RSA keys.
7602 */
7603TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007604 if (SecLevel() == SecurityLevel::STRONGBOX) {
7605 GTEST_SKIP() << "Test not applicable to StrongBox device";
7606 }
Selene Huang31ab4042020-04-29 04:22:39 -07007607
7608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7609 .Authorization(TAG_NO_AUTH_REQUIRED)
7610 .RsaSigningKey(1024, 65537)
7611 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007612 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7613 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007614
7615 string message = "1234567890123456";
7616
7617 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7618
7619 SignMessage(message, params);
7620 SignMessage(message, params);
7621 SignMessage(message, params);
7622
7623 // Fourth time should fail.
7624 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7625}
7626
7627INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7628
Qi Wud22ec842020-11-26 13:27:53 +08007629typedef KeyMintAidlTestBase UsageCountLimitTest;
7630
7631/*
Qi Wubeefae42021-01-28 23:16:37 +08007632 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007633 *
Qi Wubeefae42021-01-28 23:16:37 +08007634 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007635 */
Qi Wubeefae42021-01-28 23:16:37 +08007636TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007637 if (SecLevel() == SecurityLevel::STRONGBOX) {
7638 GTEST_SKIP() << "Test not applicable to StrongBox device";
7639 }
Qi Wud22ec842020-11-26 13:27:53 +08007640
7641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7642 .Authorization(TAG_NO_AUTH_REQUIRED)
7643 .AesEncryptionKey(128)
7644 .EcbMode()
7645 .Padding(PaddingMode::NONE)
7646 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7647
7648 // Check the usage count limit tag appears in the authorizations.
7649 AuthorizationSet auths;
7650 for (auto& entry : key_characteristics_) {
7651 auths.push_back(AuthorizationSet(entry.authorizations));
7652 }
7653 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7654 << "key usage count limit " << 1U << " missing";
7655
7656 string message = "1234567890123456";
7657 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7658
Qi Wubeefae42021-01-28 23:16:37 +08007659 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7660 AuthorizationSet keystore_auths =
7661 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7662
Qi Wud22ec842020-11-26 13:27:53 +08007663 // First usage of AES key should work.
7664 EncryptMessage(message, params);
7665
Qi Wud22ec842020-11-26 13:27:53 +08007666 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7667 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7668 // must be invalidated from secure storage (such as RPMB partition).
7669 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7670 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007671 // Usage count limit tag is enforced by keystore, keymint does nothing.
7672 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007673 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007674 }
7675}
7676
7677/*
Qi Wubeefae42021-01-28 23:16:37 +08007678 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007679 *
Qi Wubeefae42021-01-28 23:16:37 +08007680 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007681 */
Qi Wubeefae42021-01-28 23:16:37 +08007682TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007683 if (SecLevel() == SecurityLevel::STRONGBOX) {
7684 GTEST_SKIP() << "Test not applicable to StrongBox device";
7685 }
Qi Wubeefae42021-01-28 23:16:37 +08007686
7687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7688 .Authorization(TAG_NO_AUTH_REQUIRED)
7689 .AesEncryptionKey(128)
7690 .EcbMode()
7691 .Padding(PaddingMode::NONE)
7692 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7693
7694 // Check the usage count limit tag appears in the authorizations.
7695 AuthorizationSet auths;
7696 for (auto& entry : key_characteristics_) {
7697 auths.push_back(AuthorizationSet(entry.authorizations));
7698 }
7699 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7700 << "key usage count limit " << 3U << " missing";
7701
7702 string message = "1234567890123456";
7703 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7704
7705 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7706 AuthorizationSet keystore_auths =
7707 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7708
7709 EncryptMessage(message, params);
7710 EncryptMessage(message, params);
7711 EncryptMessage(message, params);
7712
7713 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7714 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7715 // must be invalidated from secure storage (such as RPMB partition).
7716 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7717 } else {
7718 // Usage count limit tag is enforced by keystore, keymint does nothing.
7719 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007720 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007721 }
7722}
7723
7724/*
7725 * UsageCountLimitTest.TestSingleUseRsa
7726 *
7727 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7728 */
7729TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007730 if (SecLevel() == SecurityLevel::STRONGBOX) {
7731 GTEST_SKIP() << "Test not applicable to StrongBox device";
7732 }
Qi Wud22ec842020-11-26 13:27:53 +08007733
7734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7735 .Authorization(TAG_NO_AUTH_REQUIRED)
7736 .RsaSigningKey(1024, 65537)
7737 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007738 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7739 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007740
7741 // Check the usage count limit tag appears in the authorizations.
7742 AuthorizationSet auths;
7743 for (auto& entry : key_characteristics_) {
7744 auths.push_back(AuthorizationSet(entry.authorizations));
7745 }
7746 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7747 << "key usage count limit " << 1U << " missing";
7748
7749 string message = "1234567890123456";
7750 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7751
Qi Wubeefae42021-01-28 23:16:37 +08007752 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7753 AuthorizationSet keystore_auths =
7754 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7755
Qi Wud22ec842020-11-26 13:27:53 +08007756 // First usage of RSA key should work.
7757 SignMessage(message, params);
7758
Qi Wud22ec842020-11-26 13:27:53 +08007759 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7760 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7761 // must be invalidated from secure storage (such as RPMB partition).
7762 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7763 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007764 // Usage count limit tag is enforced by keystore, keymint does nothing.
7765 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007766 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007767 }
7768}
7769
7770/*
7771 * UsageCountLimitTest.TestLimitUseRsa
7772 *
7773 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7774 */
7775TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007776 if (SecLevel() == SecurityLevel::STRONGBOX) {
7777 GTEST_SKIP() << "Test not applicable to StrongBox device";
7778 }
Qi Wubeefae42021-01-28 23:16:37 +08007779
7780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7781 .Authorization(TAG_NO_AUTH_REQUIRED)
7782 .RsaSigningKey(1024, 65537)
7783 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007784 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7785 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007786
7787 // Check the usage count limit tag appears in the authorizations.
7788 AuthorizationSet auths;
7789 for (auto& entry : key_characteristics_) {
7790 auths.push_back(AuthorizationSet(entry.authorizations));
7791 }
7792 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7793 << "key usage count limit " << 3U << " missing";
7794
7795 string message = "1234567890123456";
7796 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7797
7798 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7799 AuthorizationSet keystore_auths =
7800 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7801
7802 SignMessage(message, params);
7803 SignMessage(message, params);
7804 SignMessage(message, params);
7805
7806 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7807 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7808 // must be invalidated from secure storage (such as RPMB partition).
7809 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7810 } else {
7811 // Usage count limit tag is enforced by keystore, keymint does nothing.
7812 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007813 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007814 }
7815}
7816
Qi Wu8e727f72021-02-11 02:49:33 +08007817/*
7818 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7819 *
7820 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7821 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7822 * in hardware.
7823 */
7824TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007825 auto error = GenerateKey(AuthorizationSetBuilder()
7826 .RsaSigningKey(2048, 65537)
7827 .Digest(Digest::NONE)
7828 .Padding(PaddingMode::NONE)
7829 .Authorization(TAG_NO_AUTH_REQUIRED)
7830 .Authorization(TAG_ROLLBACK_RESISTANCE)
7831 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007832 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7833 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007834 }
David Drysdale513bf122021-10-06 11:53:13 +01007835
7836 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7837 ASSERT_EQ(ErrorCode::OK, error);
7838 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7839 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7840 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7841
7842 // The KeyMint should also enforce single use key in hardware when it supports rollback
7843 // resistance.
7844 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7845 .Authorization(TAG_NO_AUTH_REQUIRED)
7846 .RsaSigningKey(1024, 65537)
7847 .NoDigestOrPadding()
7848 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7849 .SetDefaultValidity()));
7850
7851 // Check the usage count limit tag appears in the hardware authorizations.
7852 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7853 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7854 << "key usage count limit " << 1U << " missing";
7855
7856 string message = "1234567890123456";
7857 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7858
7859 // First usage of RSA key should work.
7860 SignMessage(message, params);
7861
7862 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7863 // must be invalidated from secure storage (such as RPMB partition).
7864 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007865}
7866
Qi Wud22ec842020-11-26 13:27:53 +08007867INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7868
David Drysdale7de9feb2021-03-05 14:56:19 +00007869typedef KeyMintAidlTestBase GetHardwareInfoTest;
7870
7871TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7872 // Retrieving hardware info should give the same result each time.
7873 KeyMintHardwareInfo info;
7874 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7875 KeyMintHardwareInfo info2;
7876 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7877 EXPECT_EQ(info, info2);
7878}
7879
7880INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7881
Selene Huang31ab4042020-04-29 04:22:39 -07007882typedef KeyMintAidlTestBase AddEntropyTest;
7883
7884/*
7885 * AddEntropyTest.AddEntropy
7886 *
7887 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7888 * is actually added.
7889 */
7890TEST_P(AddEntropyTest, AddEntropy) {
7891 string data = "foo";
7892 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7893}
7894
7895/*
7896 * AddEntropyTest.AddEmptyEntropy
7897 *
7898 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7899 */
7900TEST_P(AddEntropyTest, AddEmptyEntropy) {
7901 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7902}
7903
7904/*
7905 * AddEntropyTest.AddLargeEntropy
7906 *
7907 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7908 */
7909TEST_P(AddEntropyTest, AddLargeEntropy) {
7910 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7911}
7912
David Drysdalebb3d85e2021-04-13 11:15:51 +01007913/*
7914 * AddEntropyTest.AddTooLargeEntropy
7915 *
7916 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7917 */
7918TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7919 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7920 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7921}
7922
Selene Huang31ab4042020-04-29 04:22:39 -07007923INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7924
Selene Huang31ab4042020-04-29 04:22:39 -07007925typedef KeyMintAidlTestBase KeyDeletionTest;
7926
7927/**
7928 * KeyDeletionTest.DeleteKey
7929 *
7930 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7931 * valid key blob.
7932 */
7933TEST_P(KeyDeletionTest, DeleteKey) {
7934 auto error = GenerateKey(AuthorizationSetBuilder()
7935 .RsaSigningKey(2048, 65537)
7936 .Digest(Digest::NONE)
7937 .Padding(PaddingMode::NONE)
7938 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007939 .Authorization(TAG_ROLLBACK_RESISTANCE)
7940 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007941 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7942 GTEST_SKIP() << "Rollback resistance not supported";
7943 }
Selene Huang31ab4042020-04-29 04:22:39 -07007944
7945 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007946 ASSERT_EQ(ErrorCode::OK, error);
7947 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7948 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007949
David Drysdale513bf122021-10-06 11:53:13 +01007950 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007951
David Drysdale513bf122021-10-06 11:53:13 +01007952 string message = "12345678901234567890123456789012";
7953 AuthorizationSet begin_out_params;
7954 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7955 Begin(KeyPurpose::SIGN, key_blob_,
7956 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7957 &begin_out_params));
7958 AbortIfNeeded();
7959 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007960}
7961
7962/**
7963 * KeyDeletionTest.DeleteInvalidKey
7964 *
7965 * This test checks that the HAL excepts invalid key blobs..
7966 */
7967TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7968 // Generate key just to check if rollback protection is implemented
7969 auto error = GenerateKey(AuthorizationSetBuilder()
7970 .RsaSigningKey(2048, 65537)
7971 .Digest(Digest::NONE)
7972 .Padding(PaddingMode::NONE)
7973 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007974 .Authorization(TAG_ROLLBACK_RESISTANCE)
7975 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007976 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7977 GTEST_SKIP() << "Rollback resistance not supported";
7978 }
Selene Huang31ab4042020-04-29 04:22:39 -07007979
7980 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007981 ASSERT_EQ(ErrorCode::OK, error);
7982 AuthorizationSet enforced(SecLevelAuthorizations());
7983 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007984
David Drysdale513bf122021-10-06 11:53:13 +01007985 // Delete the key we don't care about the result at this point.
7986 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007987
David Drysdale513bf122021-10-06 11:53:13 +01007988 // Now create an invalid key blob and delete it.
7989 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007990
David Drysdale513bf122021-10-06 11:53:13 +01007991 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007992}
7993
7994/**
7995 * KeyDeletionTest.DeleteAllKeys
7996 *
7997 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7998 *
7999 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8000 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8001 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8002 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8003 * credentials stored in Keystore/Keymint.
8004 */
8005TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008006 if (!arm_deleteAllKeys) {
8007 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8008 return;
8009 }
Selene Huang31ab4042020-04-29 04:22:39 -07008010 auto error = GenerateKey(AuthorizationSetBuilder()
8011 .RsaSigningKey(2048, 65537)
8012 .Digest(Digest::NONE)
8013 .Padding(PaddingMode::NONE)
8014 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008015 .Authorization(TAG_ROLLBACK_RESISTANCE)
8016 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008017 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8018 GTEST_SKIP() << "Rollback resistance not supported";
8019 }
Selene Huang31ab4042020-04-29 04:22:39 -07008020
8021 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008022 ASSERT_EQ(ErrorCode::OK, error);
8023 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8024 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008025
David Drysdale513bf122021-10-06 11:53:13 +01008026 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008027
David Drysdale513bf122021-10-06 11:53:13 +01008028 string message = "12345678901234567890123456789012";
8029 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008030
David Drysdale513bf122021-10-06 11:53:13 +01008031 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8032 Begin(KeyPurpose::SIGN, key_blob_,
8033 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8034 &begin_out_params));
8035 AbortIfNeeded();
8036 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008037}
8038
8039INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8040
David Drysdaled2cc8c22021-04-15 13:29:45 +01008041typedef KeyMintAidlTestBase KeyUpgradeTest;
8042
8043/**
8044 * KeyUpgradeTest.UpgradeInvalidKey
8045 *
8046 * This test checks that the HAL excepts invalid key blobs..
8047 */
8048TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8049 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8050
8051 std::vector<uint8_t> new_blob;
8052 Status result = keymint_->upgradeKey(key_blob,
8053 AuthorizationSetBuilder()
8054 .Authorization(TAG_APPLICATION_ID, "clientid")
8055 .Authorization(TAG_APPLICATION_DATA, "appdata")
8056 .vector_data(),
8057 &new_blob);
8058 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8059}
8060
8061INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8062
Selene Huang31ab4042020-04-29 04:22:39 -07008063using UpgradeKeyTest = KeyMintAidlTestBase;
8064
8065/*
8066 * UpgradeKeyTest.UpgradeKey
8067 *
8068 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8069 */
8070TEST_P(UpgradeKeyTest, UpgradeKey) {
8071 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8072 .AesEncryptionKey(128)
8073 .Padding(PaddingMode::NONE)
8074 .Authorization(TAG_NO_AUTH_REQUIRED)));
8075
8076 auto result = UpgradeKey(key_blob_);
8077
8078 // Key doesn't need upgrading. Should get okay, but no new key blob.
8079 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8080}
8081
8082INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8083
8084using ClearOperationsTest = KeyMintAidlTestBase;
8085
8086/*
8087 * ClearSlotsTest.TooManyOperations
8088 *
8089 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8090 * operations are started without being finished or aborted. Also verifies
8091 * that aborting the operations clears the operations.
8092 *
8093 */
8094TEST_P(ClearOperationsTest, TooManyOperations) {
8095 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8096 .Authorization(TAG_NO_AUTH_REQUIRED)
8097 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008098 .Padding(PaddingMode::NONE)
8099 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008100
8101 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8102 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008103 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008104 AuthorizationSet out_params;
8105 ErrorCode result;
8106 size_t i;
8107
8108 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008109 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008110 if (ErrorCode::OK != result) {
8111 break;
8112 }
8113 }
8114 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8115 // Try again just in case there's a weird overflow bug
8116 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008117 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008118 for (size_t j = 0; j < i; j++) {
8119 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8120 << "Aboort failed for i = " << j << std::endl;
8121 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008122 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008123 AbortIfNeeded();
8124}
8125
8126INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8127
8128typedef KeyMintAidlTestBase TransportLimitTest;
8129
8130/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008131 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008132 *
8133 * Verifies that passing input data to finish succeeds as expected.
8134 */
8135TEST_P(TransportLimitTest, LargeFinishInput) {
8136 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8137 .Authorization(TAG_NO_AUTH_REQUIRED)
8138 .AesEncryptionKey(128)
8139 .BlockMode(BlockMode::ECB)
8140 .Padding(PaddingMode::NONE)));
8141
8142 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008143 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008144 auto cipher_params =
8145 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8146
8147 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008148 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008149
8150 string plain_message = std::string(1 << msg_size, 'x');
8151 string encrypted_message;
8152 auto rc = Finish(plain_message, &encrypted_message);
8153
8154 EXPECT_EQ(ErrorCode::OK, rc);
8155 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8156 << "Encrypt finish returned OK, but did not consume all of the given input";
8157 cipher_params.push_back(out_params);
8158
David Drysdale7fc26b92022-05-13 09:54:24 +01008159 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008160
8161 string decrypted_message;
8162 rc = Finish(encrypted_message, &decrypted_message);
8163 EXPECT_EQ(ErrorCode::OK, rc);
8164 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8165 << "Decrypt finish returned OK, did not consume all of the given input";
8166 }
8167}
8168
8169INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8170
Seth Moored79a0ec2021-12-13 20:03:33 +00008171static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008172 switch (curve) {
8173 case EcCurve::P_224:
8174 return NID_secp224r1;
8175 case EcCurve::P_256:
8176 return NID_X9_62_prime256v1;
8177 case EcCurve::P_384:
8178 return NID_secp384r1;
8179 case EcCurve::P_521:
8180 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008181 case EcCurve::CURVE_25519:
8182 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008183 }
8184}
8185
David Drysdale42fe1892021-10-14 14:43:46 +01008186class KeyAgreementTest : public KeyMintAidlTestBase {
8187 protected:
8188 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8189 std::vector<uint8_t>* localPublicKey) {
8190 // Generate EC key locally (with access to private key material)
8191 if (localCurve == EcCurve::CURVE_25519) {
8192 uint8_t privKeyData[32];
8193 uint8_t pubKeyData[32];
8194 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008195 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8196 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8197 } else {
8198 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8199 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8200 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8201 ASSERT_NE(group, nullptr);
8202 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8203 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8204 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8205 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008206 }
David Drysdalea410b772022-05-09 16:44:13 +01008207
8208 // Get encoded form of the public part of the locally generated key...
8209 unsigned char* p = nullptr;
8210 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8211 ASSERT_GT(localPublicKeySize, 0);
8212 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8213 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8214 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008215 }
8216
8217 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8218 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008219 auto builder = AuthorizationSetBuilder()
8220 .Authorization(TAG_NO_AUTH_REQUIRED)
8221 .Authorization(TAG_EC_CURVE, curve)
8222 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8223 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8224 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8225 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8226 .SetDefaultValidity();
8227 ErrorCode result = GenerateKey(builder);
8228
8229 if (SecLevel() == SecurityLevel::STRONGBOX) {
8230 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8231 result = GenerateKeyWithSelfSignedAttestKey(
8232 AuthorizationSetBuilder()
8233 .EcdsaKey(EcCurve::P_256)
8234 .AttestKey()
8235 .SetDefaultValidity(), /* attest key params */
8236 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8237 }
8238 }
David Drysdale42fe1892021-10-14 14:43:46 +01008239 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8240 ASSERT_GT(cert_chain_.size(), 0);
8241 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8242 ASSERT_NE(kmKeyCert, nullptr);
8243 // Check that keyAgreement (bit 4) is set in KeyUsage
8244 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8245 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8246 ASSERT_NE(*kmPubKey, nullptr);
8247 if (dump_Attestations) {
8248 for (size_t n = 0; n < cert_chain_.size(); n++) {
8249 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8250 }
8251 }
8252 }
8253
8254 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8255 const std::vector<uint8_t>& localPublicKey) {
8256 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8257 string ZabFromKeyMintStr;
8258 ASSERT_EQ(ErrorCode::OK,
8259 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8260 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8261 vector<uint8_t> ZabFromTest;
8262
8263 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8264 size_t kmPubKeySize = 32;
8265 uint8_t kmPubKeyData[32];
8266 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8267 ASSERT_EQ(kmPubKeySize, 32);
8268
8269 uint8_t localPrivKeyData[32];
8270 size_t localPrivKeySize = 32;
8271 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8272 &localPrivKeySize));
8273 ASSERT_EQ(localPrivKeySize, 32);
8274
8275 uint8_t sharedKey[32];
8276 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8277 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8278 } else {
8279 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8280 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8281 ASSERT_NE(ctx, nullptr);
8282 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8283 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8284 size_t ZabFromTestLen = 0;
8285 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8286 ZabFromTest.resize(ZabFromTestLen);
8287 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8288 }
8289 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8290 }
8291};
8292
David Zeuthene0c40892021-01-08 12:54:11 -05008293/*
8294 * KeyAgreementTest.Ecdh
8295 *
David Drysdale42fe1892021-10-14 14:43:46 +01008296 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008297 */
8298TEST_P(KeyAgreementTest, Ecdh) {
8299 // Because it's possible to use this API with keys on different curves, we
8300 // check all N^2 combinations where N is the number of supported
8301 // curves.
8302 //
8303 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8304 // lot more curves we can be smart about things and just pick |otherCurve| so
8305 // it's not |curve| and that way we end up with only 2*N runs
8306 //
8307 for (auto curve : ValidCurves()) {
8308 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008309 SCOPED_TRACE(testing::Message()
8310 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8311
David Zeuthene0c40892021-01-08 12:54:11 -05008312 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008313 EVP_PKEY_Ptr localPrivKey;
8314 vector<uint8_t> localPublicKey;
8315 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008316
8317 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008318 EVP_PKEY_Ptr kmPubKey;
8319 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008320
8321 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8322 if (curve != localCurve) {
8323 // If the keys are using different curves KeyMint should fail with
8324 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008325 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008326 string ZabFromKeyMintStr;
8327 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008328 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008329 &ZabFromKeyMintStr));
8330
8331 } else {
8332 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008333 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008334 }
8335
8336 CheckedDeleteKey();
8337 }
8338 }
8339}
8340
David Drysdale42fe1892021-10-14 14:43:46 +01008341/*
8342 * KeyAgreementTest.EcdhCurve25519
8343 *
8344 * Verifies that ECDH works for curve25519. This is also covered by the general
8345 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8346 * KeyMint 1.0.
8347 */
8348TEST_P(KeyAgreementTest, EcdhCurve25519) {
8349 if (!Curve25519Supported()) {
8350 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8351 }
8352
8353 // Generate EC key in KeyMint (only access to public key material)
8354 EcCurve curve = EcCurve::CURVE_25519;
8355 EVP_PKEY_Ptr kmPubKey = nullptr;
8356 GenerateKeyMintEcKey(curve, &kmPubKey);
8357
8358 // Generate EC key on same curve locally (with access to private key material).
8359 EVP_PKEY_Ptr privKey;
8360 vector<uint8_t> encodedPublicKey;
8361 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8362
8363 // Agree on a key between local and KeyMint and check it.
8364 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8365
8366 CheckedDeleteKey();
8367}
8368
8369/*
8370 * KeyAgreementTest.EcdhCurve25519Imported
8371 *
8372 * Verifies that ECDH works for an imported curve25519 key.
8373 */
8374TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8375 if (!Curve25519Supported()) {
8376 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8377 }
8378
8379 // Import x25519 key into KeyMint.
8380 EcCurve curve = EcCurve::CURVE_25519;
8381 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8382 .Authorization(TAG_NO_AUTH_REQUIRED)
8383 .EcdsaKey(EcCurve::CURVE_25519)
8384 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8385 .SetDefaultValidity(),
8386 KeyFormat::PKCS8, x25519_pkcs8_key));
8387 ASSERT_GT(cert_chain_.size(), 0);
8388 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8389 ASSERT_NE(kmKeyCert, nullptr);
8390 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8391 ASSERT_NE(kmPubKey.get(), nullptr);
8392
8393 // Expect the import to emit corresponding public key data.
8394 size_t kmPubKeySize = 32;
8395 uint8_t kmPubKeyData[32];
8396 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8397 ASSERT_EQ(kmPubKeySize, 32);
8398 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8399 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8400
8401 // Generate EC key on same curve locally (with access to private key material).
8402 EVP_PKEY_Ptr privKey;
8403 vector<uint8_t> encodedPublicKey;
8404 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8405
8406 // Agree on a key between local and KeyMint and check it.
8407 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8408
8409 CheckedDeleteKey();
8410}
8411
8412/*
8413 * KeyAgreementTest.EcdhCurve25519InvalidSize
8414 *
8415 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8416 */
8417TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8418 if (!Curve25519Supported()) {
8419 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8420 }
8421
8422 // Generate EC key in KeyMint (only access to public key material)
8423 EcCurve curve = EcCurve::CURVE_25519;
8424 EVP_PKEY_Ptr kmPubKey = nullptr;
8425 GenerateKeyMintEcKey(curve, &kmPubKey);
8426
8427 // Generate EC key on same curve locally (with access to private key material).
8428 EVP_PKEY_Ptr privKey;
8429 vector<uint8_t> encodedPublicKey;
8430 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8431
8432 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8433 string ZabFromKeyMintStr;
8434 // Send in an incomplete public key.
8435 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8436 &ZabFromKeyMintStr));
8437
8438 CheckedDeleteKey();
8439}
8440
8441/*
8442 * KeyAgreementTest.EcdhCurve25519Mismatch
8443 *
8444 * Verifies that ECDH fails between curve25519 and other curves.
8445 */
8446TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8447 if (!Curve25519Supported()) {
8448 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8449 }
8450
8451 // Generate EC key in KeyMint (only access to public key material)
8452 EcCurve curve = EcCurve::CURVE_25519;
8453 EVP_PKEY_Ptr kmPubKey = nullptr;
8454 GenerateKeyMintEcKey(curve, &kmPubKey);
8455
8456 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008457 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008458 if (localCurve == curve) {
8459 continue;
8460 }
8461 // Generate EC key on a different curve locally (with access to private key material).
8462 EVP_PKEY_Ptr privKey;
8463 vector<uint8_t> encodedPublicKey;
8464 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8465
David Drysdale7fc26b92022-05-13 09:54:24 +01008466 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008467 string ZabFromKeyMintStr;
8468 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8469 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8470 &ZabFromKeyMintStr));
8471 }
8472
8473 CheckedDeleteKey();
8474}
8475
David Zeuthene0c40892021-01-08 12:54:11 -05008476INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8477
David Drysdaled2cc8c22021-04-15 13:29:45 +01008478using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8479
8480// This is a problematic test, as it can render the device under test permanently unusable.
8481// Re-enable and run at your own risk.
8482TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8483 auto result = DestroyAttestationIds();
8484 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8485}
8486
8487INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8488
Shawn Willdend659c7c2021-02-19 14:51:51 -07008489using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008490
David Drysdaledb0dcf52021-05-18 11:43:31 +01008491/*
8492 * EarlyBootKeyTest.CreateEarlyBootKeys
8493 *
8494 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8495 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008496TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008497 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008498 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8499 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8500
David Drysdaleadfe6112021-05-27 12:00:53 +01008501 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8502 ASSERT_GT(keyData.blob.size(), 0U);
8503 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8504 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8505 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008506 CheckedDeleteKey(&aesKeyData.blob);
8507 CheckedDeleteKey(&hmacKeyData.blob);
8508 CheckedDeleteKey(&rsaKeyData.blob);
8509 CheckedDeleteKey(&ecdsaKeyData.blob);
8510}
8511
David Drysdaledb0dcf52021-05-18 11:43:31 +01008512/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008513 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8514 *
8515 * Verifies that creating an early boot key with attestation succeeds.
8516 */
8517TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8518 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8519 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8520 builder->AttestationChallenge("challenge");
8521 builder->AttestationApplicationId("app_id");
8522 });
8523
8524 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008525 // Strongbox may not support factory attestation. Key creation might fail with
8526 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8527 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8528 continue;
8529 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008530 ASSERT_GT(keyData.blob.size(), 0U);
8531 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8532 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8533 }
8534 CheckedDeleteKey(&aesKeyData.blob);
8535 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008536 if (rsaKeyData.blob.size() != 0U) {
8537 CheckedDeleteKey(&rsaKeyData.blob);
8538 }
8539 if (ecdsaKeyData.blob.size() != 0U) {
8540 CheckedDeleteKey(&ecdsaKeyData.blob);
8541 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008542}
8543
8544/*
8545 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008546 *
8547 * Verifies that using early boot keys at a later stage fails.
8548 */
8549TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8551 .Authorization(TAG_NO_AUTH_REQUIRED)
8552 .Authorization(TAG_EARLY_BOOT_ONLY)
8553 .HmacKey(128)
8554 .Digest(Digest::SHA_2_256)
8555 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8556 AuthorizationSet output_params;
8557 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8558 AuthorizationSetBuilder()
8559 .Digest(Digest::SHA_2_256)
8560 .Authorization(TAG_MAC_LENGTH, 256),
8561 &output_params));
8562}
8563
8564/*
8565 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8566 *
8567 * Verifies that importing early boot keys fails.
8568 */
8569TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8570 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8571 .Authorization(TAG_NO_AUTH_REQUIRED)
8572 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008573 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008574 .Digest(Digest::SHA_2_256)
8575 .SetDefaultValidity(),
8576 KeyFormat::PKCS8, ec_256_key));
8577}
8578
David Drysdaled2cc8c22021-04-15 13:29:45 +01008579// 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 +00008580// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8581// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8582// early boot, so you'll have to reboot between runs.
8583TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8584 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8585 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8586 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8587 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8588 EXPECT_TRUE(
8589 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8590 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8591 EXPECT_TRUE(
8592 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8593
8594 // Should be able to use keys, since early boot has not ended
8595 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8596 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8597 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8598 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8599
8600 // End early boot
8601 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8602 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8603
8604 // Should not be able to use already-created keys.
8605 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8606 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8607 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8608 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8609
8610 CheckedDeleteKey(&aesKeyData.blob);
8611 CheckedDeleteKey(&hmacKeyData.blob);
8612 CheckedDeleteKey(&rsaKeyData.blob);
8613 CheckedDeleteKey(&ecdsaKeyData.blob);
8614
8615 // Should not be able to create new keys
8616 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8617 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8618
8619 CheckedDeleteKey(&aesKeyData.blob);
8620 CheckedDeleteKey(&hmacKeyData.blob);
8621 CheckedDeleteKey(&rsaKeyData.blob);
8622 CheckedDeleteKey(&ecdsaKeyData.blob);
8623}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008624
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008625INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8626
Shawn Willdend659c7c2021-02-19 14:51:51 -07008627using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008628
8629// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8630// between runs... and on most test devices there are no enrolled credentials so it can't be
8631// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8632// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8633// a manual test process, which includes unlocking between runs, which is why it's included here.
8634// Well, that and the fact that it's the only test we can do without also making calls into the
8635// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8636// implications might be, so that may or may not be a solution.
8637TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8638 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8639 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8640
8641 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8642 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8643 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8644 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8645
8646 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008647 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008648 ASSERT_EQ(ErrorCode::OK, rc);
8649 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8650 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8651 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8652 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8653
8654 CheckedDeleteKey(&aesKeyData.blob);
8655 CheckedDeleteKey(&hmacKeyData.blob);
8656 CheckedDeleteKey(&rsaKeyData.blob);
8657 CheckedDeleteKey(&ecdsaKeyData.blob);
8658}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008659
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008660INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8661
Shawn Willden22fb9c12022-06-02 14:04:33 -06008662using VsrRequirementTest = KeyMintAidlTestBase;
8663
8664TEST_P(VsrRequirementTest, Vsr13Test) {
8665 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008666 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008667 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8668 }
8669 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8670}
8671
Eran Messerib9346f52022-12-15 14:58:34 +00008672TEST_P(VsrRequirementTest, Vsr14Test) {
8673 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008674 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008675 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8676 }
8677 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8678}
8679
Shawn Willden22fb9c12022-06-02 14:04:33 -06008680INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8681
Janis Danisevskis24c04702020-12-16 18:28:39 -08008682} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008683
8684int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008685 std::cout << "Testing ";
8686 auto halInstances =
8687 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8688 std::cout << "HAL instances:\n";
8689 for (auto& entry : halInstances) {
8690 std::cout << " " << entry << '\n';
8691 }
8692
Selene Huang31ab4042020-04-29 04:22:39 -07008693 ::testing::InitGoogleTest(&argc, argv);
8694 for (int i = 1; i < argc; ++i) {
8695 if (argv[i][0] == '-') {
8696 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008697 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8698 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008699 }
8700 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008701 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8702 dump_Attestations = true;
8703 } else {
8704 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008705 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008706 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8707 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8708 // be run in emulated environments that don't have the normal bootloader
8709 // interactions.
8710 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8711 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008712 if (std::string(argv[i]) == "--keyblob_dir") {
8713 if (i + 1 >= argc) {
8714 std::cerr << "Missing argument for --keyblob_dir\n";
8715 return 1;
8716 }
8717 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8718 std::string(argv[i + 1]);
8719 ++i;
8720 }
Selene Huang31ab4042020-04-29 04:22:39 -07008721 }
8722 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008723 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008724}