blob: 63b2e73ea728cf27c68880728ec6b6688dffb7e3 [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) {
David Drysdale513bf122021-10-06 11:53:13 +01003121 if (SecLevel() == SecurityLevel::STRONGBOX) {
3122 GTEST_SKIP() << "Test not applicable to StrongBox device";
3123 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08003124 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3125 .RsaSigningKey(1024, 65537)
3126 .Digest(Digest::NONE)
3127 .Padding(PaddingMode::NONE)
3128 .Authorization(TAG_NO_AUTH_REQUIRED)
3129 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3130 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003131
3132 const string message = "12345678901234567890123456789012";
3133 EXPECT_EQ(ErrorCode::OK,
3134 Begin(KeyPurpose::SIGN,
3135 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3136 string signature;
3137 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3138}
3139
3140/*
3141 * SigningOperationsTest.RsaPkcs1Sha256Success
3142 *
3143 * Verifies that digested RSA-PKCS1 signature operations succeed.
3144 */
3145TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3146 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3147 .RsaSigningKey(2048, 65537)
3148 .Digest(Digest::SHA_2_256)
3149 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003150 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3151 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003152 string message(1024, 'a');
3153 string signature = SignMessage(message, AuthorizationSetBuilder()
3154 .Digest(Digest::SHA_2_256)
3155 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3156}
3157
3158/*
3159 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3160 *
3161 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3162 */
3163TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3164 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3165 .RsaSigningKey(2048, 65537)
3166 .Digest(Digest::NONE)
3167 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003168 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3169 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003170 string message(53, 'a');
3171 string signature = SignMessage(message, AuthorizationSetBuilder()
3172 .Digest(Digest::NONE)
3173 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3174}
3175
3176/*
3177 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3178 *
3179 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3180 * given a too-long message.
3181 */
3182TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3183 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3184 .RsaSigningKey(2048, 65537)
3185 .Digest(Digest::NONE)
3186 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003187 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3188 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003189 string message(257, 'a');
3190
3191 EXPECT_EQ(ErrorCode::OK,
3192 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3193 .Digest(Digest::NONE)
3194 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3195 string signature;
3196 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3197}
3198
3199/*
3200 * SigningOperationsTest.RsaPssSha512TooSmallKey
3201 *
3202 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3203 * used with a key that is too small for the message.
3204 *
3205 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3206 * keymint specification requires that salt_size == digest_size, so the message will be
3207 * digest_size * 2 +
3208 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3209 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3210 * for a 1024-bit key.
3211 */
3212TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003213 if (SecLevel() == SecurityLevel::STRONGBOX) {
3214 GTEST_SKIP() << "Test not applicable to StrongBox device";
3215 }
Selene Huang31ab4042020-04-29 04:22:39 -07003216 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3217 .RsaSigningKey(1024, 65537)
3218 .Digest(Digest::SHA_2_512)
3219 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003220 .Padding(PaddingMode::RSA_PSS)
3221 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003222 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3223 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3224 .Digest(Digest::SHA_2_512)
3225 .Padding(PaddingMode::RSA_PSS)));
3226}
3227
3228/*
3229 * SigningOperationsTest.RsaNoPaddingTooLong
3230 *
3231 * Verifies that raw RSA signature operations fail with the correct error code when
3232 * given a too-long message.
3233 */
3234TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3235 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3236 .RsaSigningKey(2048, 65537)
3237 .Digest(Digest::NONE)
3238 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003239 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3240 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003241 // One byte too long
3242 string message(2048 / 8 + 1, 'a');
3243 ASSERT_EQ(ErrorCode::OK,
3244 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3245 .Digest(Digest::NONE)
3246 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3247 string result;
3248 ErrorCode finish_error_code = Finish(message, &result);
3249 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3250 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3251
3252 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3253 message = string(128 * 1024, 'a');
3254 ASSERT_EQ(ErrorCode::OK,
3255 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3256 .Digest(Digest::NONE)
3257 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3258 finish_error_code = Finish(message, &result);
3259 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3260 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3261}
3262
3263/*
3264 * SigningOperationsTest.RsaAbort
3265 *
3266 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3267 * test, but the behavior should be algorithm and purpose-independent.
3268 */
3269TEST_P(SigningOperationsTest, RsaAbort) {
3270 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3271 .RsaSigningKey(2048, 65537)
3272 .Digest(Digest::NONE)
3273 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003274 .Padding(PaddingMode::NONE)
3275 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003276
3277 ASSERT_EQ(ErrorCode::OK,
3278 Begin(KeyPurpose::SIGN,
3279 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3280 EXPECT_EQ(ErrorCode::OK, Abort());
3281
3282 // Another abort should fail
3283 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3284
3285 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003286 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003287}
3288
3289/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003290 * SigningOperationsTest.RsaNonUniqueParams
3291 *
3292 * Verifies that an operation with multiple padding modes is rejected.
3293 */
3294TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3296 .RsaSigningKey(2048, 65537)
3297 .Digest(Digest::NONE)
3298 .Digest(Digest::SHA1)
3299 .Authorization(TAG_NO_AUTH_REQUIRED)
3300 .Padding(PaddingMode::NONE)
3301 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3302 .SetDefaultValidity()));
3303
3304 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3305 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3306 .Digest(Digest::NONE)
3307 .Padding(PaddingMode::NONE)
3308 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3309
Tommy Chiuc93c4392021-05-11 18:36:50 +08003310 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3311 .Digest(Digest::NONE)
3312 .Digest(Digest::SHA1)
3313 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3314 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003315
3316 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3317 Begin(KeyPurpose::SIGN,
3318 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3319}
3320
3321/*
Selene Huang31ab4042020-04-29 04:22:39 -07003322 * SigningOperationsTest.RsaUnsupportedPadding
3323 *
3324 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3325 * with a padding mode inappropriate for RSA.
3326 */
3327TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3328 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3329 .RsaSigningKey(2048, 65537)
3330 .Authorization(TAG_NO_AUTH_REQUIRED)
3331 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003332 .Padding(PaddingMode::PKCS7)
3333 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003334 ASSERT_EQ(
3335 ErrorCode::UNSUPPORTED_PADDING_MODE,
3336 Begin(KeyPurpose::SIGN,
3337 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003338 CheckedDeleteKey();
3339
3340 ASSERT_EQ(ErrorCode::OK,
3341 GenerateKey(
3342 AuthorizationSetBuilder()
3343 .RsaSigningKey(2048, 65537)
3344 .Authorization(TAG_NO_AUTH_REQUIRED)
3345 .Digest(Digest::SHA_2_256 /* supported digest */)
3346 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3347 .SetDefaultValidity()));
3348 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3349 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3350 .Digest(Digest::SHA_2_256)
3351 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003352}
3353
3354/*
3355 * SigningOperationsTest.RsaPssNoDigest
3356 *
3357 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3358 */
3359TEST_P(SigningOperationsTest, RsaNoDigest) {
3360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3361 .RsaSigningKey(2048, 65537)
3362 .Authorization(TAG_NO_AUTH_REQUIRED)
3363 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003364 .Padding(PaddingMode::RSA_PSS)
3365 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003366 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3367 Begin(KeyPurpose::SIGN,
3368 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3369
3370 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3371 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3372}
3373
3374/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003375 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003376 *
3377 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3378 * supported in some cases (as validated in other tests), but a mode must be specified.
3379 */
3380TEST_P(SigningOperationsTest, RsaNoPadding) {
3381 // Padding must be specified
3382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3383 .RsaKey(2048, 65537)
3384 .Authorization(TAG_NO_AUTH_REQUIRED)
3385 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003386 .Digest(Digest::NONE)
3387 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003388 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3389 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3390}
3391
3392/*
3393 * SigningOperationsTest.RsaShortMessage
3394 *
3395 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3396 */
3397TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3399 .Authorization(TAG_NO_AUTH_REQUIRED)
3400 .RsaSigningKey(2048, 65537)
3401 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003402 .Padding(PaddingMode::NONE)
3403 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003404
3405 // Barely shorter
3406 string message(2048 / 8 - 1, 'a');
3407 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3408
3409 // Much shorter
3410 message = "a";
3411 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3412}
3413
3414/*
3415 * SigningOperationsTest.RsaSignWithEncryptionKey
3416 *
3417 * Verifies that RSA encryption keys cannot be used to sign.
3418 */
3419TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3421 .Authorization(TAG_NO_AUTH_REQUIRED)
3422 .RsaEncryptionKey(2048, 65537)
3423 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003424 .Padding(PaddingMode::NONE)
3425 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003426 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3427 Begin(KeyPurpose::SIGN,
3428 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3429}
3430
3431/*
3432 * SigningOperationsTest.RsaSignTooLargeMessage
3433 *
3434 * Verifies that attempting a raw signature of a message which is the same length as the key,
3435 * but numerically larger than the public modulus, fails with the correct error.
3436 */
3437TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3438 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3439 .Authorization(TAG_NO_AUTH_REQUIRED)
3440 .RsaSigningKey(2048, 65537)
3441 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003442 .Padding(PaddingMode::NONE)
3443 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003444
3445 // Largest possible message will always be larger than the public modulus.
3446 string message(2048 / 8, static_cast<char>(0xff));
3447 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3448 .Authorization(TAG_NO_AUTH_REQUIRED)
3449 .Digest(Digest::NONE)
3450 .Padding(PaddingMode::NONE)));
3451 string signature;
3452 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3453}
3454
3455/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003456 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3457 *
David Drysdale42fe1892021-10-14 14:43:46 +01003458 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003459 */
3460TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003461
3462 string message = "1234567890";
3463 string corrupt_message = "2234567890";
3464 for (auto curve : ValidCurves()) {
3465 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003466 // Ed25519 only allows Digest::NONE.
3467 auto digests = (curve == EcCurve::CURVE_25519)
3468 ? std::vector<Digest>(1, Digest::NONE)
3469 : ValidDigests(true /* withNone */, false /* withMD5 */);
3470
David Drysdaledf8f52e2021-05-06 08:10:58 +01003471 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3472 .Authorization(TAG_NO_AUTH_REQUIRED)
3473 .EcdsaSigningKey(curve)
3474 .Digest(digests)
3475 .SetDefaultValidity());
3476 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3477 if (error != ErrorCode::OK) {
3478 continue;
3479 }
3480
3481 for (auto digest : digests) {
3482 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3483 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3484 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3485 }
3486
3487 auto rc = DeleteKey();
3488 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3489 }
3490}
3491
3492/*
Selene Huang31ab4042020-04-29 04:22:39 -07003493 * SigningOperationsTest.EcdsaAllCurves
3494 *
David Drysdale42fe1892021-10-14 14:43:46 +01003495 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003496 */
3497TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3498 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003499 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3500 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003501 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3502 .Authorization(TAG_NO_AUTH_REQUIRED)
3503 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003504 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003505 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003506 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3507 if (error != ErrorCode::OK) continue;
3508
3509 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003510 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003511 CheckedDeleteKey();
3512 }
3513}
3514
3515/*
David Drysdale42fe1892021-10-14 14:43:46 +01003516 * SigningOperationsTest.EcdsaCurve25519
3517 *
3518 * Verifies that ECDSA operations succeed with curve25519.
3519 */
3520TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3521 if (!Curve25519Supported()) {
3522 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3523 }
3524
3525 EcCurve curve = EcCurve::CURVE_25519;
3526 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3527 .Authorization(TAG_NO_AUTH_REQUIRED)
3528 .EcdsaSigningKey(curve)
3529 .Digest(Digest::NONE)
3530 .SetDefaultValidity());
3531 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3532
3533 string message(1024, 'a');
3534 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3535 CheckedDeleteKey();
3536}
3537
3538/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003539 * SigningOperationsTest.EcdsaCurve25519MaxSize
3540 *
3541 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3542 */
3543TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3544 if (!Curve25519Supported()) {
3545 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3546 }
3547
3548 EcCurve curve = EcCurve::CURVE_25519;
3549 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3550 .Authorization(TAG_NO_AUTH_REQUIRED)
3551 .EcdsaSigningKey(curve)
3552 .Digest(Digest::NONE)
3553 .SetDefaultValidity());
3554 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3555
3556 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3557
3558 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3559 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3560 string message(msg_size, 'a');
3561
3562 // Attempt to sign via Begin+Finish.
3563 AuthorizationSet out_params;
3564 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3565 EXPECT_TRUE(out_params.empty());
3566 string signature;
3567 auto result = Finish(message, &signature);
3568 EXPECT_EQ(result, ErrorCode::OK);
3569 LocalVerifyMessage(message, signature, params);
3570
3571 // Attempt to sign via Begin+Update+Finish
3572 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3573 EXPECT_TRUE(out_params.empty());
3574 string output;
3575 result = Update(message, &output);
3576 EXPECT_EQ(result, ErrorCode::OK);
3577 EXPECT_EQ(output.size(), 0);
3578 string signature2;
3579 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3580 LocalVerifyMessage(message, signature2, params);
3581 }
3582
3583 CheckedDeleteKey();
3584}
3585
3586/*
3587 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3588 *
3589 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3590 */
3591TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3592 if (!Curve25519Supported()) {
3593 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3594 }
3595
3596 EcCurve curve = EcCurve::CURVE_25519;
3597 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3598 .Authorization(TAG_NO_AUTH_REQUIRED)
3599 .EcdsaSigningKey(curve)
3600 .Digest(Digest::NONE)
3601 .SetDefaultValidity());
3602 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3603
3604 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3605
3606 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3607 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3608 string message(msg_size, 'a');
3609
3610 // Attempt to sign via Begin+Finish.
3611 AuthorizationSet out_params;
3612 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3613 EXPECT_TRUE(out_params.empty());
3614 string signature;
3615 auto result = Finish(message, &signature);
3616 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3617
3618 // Attempt to sign via Begin+Update (but never get to Finish)
3619 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3620 EXPECT_TRUE(out_params.empty());
3621 string output;
3622 result = Update(message, &output);
3623 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3624 }
3625
3626 CheckedDeleteKey();
3627}
3628
3629/*
Selene Huang31ab4042020-04-29 04:22:39 -07003630 * SigningOperationsTest.EcdsaNoDigestHugeData
3631 *
3632 * Verifies that ECDSA operations support very large messages, even without digesting. This
3633 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3634 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3635 * the framework.
3636 */
3637TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003640 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003641 .Digest(Digest::NONE)
3642 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003643 string message(1 * 1024, 'a');
3644 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3645}
3646
3647/*
3648 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3649 *
3650 * Verifies that using an EC key requires the correct app ID/data.
3651 */
3652TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3654 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003655 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003656 .Digest(Digest::NONE)
3657 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003658 .Authorization(TAG_APPLICATION_DATA, "appdata")
3659 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003660
3661 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3662
Selene Huang31ab4042020-04-29 04:22:39 -07003663 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3664 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3665 AbortIfNeeded();
3666 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3667 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3668 .Digest(Digest::NONE)
3669 .Authorization(TAG_APPLICATION_ID, "clientid")));
3670 AbortIfNeeded();
3671 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3672 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3673 .Digest(Digest::NONE)
3674 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3675 AbortIfNeeded();
3676 EXPECT_EQ(ErrorCode::OK,
3677 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3678 .Digest(Digest::NONE)
3679 .Authorization(TAG_APPLICATION_DATA, "appdata")
3680 .Authorization(TAG_APPLICATION_ID, "clientid")));
3681 AbortIfNeeded();
3682}
3683
3684/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003685 * SigningOperationsTest.EcdsaIncompatibleDigest
3686 *
3687 * Verifies that using an EC key requires compatible digest.
3688 */
3689TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3691 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003692 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003693 .Digest(Digest::NONE)
3694 .Digest(Digest::SHA1)
3695 .SetDefaultValidity()));
3696 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3697 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3698 AbortIfNeeded();
3699}
3700
3701/*
Selene Huang31ab4042020-04-29 04:22:39 -07003702 * SigningOperationsTest.AesEcbSign
3703 *
3704 * Verifies that attempts to use AES keys to sign fail in the correct way.
3705 */
3706TEST_P(SigningOperationsTest, AesEcbSign) {
3707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3708 .Authorization(TAG_NO_AUTH_REQUIRED)
3709 .SigningKey()
3710 .AesEncryptionKey(128)
3711 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3712
3713 AuthorizationSet out_params;
3714 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3715 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3716 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3717 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3718}
3719
3720/*
3721 * SigningOperationsTest.HmacAllDigests
3722 *
3723 * Verifies that HMAC works with all digests.
3724 */
3725TEST_P(SigningOperationsTest, HmacAllDigests) {
3726 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003727 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3729 .Authorization(TAG_NO_AUTH_REQUIRED)
3730 .HmacKey(128)
3731 .Digest(digest)
3732 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3733 << "Failed to create HMAC key with digest " << digest;
3734 string message = "12345678901234567890123456789012";
3735 string signature = MacMessage(message, digest, 160);
3736 EXPECT_EQ(160U / 8U, signature.size())
3737 << "Failed to sign with HMAC key with digest " << digest;
3738 CheckedDeleteKey();
3739 }
3740}
3741
3742/*
3743 * SigningOperationsTest.HmacSha256TooLargeMacLength
3744 *
3745 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3746 * digest size.
3747 */
3748TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3749 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3750 .Authorization(TAG_NO_AUTH_REQUIRED)
3751 .HmacKey(128)
3752 .Digest(Digest::SHA_2_256)
3753 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3754 AuthorizationSet output_params;
3755 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3756 AuthorizationSetBuilder()
3757 .Digest(Digest::SHA_2_256)
3758 .Authorization(TAG_MAC_LENGTH, 264),
3759 &output_params));
3760}
3761
3762/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003763 * SigningOperationsTest.HmacSha256InvalidMacLength
3764 *
3765 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3766 * not a multiple of 8.
3767 */
3768TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3770 .Authorization(TAG_NO_AUTH_REQUIRED)
3771 .HmacKey(128)
3772 .Digest(Digest::SHA_2_256)
3773 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3774 AuthorizationSet output_params;
3775 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3776 AuthorizationSetBuilder()
3777 .Digest(Digest::SHA_2_256)
3778 .Authorization(TAG_MAC_LENGTH, 161),
3779 &output_params));
3780}
3781
3782/*
Selene Huang31ab4042020-04-29 04:22:39 -07003783 * SigningOperationsTest.HmacSha256TooSmallMacLength
3784 *
3785 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3786 * specified minimum MAC length.
3787 */
3788TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3790 .Authorization(TAG_NO_AUTH_REQUIRED)
3791 .HmacKey(128)
3792 .Digest(Digest::SHA_2_256)
3793 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3794 AuthorizationSet output_params;
3795 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3796 AuthorizationSetBuilder()
3797 .Digest(Digest::SHA_2_256)
3798 .Authorization(TAG_MAC_LENGTH, 120),
3799 &output_params));
3800}
3801
3802/*
3803 * SigningOperationsTest.HmacRfc4231TestCase3
3804 *
3805 * Validates against the test vectors from RFC 4231 test case 3.
3806 */
3807TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3808 string key(20, 0xaa);
3809 string message(50, 0xdd);
3810 uint8_t sha_224_expected[] = {
3811 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3812 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3813 };
3814 uint8_t sha_256_expected[] = {
3815 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3816 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3817 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3818 };
3819 uint8_t sha_384_expected[] = {
3820 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3821 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3822 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3823 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3824 };
3825 uint8_t sha_512_expected[] = {
3826 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3827 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3828 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3829 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3830 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3831 };
3832
3833 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3834 if (SecLevel() != SecurityLevel::STRONGBOX) {
3835 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3836 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3837 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3838 }
3839}
3840
3841/*
3842 * SigningOperationsTest.HmacRfc4231TestCase5
3843 *
3844 * Validates against the test vectors from RFC 4231 test case 5.
3845 */
3846TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3847 string key(20, 0x0c);
3848 string message = "Test With Truncation";
3849
3850 uint8_t sha_224_expected[] = {
3851 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3852 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3853 };
3854 uint8_t sha_256_expected[] = {
3855 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3856 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3857 };
3858 uint8_t sha_384_expected[] = {
3859 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3860 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3861 };
3862 uint8_t sha_512_expected[] = {
3863 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3864 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3865 };
3866
3867 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3868 if (SecLevel() != SecurityLevel::STRONGBOX) {
3869 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3870 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3871 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3872 }
3873}
3874
3875INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3876
3877typedef KeyMintAidlTestBase VerificationOperationsTest;
3878
3879/*
Selene Huang31ab4042020-04-29 04:22:39 -07003880 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3881 *
3882 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3883 */
3884TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3885 string key_material = "HelloThisIsAKey";
3886
3887 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003888 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003889 EXPECT_EQ(ErrorCode::OK,
3890 ImportKey(AuthorizationSetBuilder()
3891 .Authorization(TAG_NO_AUTH_REQUIRED)
3892 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3893 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3894 .Digest(Digest::SHA_2_256)
3895 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3896 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3897 EXPECT_EQ(ErrorCode::OK,
3898 ImportKey(AuthorizationSetBuilder()
3899 .Authorization(TAG_NO_AUTH_REQUIRED)
3900 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3901 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3902 .Digest(Digest::SHA_2_256)
3903 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3904 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3905
3906 string message = "This is a message.";
3907 string signature = SignMessage(
3908 signing_key, message,
3909 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3910
3911 // Signing key should not work.
3912 AuthorizationSet out_params;
3913 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3914 Begin(KeyPurpose::VERIFY, signing_key,
3915 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3916
3917 // Verification key should work.
3918 VerifyMessage(verification_key, message, signature,
3919 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3920
3921 CheckedDeleteKey(&signing_key);
3922 CheckedDeleteKey(&verification_key);
3923}
3924
Prashant Patildec9fdc2021-12-08 15:25:47 +00003925/*
3926 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3927 *
3928 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3929 */
3930TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3931 string key_material = "HelloThisIsAKey";
3932
3933 vector<uint8_t> signing_key, verification_key;
3934 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3935 EXPECT_EQ(ErrorCode::OK,
3936 ImportKey(AuthorizationSetBuilder()
3937 .Authorization(TAG_NO_AUTH_REQUIRED)
3938 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3939 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3940 .Digest(Digest::SHA_2_256)
3941 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3942 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3943 EXPECT_EQ(ErrorCode::OK,
3944 ImportKey(AuthorizationSetBuilder()
3945 .Authorization(TAG_NO_AUTH_REQUIRED)
3946 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3947 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3948 .Digest(Digest::SHA_2_256)
3949 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3950 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3951
3952 string message = "This is a message.";
3953 string signature = SignMessage(
3954 signing_key, message,
3955 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3956
3957 AuthorizationSet begin_out_params;
3958 ASSERT_EQ(ErrorCode::OK,
3959 Begin(KeyPurpose::VERIFY, verification_key,
3960 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3961
3962 string corruptMessage = "This is b message."; // Corrupted message
3963 string output;
3964 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3965
3966 ASSERT_EQ(ErrorCode::OK,
3967 Begin(KeyPurpose::VERIFY, verification_key,
3968 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3969
3970 signature[0] += 1; // Corrupt a signature
3971 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3972
3973 CheckedDeleteKey(&signing_key);
3974 CheckedDeleteKey(&verification_key);
3975}
3976
Selene Huang31ab4042020-04-29 04:22:39 -07003977INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3978
3979typedef KeyMintAidlTestBase ExportKeyTest;
3980
3981/*
3982 * ExportKeyTest.RsaUnsupportedKeyFormat
3983 *
3984 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3985 */
3986// TODO(seleneh) add ExportKey to GenerateKey
3987// check result
3988
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003989class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003990 public:
3991 template <TagType tag_type, Tag tag, typename ValueT>
3992 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3993 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003994 for (auto& entry : key_characteristics_) {
3995 if (entry.securityLevel == SecLevel()) {
3996 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3997 << "Tag " << tag << " with value " << expected
3998 << " not found at security level" << entry.securityLevel;
3999 } else {
4000 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
4001 << "Tag " << tag << " found at security level " << entry.securityLevel;
4002 }
Selene Huang31ab4042020-04-29 04:22:39 -07004003 }
4004 }
4005
4006 void CheckOrigin() {
4007 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07004008 // Origin isn't a crypto param, but it always lives with them.
4009 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07004010 }
4011};
4012
4013/*
4014 * ImportKeyTest.RsaSuccess
4015 *
4016 * Verifies that importing and using an RSA key pair works correctly.
4017 */
4018TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07004019 uint32_t key_size;
4020 string key;
4021
4022 if (SecLevel() == SecurityLevel::STRONGBOX) {
4023 key_size = 2048;
4024 key = rsa_2048_key;
4025 } else {
4026 key_size = 1024;
4027 key = rsa_key;
4028 }
4029
Selene Huang31ab4042020-04-29 04:22:39 -07004030 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4031 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004032 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004033 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004034 .Padding(PaddingMode::RSA_PSS)
4035 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004036 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004037
4038 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004039 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004040 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4041 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4042 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4043 CheckOrigin();
4044
4045 string message(1024 / 8, 'a');
4046 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4047 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004048 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004049}
4050
4051/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004052 * ImportKeyTest.RsaSuccessWithoutParams
4053 *
4054 * Verifies that importing and using an RSA key pair without specifying parameters
4055 * works correctly.
4056 */
4057TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4058 uint32_t key_size;
4059 string key;
4060
4061 if (SecLevel() == SecurityLevel::STRONGBOX) {
4062 key_size = 2048;
4063 key = rsa_2048_key;
4064 } else {
4065 key_size = 1024;
4066 key = rsa_key;
4067 }
4068
4069 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4070 .Authorization(TAG_NO_AUTH_REQUIRED)
4071 .SigningKey()
4072 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4073 .Digest(Digest::SHA_2_256)
4074 .Padding(PaddingMode::RSA_PSS)
4075 .SetDefaultValidity(),
4076 KeyFormat::PKCS8, key));
4077
4078 // Key size and public exponent are determined from the imported key material.
4079 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4080 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4081
4082 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4083 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4084 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4085 CheckOrigin();
4086
4087 string message(1024 / 8, 'a');
4088 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4089 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004090 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004091}
4092
4093/*
Selene Huang31ab4042020-04-29 04:22:39 -07004094 * ImportKeyTest.RsaKeySizeMismatch
4095 *
4096 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4097 * correct way.
4098 */
4099TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4100 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4101 ImportKey(AuthorizationSetBuilder()
4102 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4103 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004104 .Padding(PaddingMode::NONE)
4105 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004106 KeyFormat::PKCS8, rsa_key));
4107}
4108
4109/*
4110 * ImportKeyTest.RsaPublicExponentMismatch
4111 *
4112 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4113 * fails in the correct way.
4114 */
4115TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4116 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4117 ImportKey(AuthorizationSetBuilder()
4118 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4119 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004120 .Padding(PaddingMode::NONE)
4121 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004122 KeyFormat::PKCS8, rsa_key));
4123}
4124
4125/*
David Drysdalee60248c2021-10-04 12:54:13 +01004126 * ImportKeyTest.RsaAttestMultiPurposeFail
4127 *
4128 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4129 */
4130TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004131 if (AidlVersion() < 2) {
4132 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4133 // with other key purposes. However, this was not checked at the time
4134 // so we can only be strict about checking this for implementations of KeyMint
4135 // version 2 and above.
4136 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4137 }
David Drysdalee60248c2021-10-04 12:54:13 +01004138 uint32_t key_size = 2048;
4139 string key = rsa_2048_key;
4140
4141 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4142 ImportKey(AuthorizationSetBuilder()
4143 .Authorization(TAG_NO_AUTH_REQUIRED)
4144 .RsaSigningKey(key_size, 65537)
4145 .AttestKey()
4146 .Digest(Digest::SHA_2_256)
4147 .Padding(PaddingMode::RSA_PSS)
4148 .SetDefaultValidity(),
4149 KeyFormat::PKCS8, key));
4150}
4151
4152/*
Selene Huang31ab4042020-04-29 04:22:39 -07004153 * ImportKeyTest.EcdsaSuccess
4154 *
4155 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4156 */
4157TEST_P(ImportKeyTest, EcdsaSuccess) {
4158 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4159 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004160 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004161 .Digest(Digest::SHA_2_256)
4162 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004163 KeyFormat::PKCS8, ec_256_key));
4164
4165 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004166 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4167 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4168
4169 CheckOrigin();
4170
4171 string message(32, 'a');
4172 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4173 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004174 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004175}
4176
4177/*
4178 * ImportKeyTest.EcdsaP256RFC5915Success
4179 *
4180 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4181 * correctly.
4182 */
4183TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4184 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4185 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004186 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004187 .Digest(Digest::SHA_2_256)
4188 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004189 KeyFormat::PKCS8, ec_256_key_rfc5915));
4190
4191 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004192 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4193 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4194
4195 CheckOrigin();
4196
4197 string message(32, 'a');
4198 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4199 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004200 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004201}
4202
4203/*
4204 * ImportKeyTest.EcdsaP256SEC1Success
4205 *
4206 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4207 */
4208TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4209 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4210 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004211 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004212 .Digest(Digest::SHA_2_256)
4213 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004214 KeyFormat::PKCS8, ec_256_key_sec1));
4215
4216 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004217 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4218 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4219
4220 CheckOrigin();
4221
4222 string message(32, 'a');
4223 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4224 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004225 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004226}
4227
4228/*
4229 * ImportKeyTest.Ecdsa521Success
4230 *
4231 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4232 */
4233TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004234 if (SecLevel() == SecurityLevel::STRONGBOX) {
4235 GTEST_SKIP() << "Test not applicable to StrongBox device";
4236 }
Selene Huang31ab4042020-04-29 04:22:39 -07004237 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4238 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004239 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004240 .Digest(Digest::SHA_2_256)
4241 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004242 KeyFormat::PKCS8, ec_521_key));
4243
4244 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004245 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4246 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4247 CheckOrigin();
4248
4249 string message(32, 'a');
4250 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4251 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004252 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004253}
4254
4255/*
Selene Huang31ab4042020-04-29 04:22:39 -07004256 * ImportKeyTest.EcdsaCurveMismatch
4257 *
4258 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4259 * the correct way.
4260 */
4261TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4262 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4263 ImportKey(AuthorizationSetBuilder()
4264 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004265 .Digest(Digest::NONE)
4266 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004267 KeyFormat::PKCS8, ec_256_key));
4268}
4269
4270/*
David Drysdalee60248c2021-10-04 12:54:13 +01004271 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4272 *
4273 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4274 */
4275TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004276 if (AidlVersion() < 2) {
4277 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4278 // with other key purposes. However, this was not checked at the time
4279 // so we can only be strict about checking this for implementations of KeyMint
4280 // version 2 and above.
4281 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4282 }
David Drysdalee60248c2021-10-04 12:54:13 +01004283 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4284 ImportKey(AuthorizationSetBuilder()
4285 .Authorization(TAG_NO_AUTH_REQUIRED)
4286 .EcdsaSigningKey(EcCurve::P_256)
4287 .AttestKey()
4288 .Digest(Digest::SHA_2_256)
4289 .SetDefaultValidity(),
4290 KeyFormat::PKCS8, ec_256_key));
4291}
4292
4293/*
David Drysdale42fe1892021-10-14 14:43:46 +01004294 * ImportKeyTest.Ed25519RawSuccess
4295 *
4296 * Verifies that importing and using a raw Ed25519 private key works correctly.
4297 */
4298TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4299 if (!Curve25519Supported()) {
4300 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4301 }
4302
4303 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4304 .Authorization(TAG_NO_AUTH_REQUIRED)
4305 .EcdsaSigningKey(EcCurve::CURVE_25519)
4306 .Digest(Digest::NONE)
4307 .SetDefaultValidity(),
4308 KeyFormat::RAW, ed25519_key));
4309 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4310 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4311 CheckOrigin();
4312
4313 // The returned cert should hold the correct public key.
4314 ASSERT_GT(cert_chain_.size(), 0);
4315 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4316 ASSERT_NE(kmKeyCert, nullptr);
4317 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4318 ASSERT_NE(kmPubKey.get(), nullptr);
4319 size_t kmPubKeySize = 32;
4320 uint8_t kmPubKeyData[32];
4321 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4322 ASSERT_EQ(kmPubKeySize, 32);
4323 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4324
4325 string message(32, 'a');
4326 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4327 string signature = SignMessage(message, params);
4328 LocalVerifyMessage(message, signature, params);
4329}
4330
4331/*
4332 * ImportKeyTest.Ed25519Pkcs8Success
4333 *
4334 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4335 */
4336TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4337 if (!Curve25519Supported()) {
4338 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4339 }
4340
4341 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4342 .Authorization(TAG_NO_AUTH_REQUIRED)
4343 .EcdsaSigningKey(EcCurve::CURVE_25519)
4344 .Digest(Digest::NONE)
4345 .SetDefaultValidity(),
4346 KeyFormat::PKCS8, ed25519_pkcs8_key));
4347 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4348 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4349 CheckOrigin();
4350
4351 // The returned cert should hold the correct public key.
4352 ASSERT_GT(cert_chain_.size(), 0);
4353 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4354 ASSERT_NE(kmKeyCert, nullptr);
4355 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4356 ASSERT_NE(kmPubKey.get(), nullptr);
4357 size_t kmPubKeySize = 32;
4358 uint8_t kmPubKeyData[32];
4359 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4360 ASSERT_EQ(kmPubKeySize, 32);
4361 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4362
4363 string message(32, 'a');
4364 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4365 string signature = SignMessage(message, params);
4366 LocalVerifyMessage(message, signature, params);
4367}
4368
4369/*
4370 * ImportKeyTest.Ed25519CurveMismatch
4371 *
4372 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4373 * the correct way.
4374 */
4375TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4376 if (!Curve25519Supported()) {
4377 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4378 }
4379
4380 ASSERT_NE(ErrorCode::OK,
4381 ImportKey(AuthorizationSetBuilder()
4382 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4383 .Digest(Digest::NONE)
4384 .SetDefaultValidity(),
4385 KeyFormat::RAW, ed25519_key));
4386}
4387
4388/*
4389 * ImportKeyTest.Ed25519FormatMismatch
4390 *
4391 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4392 */
4393TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4394 if (!Curve25519Supported()) {
4395 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4396 }
4397
4398 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4399 .EcdsaSigningKey(EcCurve::CURVE_25519)
4400 .Digest(Digest::NONE)
4401 .SetDefaultValidity(),
4402 KeyFormat::PKCS8, ed25519_key));
4403 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4404 .EcdsaSigningKey(EcCurve::CURVE_25519)
4405 .Digest(Digest::NONE)
4406 .SetDefaultValidity(),
4407 KeyFormat::RAW, ed25519_pkcs8_key));
4408}
4409
4410/*
4411 * ImportKeyTest.Ed25519PurposeMismatch
4412 *
4413 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4414 */
4415TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4416 if (!Curve25519Supported()) {
4417 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4418 }
4419
4420 // Can't have both SIGN and ATTEST_KEY
4421 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4422 .EcdsaSigningKey(EcCurve::CURVE_25519)
4423 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4424 .Digest(Digest::NONE)
4425 .SetDefaultValidity(),
4426 KeyFormat::RAW, ed25519_key));
4427 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4428 // PKCS#8 format and so includes an OID).
4429 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4430 .EcdsaKey(EcCurve::CURVE_25519)
4431 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4432 .Digest(Digest::NONE)
4433 .SetDefaultValidity(),
4434 KeyFormat::PKCS8, ed25519_pkcs8_key));
4435}
4436
4437/*
4438 * ImportKeyTest.X25519RawSuccess
4439 *
4440 * Verifies that importing and using a raw X25519 private key works correctly.
4441 */
4442TEST_P(ImportKeyTest, X25519RawSuccess) {
4443 if (!Curve25519Supported()) {
4444 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4445 }
4446
4447 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4448 .Authorization(TAG_NO_AUTH_REQUIRED)
4449 .EcdsaKey(EcCurve::CURVE_25519)
4450 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4451 .SetDefaultValidity(),
4452 KeyFormat::RAW, x25519_key));
4453
4454 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4455 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4456 CheckOrigin();
4457}
4458
4459/*
4460 * ImportKeyTest.X25519Pkcs8Success
4461 *
4462 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4463 */
4464TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4465 if (!Curve25519Supported()) {
4466 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4467 }
4468
4469 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4470 .Authorization(TAG_NO_AUTH_REQUIRED)
4471 .EcdsaKey(EcCurve::CURVE_25519)
4472 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4473 .SetDefaultValidity(),
4474 KeyFormat::PKCS8, x25519_pkcs8_key));
4475
4476 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4477 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4478 CheckOrigin();
4479}
4480
4481/*
4482 * ImportKeyTest.X25519CurveMismatch
4483 *
4484 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4485 * the correct way.
4486 */
4487TEST_P(ImportKeyTest, X25519CurveMismatch) {
4488 if (!Curve25519Supported()) {
4489 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4490 }
4491
4492 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4493 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4494 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4495 .SetDefaultValidity(),
4496 KeyFormat::RAW, x25519_key));
4497}
4498
4499/*
4500 * ImportKeyTest.X25519FormatMismatch
4501 *
4502 * Verifies that importing an X25519 key with an invalid format fails.
4503 */
4504TEST_P(ImportKeyTest, X25519FormatMismatch) {
4505 if (!Curve25519Supported()) {
4506 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4507 }
4508
4509 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4510 .EcdsaKey(EcCurve::CURVE_25519)
4511 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4512 .SetDefaultValidity(),
4513 KeyFormat::PKCS8, x25519_key));
4514 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4515 .EcdsaKey(EcCurve::CURVE_25519)
4516 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4517 .SetDefaultValidity(),
4518 KeyFormat::RAW, x25519_pkcs8_key));
4519}
4520
4521/*
4522 * ImportKeyTest.X25519PurposeMismatch
4523 *
4524 * Verifies that importing an X25519 key pair with an invalid format fails.
4525 */
4526TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4527 if (!Curve25519Supported()) {
4528 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4529 }
4530
4531 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4532 .EcdsaKey(EcCurve::CURVE_25519)
4533 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4534 .SetDefaultValidity(),
4535 KeyFormat::PKCS8, x25519_pkcs8_key));
4536 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4537 .EcdsaSigningKey(EcCurve::CURVE_25519)
4538 .SetDefaultValidity(),
4539 KeyFormat::PKCS8, x25519_pkcs8_key));
4540}
4541
4542/*
Selene Huang31ab4042020-04-29 04:22:39 -07004543 * ImportKeyTest.AesSuccess
4544 *
4545 * Verifies that importing and using an AES key works.
4546 */
4547TEST_P(ImportKeyTest, AesSuccess) {
4548 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4549 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4550 .Authorization(TAG_NO_AUTH_REQUIRED)
4551 .AesEncryptionKey(key.size() * 8)
4552 .EcbMode()
4553 .Padding(PaddingMode::PKCS7),
4554 KeyFormat::RAW, key));
4555
4556 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4557 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4558 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4559 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4560 CheckOrigin();
4561
4562 string message = "Hello World!";
4563 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4564 string ciphertext = EncryptMessage(message, params);
4565 string plaintext = DecryptMessage(ciphertext, params);
4566 EXPECT_EQ(message, plaintext);
4567}
4568
4569/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004570 * ImportKeyTest.AesFailure
4571 *
4572 * Verifies that importing an invalid AES key fails.
4573 */
4574TEST_P(ImportKeyTest, AesFailure) {
4575 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4576 uint32_t bitlen = key.size() * 8;
4577 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004578 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004579 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004580 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004581 .Authorization(TAG_NO_AUTH_REQUIRED)
4582 .AesEncryptionKey(key_size)
4583 .EcbMode()
4584 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004585 KeyFormat::RAW, key);
4586 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004587 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4588 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004589 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004590
4591 // Explicit key size matches that of the provided key, but it's not a valid size.
4592 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4593 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4594 ImportKey(AuthorizationSetBuilder()
4595 .Authorization(TAG_NO_AUTH_REQUIRED)
4596 .AesEncryptionKey(long_key.size() * 8)
4597 .EcbMode()
4598 .Padding(PaddingMode::PKCS7),
4599 KeyFormat::RAW, long_key));
4600 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4601 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4602 ImportKey(AuthorizationSetBuilder()
4603 .Authorization(TAG_NO_AUTH_REQUIRED)
4604 .AesEncryptionKey(short_key.size() * 8)
4605 .EcbMode()
4606 .Padding(PaddingMode::PKCS7),
4607 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004608}
4609
4610/*
4611 * ImportKeyTest.TripleDesSuccess
4612 *
4613 * Verifies that importing and using a 3DES key works.
4614 */
4615TEST_P(ImportKeyTest, TripleDesSuccess) {
4616 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4617 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4618 .Authorization(TAG_NO_AUTH_REQUIRED)
4619 .TripleDesEncryptionKey(168)
4620 .EcbMode()
4621 .Padding(PaddingMode::PKCS7),
4622 KeyFormat::RAW, key));
4623
4624 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4625 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4626 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4627 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4628 CheckOrigin();
4629
4630 string message = "Hello World!";
4631 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4632 string ciphertext = EncryptMessage(message, params);
4633 string plaintext = DecryptMessage(ciphertext, params);
4634 EXPECT_EQ(message, plaintext);
4635}
4636
4637/*
4638 * ImportKeyTest.TripleDesFailure
4639 *
4640 * Verifies that importing an invalid 3DES key fails.
4641 */
4642TEST_P(ImportKeyTest, TripleDesFailure) {
4643 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004644 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004645 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004646 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004647 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004648 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004649 .Authorization(TAG_NO_AUTH_REQUIRED)
4650 .TripleDesEncryptionKey(key_size)
4651 .EcbMode()
4652 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004653 KeyFormat::RAW, key);
4654 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004655 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4656 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004657 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004658 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004659 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004660 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4661 ImportKey(AuthorizationSetBuilder()
4662 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004663 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004664 .EcbMode()
4665 .Padding(PaddingMode::PKCS7),
4666 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004667 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004668 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4669 ImportKey(AuthorizationSetBuilder()
4670 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004671 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004672 .EcbMode()
4673 .Padding(PaddingMode::PKCS7),
4674 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004675}
4676
4677/*
4678 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004679 *
4680 * Verifies that importing and using an HMAC key works.
4681 */
4682TEST_P(ImportKeyTest, HmacKeySuccess) {
4683 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4684 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4685 .Authorization(TAG_NO_AUTH_REQUIRED)
4686 .HmacKey(key.size() * 8)
4687 .Digest(Digest::SHA_2_256)
4688 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4689 KeyFormat::RAW, key));
4690
4691 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4692 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4693 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4694 CheckOrigin();
4695
4696 string message = "Hello World!";
4697 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4698 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4699}
4700
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004701/*
4702 * ImportKeyTest.GetKeyCharacteristics
4703 *
4704 * Verifies that imported keys have the correct characteristics.
4705 */
4706TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4707 vector<uint8_t> key_blob;
4708 vector<KeyCharacteristics> key_characteristics;
4709 auto base_builder = AuthorizationSetBuilder()
4710 .Padding(PaddingMode::NONE)
4711 .Authorization(TAG_NO_AUTH_REQUIRED)
4712 .SetDefaultValidity();
4713 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4714 Algorithm::TRIPLE_DES};
4715 ErrorCode result;
4716 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4717 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4718 for (auto alg : algorithms) {
4719 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4720 AuthorizationSetBuilder builder(base_builder);
4721 switch (alg) {
4722 case Algorithm::RSA:
4723 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4724
4725 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4726 &key_characteristics);
4727 break;
4728 case Algorithm::EC:
4729 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4730 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4731 &key_characteristics);
4732 break;
4733 case Algorithm::HMAC:
4734 builder.HmacKey(128)
4735 .Digest(Digest::SHA_2_256)
4736 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4737 result =
4738 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4739 break;
4740 case Algorithm::AES:
4741 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4742 result =
4743 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4744 break;
4745 case Algorithm::TRIPLE_DES:
4746 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4747 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4748 &key_characteristics);
4749 break;
4750 default:
4751 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4752 continue;
4753 }
4754 ASSERT_EQ(ErrorCode::OK, result);
4755 CheckCharacteristics(key_blob, key_characteristics);
4756 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4757 }
4758}
4759
Selene Huang31ab4042020-04-29 04:22:39 -07004760INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4761
4762auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004763 // IKeyMintDevice.aidl
4764 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4765 "020100" // INTEGER length 1 value 0x00 (version)
4766 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4767 "934bf94e2aa28a3f83c9f79297250262"
4768 "fbe3276b5a1c91159bbfa3ef8957aac8"
4769 "4b59b30b455a79c2973480823d8b3863"
4770 "c3deef4a8e243590268d80e18751a0e1"
4771 "30f67ce6a1ace9f79b95e097474febc9"
4772 "81195b1d13a69086c0863f66a7b7fdb4"
4773 "8792227b1ac5e2489febdf087ab54864"
4774 "83033a6f001ca5d1ec1e27f5c30f4cec"
4775 "2642074a39ae68aee552e196627a8e3d"
4776 "867e67a8c01b11e75f13cca0a97ab668"
4777 "b50cda07a8ecb7cd8e3dd7009c963653"
4778 "4f6f239cffe1fc8daa466f78b676c711"
4779 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4780 "99b801597d5220e307eaa5bee507fb94"
4781 "d1fa69f9e519b2de315bac92c36f2ea1"
4782 "fa1df4478c0ddedeae8c70e0233cd098"
4783 "040c" // OCTET STRING length 0x0c (initializationVector)
4784 "d796b02c370f1fa4cc0124f1"
4785 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4786 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4787 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4788 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4789 "3106" // SET length 0x06
4790 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4791 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4792 // } end SET
4793 // } end [1]
4794 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4795 "020120" // INTEGER length 1 value 0x20 (AES)
4796 // } end [2]
4797 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4798 "02020100" // INTEGER length 2 value 0x100
4799 // } end [3]
4800 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4801 "3103" // SET length 0x03 {
4802 "020101" // INTEGER length 1 value 0x01 (ECB)
4803 // } end SET
4804 // } end [4]
4805 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4806 "3103" // SET length 0x03 {
4807 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4808 // } end SET
4809 // } end [5]
4810 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4811 // (noAuthRequired)
4812 "0500" // NULL
4813 // } end [503]
4814 // } end SEQUENCE (AuthorizationList)
4815 // } end SEQUENCE (KeyDescription)
4816 "0420" // OCTET STRING length 0x20 (encryptedKey)
4817 "ccd540855f833a5e1480bfd2d36faf3a"
4818 "eee15df5beabe2691bc82dde2a7aa910"
4819 "0410" // OCTET STRING length 0x10 (tag)
4820 "64c9f689c60ff6223ab6e6999e0eb6e5"
4821 // } SEQUENCE (SecureKeyWrapper)
4822);
Selene Huang31ab4042020-04-29 04:22:39 -07004823
4824auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004825 // IKeyMintDevice.aidl
4826 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4827 "020100" // INTEGER length 1 value 0x00 (version)
4828 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4829 "aad93ed5924f283b4bb5526fbe7a1412"
4830 "f9d9749ec30db9062b29e574a8546f33"
4831 "c88732452f5b8e6a391ee76c39ed1712"
4832 "c61d8df6213dec1cffbc17a8c6d04c7b"
4833 "30893d8daa9b2015213e219468215532"
4834 "07f8f9931c4caba23ed3bee28b36947e"
4835 "47f10e0a5c3dc51c988a628daad3e5e1"
4836 "f4005e79c2d5a96c284b4b8d7e4948f3"
4837 "31e5b85dd5a236f85579f3ea1d1b8484"
4838 "87470bdb0ab4f81a12bee42c99fe0df4"
4839 "bee3759453e69ad1d68a809ce06b949f"
4840 "7694a990429b2fe81e066ff43e56a216"
4841 "02db70757922a4bcc23ab89f1e35da77"
4842 "586775f423e519c2ea394caf48a28d0c"
4843 "8020f1dcf6b3a68ec246f615ae96dae9"
4844 "a079b1f6eb959033c1af5c125fd94168"
4845 "040c" // OCTET STRING length 0x0c (initializationVector)
4846 "6d9721d08589581ab49204a3"
4847 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4848 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4849 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4850 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4851 "3106" // SET length 0x06
4852 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4853 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4854 // } end SET
4855 // } end [1]
4856 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4857 "020120" // INTEGER length 1 value 0x20 (AES)
4858 // } end [2]
4859 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4860 "02020100" // INTEGER length 2 value 0x100
4861 // } end [3]
4862 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4863 "3103" // SET length 0x03 {
4864 "020101" // INTEGER length 1 value 0x01 (ECB)
4865 // } end SET
4866 // } end [4]
4867 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4868 "3103" // SET length 0x03 {
4869 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4870 // } end SET
4871 // } end [5]
4872 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4873 // (noAuthRequired)
4874 "0500" // NULL
4875 // } end [503]
4876 // } end SEQUENCE (AuthorizationList)
4877 // } end SEQUENCE (KeyDescription)
4878 "0420" // OCTET STRING length 0x20 (encryptedKey)
4879 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4880 "c20d1f99a9a024a76f35c8e2cab9b68d"
4881 "0410" // OCTET STRING length 0x10 (tag)
4882 "2560c70109ae67c030f00b98b512a670"
4883 // } SEQUENCE (SecureKeyWrapper)
4884);
Selene Huang31ab4042020-04-29 04:22:39 -07004885
4886auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004887 // RFC 5208 s5
4888 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4889 "020100" // INTEGER length 1 value 0x00 (version)
4890 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4891 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4892 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4893 "0500" // NULL (parameters)
4894 // } SEQUENCE (AlgorithmIdentifier)
4895 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4896 // RFC 8017 A.1.2
4897 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4898 "020100" // INTEGER length 1 value 0x00 (version)
4899 "02820101" // INTEGER length 0x0101 (modulus) value...
4900 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4901 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4902 "7b06e673a837313d56b1c725150a3fef" // 0x30
4903 "86acbddc41bb759c2854eae32d35841e" // 0x40
4904 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4905 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4906 "312d7bd5921ffaea1347c157406fef71" // 0x70
4907 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4908 "f4645c11f5c1374c3886427411c44979" // 0x90
4909 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4910 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4911 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4912 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4913 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4914 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4915 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4916 "55" // 0x101
4917 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4918 "02820100" // INTEGER length 0x100 (privateExponent) value...
4919 "431447b6251908112b1ee76f99f3711a" // 0x10
4920 "52b6630960046c2de70de188d833f8b8" // 0x20
4921 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4922 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4923 "e710b630a03adc683b5d2c43080e52be" // 0x50
4924 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4925 "822bccff087d63c940ba8a45f670feb2" // 0x70
4926 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4927 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4928 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4929 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4930 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4931 "52659d5a5ba05b663737a8696281865b" // 0xd0
4932 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4933 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4934 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4935 "028181" // INTEGER length 0x81 (prime1) value...
4936 "00de392e18d682c829266cc3454e1d61" // 0x10
4937 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4938 "ff841be5bac82a164c5970007047b8c5" // 0x30
4939 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4940 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4941 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4942 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4943 "9e91346130748a6e3c124f9149d71c74" // 0x80
4944 "35"
4945 "028181" // INTEGER length 0x81 (prime2) value...
4946 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4947 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4948 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4949 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4950 "9ed39a2d934c880440aed8832f984316" // 0x50
4951 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4952 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4953 "b880677c068e1be936e81288815252a8" // 0x80
4954 "a1"
4955 "028180" // INTEGER length 0x80 (exponent1) value...
4956 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4957 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4958 "5a063212a4f105a3764743e53281988a" // 0x30
4959 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4960 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4961 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4962 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4963 "4719d6e2b9439823719cd08bcd031781" // 0x80
4964 "028181" // INTEGER length 0x81 (exponent2) value...
4965 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4966 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4967 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4968 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4969 "1254186af30b22c10582a8a43e34fe94" // 0x50
4970 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4971 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4972 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4973 "61"
4974 "028181" // INTEGER length 0x81 (coefficient) value...
4975 "00c931617c77829dfb1270502be9195c" // 0x10
4976 "8f2830885f57dba869536811e6864236" // 0x20
4977 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4978 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4979 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4980 "959356210723287b0affcc9f727044d4" // 0x60
4981 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4982 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4983 "22"
4984 // } SEQUENCE
4985 // } SEQUENCE ()
4986);
Selene Huang31ab4042020-04-29 04:22:39 -07004987
4988string zero_masking_key =
4989 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4990string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4991
4992class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4993
4994TEST_P(ImportWrappedKeyTest, Success) {
4995 auto wrapping_key_desc = AuthorizationSetBuilder()
4996 .RsaEncryptionKey(2048, 65537)
4997 .Digest(Digest::SHA_2_256)
4998 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004999 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5000 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005001
5002 ASSERT_EQ(ErrorCode::OK,
5003 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5004 AuthorizationSetBuilder()
5005 .Digest(Digest::SHA_2_256)
5006 .Padding(PaddingMode::RSA_OAEP)));
5007
5008 string message = "Hello World!";
5009 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5010 string ciphertext = EncryptMessage(message, params);
5011 string plaintext = DecryptMessage(ciphertext, params);
5012 EXPECT_EQ(message, plaintext);
5013}
5014
David Drysdaled2cc8c22021-04-15 13:29:45 +01005015/*
5016 * ImportWrappedKeyTest.SuccessSidsIgnored
5017 *
5018 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5019 * include Tag:USER_SECURE_ID.
5020 */
5021TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5022 auto wrapping_key_desc = AuthorizationSetBuilder()
5023 .RsaEncryptionKey(2048, 65537)
5024 .Digest(Digest::SHA_2_256)
5025 .Padding(PaddingMode::RSA_OAEP)
5026 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5027 .SetDefaultValidity();
5028
5029 int64_t password_sid = 42;
5030 int64_t biometric_sid = 24;
5031 ASSERT_EQ(ErrorCode::OK,
5032 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5033 AuthorizationSetBuilder()
5034 .Digest(Digest::SHA_2_256)
5035 .Padding(PaddingMode::RSA_OAEP),
5036 password_sid, biometric_sid));
5037
5038 string message = "Hello World!";
5039 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5040 string ciphertext = EncryptMessage(message, params);
5041 string plaintext = DecryptMessage(ciphertext, params);
5042 EXPECT_EQ(message, plaintext);
5043}
5044
Selene Huang31ab4042020-04-29 04:22:39 -07005045TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5046 auto wrapping_key_desc = AuthorizationSetBuilder()
5047 .RsaEncryptionKey(2048, 65537)
5048 .Digest(Digest::SHA_2_256)
5049 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005050 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5051 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005052
5053 ASSERT_EQ(ErrorCode::OK,
5054 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5055 AuthorizationSetBuilder()
5056 .Digest(Digest::SHA_2_256)
5057 .Padding(PaddingMode::RSA_OAEP)));
5058}
5059
5060TEST_P(ImportWrappedKeyTest, WrongMask) {
5061 auto wrapping_key_desc = AuthorizationSetBuilder()
5062 .RsaEncryptionKey(2048, 65537)
5063 .Digest(Digest::SHA_2_256)
5064 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005065 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5066 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005067
5068 ASSERT_EQ(
5069 ErrorCode::VERIFICATION_FAILED,
5070 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5071 AuthorizationSetBuilder()
5072 .Digest(Digest::SHA_2_256)
5073 .Padding(PaddingMode::RSA_OAEP)));
5074}
5075
5076TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5077 auto wrapping_key_desc = AuthorizationSetBuilder()
5078 .RsaEncryptionKey(2048, 65537)
5079 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005080 .Padding(PaddingMode::RSA_OAEP)
5081 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005082
5083 ASSERT_EQ(
5084 ErrorCode::INCOMPATIBLE_PURPOSE,
5085 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5086 AuthorizationSetBuilder()
5087 .Digest(Digest::SHA_2_256)
5088 .Padding(PaddingMode::RSA_OAEP)));
5089}
5090
David Drysdaled2cc8c22021-04-15 13:29:45 +01005091TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5092 auto wrapping_key_desc = AuthorizationSetBuilder()
5093 .RsaEncryptionKey(2048, 65537)
5094 .Digest(Digest::SHA_2_256)
5095 .Padding(PaddingMode::RSA_PSS)
5096 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5097 .SetDefaultValidity();
5098
5099 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5100 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5101 AuthorizationSetBuilder()
5102 .Digest(Digest::SHA_2_256)
5103 .Padding(PaddingMode::RSA_OAEP)));
5104}
5105
5106TEST_P(ImportWrappedKeyTest, WrongDigest) {
5107 auto wrapping_key_desc = AuthorizationSetBuilder()
5108 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005109 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005110 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005111 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5112 .SetDefaultValidity();
5113
5114 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5115 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5116 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005117 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005118 .Padding(PaddingMode::RSA_OAEP)));
5119}
5120
Selene Huang31ab4042020-04-29 04:22:39 -07005121INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5122
5123typedef KeyMintAidlTestBase EncryptionOperationsTest;
5124
5125/*
5126 * EncryptionOperationsTest.RsaNoPaddingSuccess
5127 *
David Drysdale59cae642021-05-12 13:52:03 +01005128 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005129 */
5130TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005131 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005132 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005133 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5134 .Authorization(TAG_NO_AUTH_REQUIRED)
5135 .RsaEncryptionKey(2048, exponent)
5136 .Padding(PaddingMode::NONE)
5137 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005138
David Drysdaled2cc8c22021-04-15 13:29:45 +01005139 string message = string(2048 / 8, 'a');
5140 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005141 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005142 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005143
David Drysdale59cae642021-05-12 13:52:03 +01005144 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005145 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005146
David Drysdaled2cc8c22021-04-15 13:29:45 +01005147 // Unpadded RSA is deterministic
5148 EXPECT_EQ(ciphertext1, ciphertext2);
5149
5150 CheckedDeleteKey();
5151 }
Selene Huang31ab4042020-04-29 04:22:39 -07005152}
5153
5154/*
5155 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5156 *
David Drysdale59cae642021-05-12 13:52:03 +01005157 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005158 */
5159TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5160 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5161 .Authorization(TAG_NO_AUTH_REQUIRED)
5162 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005163 .Padding(PaddingMode::NONE)
5164 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005165
5166 string message = "1";
5167 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5168
David Drysdale59cae642021-05-12 13:52:03 +01005169 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005170 EXPECT_EQ(2048U / 8, ciphertext.size());
5171
5172 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5173 string plaintext = DecryptMessage(ciphertext, params);
5174
5175 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005176}
5177
5178/*
Selene Huang31ab4042020-04-29 04:22:39 -07005179 * EncryptionOperationsTest.RsaOaepSuccess
5180 *
David Drysdale59cae642021-05-12 13:52:03 +01005181 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005182 */
5183TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5184 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5185
5186 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005187 ASSERT_EQ(ErrorCode::OK,
5188 GenerateKey(AuthorizationSetBuilder()
5189 .Authorization(TAG_NO_AUTH_REQUIRED)
5190 .RsaEncryptionKey(key_size, 65537)
5191 .Padding(PaddingMode::RSA_OAEP)
5192 .Digest(digests)
5193 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5194 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005195
5196 string message = "Hello";
5197
5198 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005199 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5200
5201 auto params = AuthorizationSetBuilder()
5202 .Digest(digest)
5203 .Padding(PaddingMode::RSA_OAEP)
5204 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5205 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005206 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5207 EXPECT_EQ(key_size / 8, ciphertext1.size());
5208
David Drysdale59cae642021-05-12 13:52:03 +01005209 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005210 EXPECT_EQ(key_size / 8, ciphertext2.size());
5211
5212 // OAEP randomizes padding so every result should be different (with astronomically high
5213 // probability).
5214 EXPECT_NE(ciphertext1, ciphertext2);
5215
5216 string plaintext1 = DecryptMessage(ciphertext1, params);
5217 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5218 string plaintext2 = DecryptMessage(ciphertext2, params);
5219 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5220
5221 // Decrypting corrupted ciphertext should fail.
5222 size_t offset_to_corrupt = random() % ciphertext1.size();
5223 char corrupt_byte;
5224 do {
5225 corrupt_byte = static_cast<char>(random() % 256);
5226 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5227 ciphertext1[offset_to_corrupt] = corrupt_byte;
5228
5229 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5230 string result;
5231 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5232 EXPECT_EQ(0U, result.size());
5233 }
5234}
5235
5236/*
5237 * EncryptionOperationsTest.RsaOaepInvalidDigest
5238 *
David Drysdale59cae642021-05-12 13:52:03 +01005239 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005240 * without a digest.
5241 */
5242TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5243 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5244 .Authorization(TAG_NO_AUTH_REQUIRED)
5245 .RsaEncryptionKey(2048, 65537)
5246 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005247 .Digest(Digest::NONE)
5248 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005249
5250 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005251 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005252}
5253
5254/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005255 * EncryptionOperationsTest.RsaOaepInvalidPadding
5256 *
David Drysdale59cae642021-05-12 13:52:03 +01005257 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005258 * with a padding value that is only suitable for signing/verifying.
5259 */
5260TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5262 .Authorization(TAG_NO_AUTH_REQUIRED)
5263 .RsaEncryptionKey(2048, 65537)
5264 .Padding(PaddingMode::RSA_PSS)
5265 .Digest(Digest::NONE)
5266 .SetDefaultValidity()));
5267
5268 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005269 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005270}
5271
5272/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005273 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005274 *
David Drysdale59cae642021-05-12 13:52:03 +01005275 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005276 * with a different digest than was used to encrypt.
5277 */
5278TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005279 if (SecLevel() == SecurityLevel::STRONGBOX) {
5280 GTEST_SKIP() << "Test not applicable to StrongBox device";
5281 }
Selene Huang31ab4042020-04-29 04:22:39 -07005282
5283 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5284 .Authorization(TAG_NO_AUTH_REQUIRED)
5285 .RsaEncryptionKey(1024, 65537)
5286 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005287 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5288 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005289 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005290 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005291 message,
5292 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5293
5294 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5295 .Digest(Digest::SHA_2_256)
5296 .Padding(PaddingMode::RSA_OAEP)));
5297 string result;
5298 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5299 EXPECT_EQ(0U, result.size());
5300}
5301
5302/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005303 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5304 *
David Drysdale59cae642021-05-12 13:52:03 +01005305 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005306 * digests.
5307 */
5308TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5309 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5310
5311 size_t key_size = 2048; // Need largish key for SHA-512 test.
5312 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5313 .OaepMGFDigest(digests)
5314 .Authorization(TAG_NO_AUTH_REQUIRED)
5315 .RsaEncryptionKey(key_size, 65537)
5316 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005317 .Digest(Digest::SHA_2_256)
5318 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005319
5320 string message = "Hello";
5321
5322 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005323 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005324 auto params = AuthorizationSetBuilder()
5325 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5326 .Digest(Digest::SHA_2_256)
5327 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005328 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005329 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5330 EXPECT_EQ(key_size / 8, ciphertext1.size());
5331
David Drysdale59cae642021-05-12 13:52:03 +01005332 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005333 EXPECT_EQ(key_size / 8, ciphertext2.size());
5334
5335 // OAEP randomizes padding so every result should be different (with astronomically high
5336 // probability).
5337 EXPECT_NE(ciphertext1, ciphertext2);
5338
5339 string plaintext1 = DecryptMessage(ciphertext1, params);
5340 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5341 string plaintext2 = DecryptMessage(ciphertext2, params);
5342 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5343
5344 // Decrypting corrupted ciphertext should fail.
5345 size_t offset_to_corrupt = random() % ciphertext1.size();
5346 char corrupt_byte;
5347 do {
5348 corrupt_byte = static_cast<char>(random() % 256);
5349 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5350 ciphertext1[offset_to_corrupt] = corrupt_byte;
5351
5352 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5353 string result;
5354 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5355 EXPECT_EQ(0U, result.size());
5356 }
5357}
5358
5359/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005360 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5361 *
5362 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5363 * specified, defaulting to SHA-1.
5364 */
5365TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5366 size_t key_size = 2048;
5367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5368 .Authorization(TAG_NO_AUTH_REQUIRED)
5369 .RsaEncryptionKey(key_size, 65537)
5370 .Padding(PaddingMode::RSA_OAEP)
5371 .Digest(Digest::SHA_2_256)
5372 .SetDefaultValidity()));
5373
5374 // Do local RSA encryption using the default MGF digest of SHA-1.
5375 string message = "Hello";
5376 auto params =
5377 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5378 string ciphertext = LocalRsaEncryptMessage(message, params);
5379 EXPECT_EQ(key_size / 8, ciphertext.size());
5380
5381 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5382 string plaintext = DecryptMessage(ciphertext, params);
5383 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5384
5385 // Decrypting corrupted ciphertext should fail.
5386 size_t offset_to_corrupt = random() % ciphertext.size();
5387 char corrupt_byte;
5388 do {
5389 corrupt_byte = static_cast<char>(random() % 256);
5390 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5391 ciphertext[offset_to_corrupt] = corrupt_byte;
5392
5393 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5394 string result;
5395 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5396 EXPECT_EQ(0U, result.size());
5397}
5398
5399/*
5400 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5401 *
5402 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5403 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5404 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5405 */
5406TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5407 size_t key_size = 2048;
5408 ASSERT_EQ(ErrorCode::OK,
5409 GenerateKey(AuthorizationSetBuilder()
5410 .Authorization(TAG_NO_AUTH_REQUIRED)
5411 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5412 .RsaEncryptionKey(key_size, 65537)
5413 .Padding(PaddingMode::RSA_OAEP)
5414 .Digest(Digest::SHA_2_256)
5415 .SetDefaultValidity()));
5416
5417 // Do local RSA encryption using the default MGF digest of SHA-1.
5418 string message = "Hello";
5419 auto params =
5420 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5421 string ciphertext = LocalRsaEncryptMessage(message, params);
5422 EXPECT_EQ(key_size / 8, ciphertext.size());
5423
5424 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5425 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5426 // is checked against those values, and found absent.
5427 auto result = Begin(KeyPurpose::DECRYPT, params);
5428 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5429 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5430}
5431
5432/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005433 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5434 *
David Drysdale59cae642021-05-12 13:52:03 +01005435 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005436 * with incompatible MGF digest.
5437 */
5438TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5439 ASSERT_EQ(ErrorCode::OK,
5440 GenerateKey(AuthorizationSetBuilder()
5441 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5442 .Authorization(TAG_NO_AUTH_REQUIRED)
5443 .RsaEncryptionKey(2048, 65537)
5444 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005445 .Digest(Digest::SHA_2_256)
5446 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005447 string message = "Hello World!";
5448
5449 auto params = AuthorizationSetBuilder()
5450 .Padding(PaddingMode::RSA_OAEP)
5451 .Digest(Digest::SHA_2_256)
5452 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005453 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005454}
5455
5456/*
5457 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5458 *
5459 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5460 * with unsupported MGF digest.
5461 */
5462TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5463 ASSERT_EQ(ErrorCode::OK,
5464 GenerateKey(AuthorizationSetBuilder()
5465 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5466 .Authorization(TAG_NO_AUTH_REQUIRED)
5467 .RsaEncryptionKey(2048, 65537)
5468 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005469 .Digest(Digest::SHA_2_256)
5470 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005471 string message = "Hello World!";
5472
5473 auto params = AuthorizationSetBuilder()
5474 .Padding(PaddingMode::RSA_OAEP)
5475 .Digest(Digest::SHA_2_256)
5476 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005477 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005478}
5479
5480/*
Selene Huang31ab4042020-04-29 04:22:39 -07005481 * EncryptionOperationsTest.RsaPkcs1Success
5482 *
5483 * Verifies that RSA PKCS encryption/decrypts works.
5484 */
5485TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5487 .Authorization(TAG_NO_AUTH_REQUIRED)
5488 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005489 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5490 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005491
5492 string message = "Hello World!";
5493 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005494 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005495 EXPECT_EQ(2048U / 8, ciphertext1.size());
5496
David Drysdale59cae642021-05-12 13:52:03 +01005497 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005498 EXPECT_EQ(2048U / 8, ciphertext2.size());
5499
5500 // PKCS1 v1.5 randomizes padding so every result should be different.
5501 EXPECT_NE(ciphertext1, ciphertext2);
5502
5503 string plaintext = DecryptMessage(ciphertext1, params);
5504 EXPECT_EQ(message, plaintext);
5505
5506 // Decrypting corrupted ciphertext should fail.
5507 size_t offset_to_corrupt = random() % ciphertext1.size();
5508 char corrupt_byte;
5509 do {
5510 corrupt_byte = static_cast<char>(random() % 256);
5511 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5512 ciphertext1[offset_to_corrupt] = corrupt_byte;
5513
5514 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5515 string result;
5516 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5517 EXPECT_EQ(0U, result.size());
5518}
5519
5520/*
Selene Huang31ab4042020-04-29 04:22:39 -07005521 * EncryptionOperationsTest.EcdsaEncrypt
5522 *
5523 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5524 */
5525TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5526 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5527 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005528 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005529 .Digest(Digest::NONE)
5530 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005531 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5532 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5533 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5534}
5535
5536/*
5537 * EncryptionOperationsTest.HmacEncrypt
5538 *
5539 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5540 */
5541TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5542 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5543 .Authorization(TAG_NO_AUTH_REQUIRED)
5544 .HmacKey(128)
5545 .Digest(Digest::SHA_2_256)
5546 .Padding(PaddingMode::NONE)
5547 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5548 auto params = AuthorizationSetBuilder()
5549 .Digest(Digest::SHA_2_256)
5550 .Padding(PaddingMode::NONE)
5551 .Authorization(TAG_MAC_LENGTH, 128);
5552 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5553 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5554}
5555
5556/*
5557 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5558 *
5559 * Verifies that AES ECB mode works.
5560 */
5561TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5562 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5563 .Authorization(TAG_NO_AUTH_REQUIRED)
5564 .AesEncryptionKey(128)
5565 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5566 .Padding(PaddingMode::NONE)));
5567
5568 ASSERT_GT(key_blob_.size(), 0U);
5569 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5570
5571 // Two-block message.
5572 string message = "12345678901234567890123456789012";
5573 string ciphertext1 = EncryptMessage(message, params);
5574 EXPECT_EQ(message.size(), ciphertext1.size());
5575
5576 string ciphertext2 = EncryptMessage(string(message), params);
5577 EXPECT_EQ(message.size(), ciphertext2.size());
5578
5579 // ECB is deterministic.
5580 EXPECT_EQ(ciphertext1, ciphertext2);
5581
5582 string plaintext = DecryptMessage(ciphertext1, params);
5583 EXPECT_EQ(message, plaintext);
5584}
5585
5586/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005587 * EncryptionOperationsTest.AesEcbUnknownTag
5588 *
5589 * Verifies that AES ECB operations ignore unknown tags.
5590 */
5591TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5592 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5593 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5594 KeyParameter unknown_param;
5595 unknown_param.tag = unknown_tag;
5596
5597 vector<KeyCharacteristics> key_characteristics;
5598 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5599 .Authorization(TAG_NO_AUTH_REQUIRED)
5600 .AesEncryptionKey(128)
5601 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5602 .Padding(PaddingMode::NONE)
5603 .Authorization(unknown_param),
5604 &key_blob_, &key_characteristics));
5605 ASSERT_GT(key_blob_.size(), 0U);
5606
5607 // Unknown tags should not be returned in key characteristics.
5608 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5609 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5610 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5611 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5612
5613 // Encrypt without mentioning the unknown parameter.
5614 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5615 string message = "12345678901234567890123456789012";
5616 string ciphertext = EncryptMessage(message, params);
5617 EXPECT_EQ(message.size(), ciphertext.size());
5618
5619 // Decrypt including the unknown parameter.
5620 auto decrypt_params = AuthorizationSetBuilder()
5621 .BlockMode(BlockMode::ECB)
5622 .Padding(PaddingMode::NONE)
5623 .Authorization(unknown_param);
5624 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5625 EXPECT_EQ(message, plaintext);
5626}
5627
5628/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005629 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005630 *
5631 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5632 */
5633TEST_P(EncryptionOperationsTest, AesWrongMode) {
5634 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5635 .Authorization(TAG_NO_AUTH_REQUIRED)
5636 .AesEncryptionKey(128)
5637 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5638 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005639 ASSERT_GT(key_blob_.size(), 0U);
5640
Selene Huang31ab4042020-04-29 04:22:39 -07005641 EXPECT_EQ(
5642 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5643 Begin(KeyPurpose::ENCRYPT,
5644 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5645}
5646
5647/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005648 * EncryptionOperationsTest.AesWrongPadding
5649 *
5650 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5651 */
5652TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5654 .Authorization(TAG_NO_AUTH_REQUIRED)
5655 .AesEncryptionKey(128)
5656 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5657 .Padding(PaddingMode::NONE)));
5658 ASSERT_GT(key_blob_.size(), 0U);
5659
5660 EXPECT_EQ(
5661 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5662 Begin(KeyPurpose::ENCRYPT,
5663 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5664}
5665
5666/*
5667 * EncryptionOperationsTest.AesInvalidParams
5668 *
5669 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5670 */
5671TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5672 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5673 .Authorization(TAG_NO_AUTH_REQUIRED)
5674 .AesEncryptionKey(128)
5675 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5676 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5677 .Padding(PaddingMode::NONE)
5678 .Padding(PaddingMode::PKCS7)));
5679 ASSERT_GT(key_blob_.size(), 0U);
5680
5681 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5682 .BlockMode(BlockMode::CBC)
5683 .BlockMode(BlockMode::ECB)
5684 .Padding(PaddingMode::NONE));
5685 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5686 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5687
5688 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5689 .BlockMode(BlockMode::ECB)
5690 .Padding(PaddingMode::NONE)
5691 .Padding(PaddingMode::PKCS7));
5692 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5693 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5694}
5695
5696/*
Selene Huang31ab4042020-04-29 04:22:39 -07005697 * EncryptionOperationsTest.AesWrongPurpose
5698 *
5699 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5700 * specified.
5701 */
5702TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5703 auto err = GenerateKey(AuthorizationSetBuilder()
5704 .Authorization(TAG_NO_AUTH_REQUIRED)
5705 .AesKey(128)
5706 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5707 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5708 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5709 .Padding(PaddingMode::NONE));
5710 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5711 ASSERT_GT(key_blob_.size(), 0U);
5712
5713 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5714 .BlockMode(BlockMode::GCM)
5715 .Padding(PaddingMode::NONE)
5716 .Authorization(TAG_MAC_LENGTH, 128));
5717 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5718
5719 CheckedDeleteKey();
5720
5721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5722 .Authorization(TAG_NO_AUTH_REQUIRED)
5723 .AesKey(128)
5724 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5725 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5726 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5727 .Padding(PaddingMode::NONE)));
5728
5729 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5730 .BlockMode(BlockMode::GCM)
5731 .Padding(PaddingMode::NONE)
5732 .Authorization(TAG_MAC_LENGTH, 128));
5733 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5734}
5735
5736/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005737 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005738 *
5739 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5740 * multiple of the block size and no padding is specified.
5741 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005742TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5743 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005744 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005745 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5746 .Authorization(TAG_NO_AUTH_REQUIRED)
5747 .AesEncryptionKey(128)
5748 .Authorization(TAG_BLOCK_MODE, blockMode)
5749 .Padding(PaddingMode::NONE)));
5750 // Message is slightly shorter than two blocks.
5751 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005752
David Drysdaled2cc8c22021-04-15 13:29:45 +01005753 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5754 AuthorizationSet out_params;
5755 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5756 string ciphertext;
5757 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5758 EXPECT_EQ(0U, ciphertext.size());
5759
5760 CheckedDeleteKey();
5761 }
Selene Huang31ab4042020-04-29 04:22:39 -07005762}
5763
5764/*
5765 * EncryptionOperationsTest.AesEcbPkcs7Padding
5766 *
5767 * Verifies that AES PKCS7 padding works for any message length.
5768 */
5769TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5771 .Authorization(TAG_NO_AUTH_REQUIRED)
5772 .AesEncryptionKey(128)
5773 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5774 .Padding(PaddingMode::PKCS7)));
5775
5776 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5777
5778 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005779 for (size_t i = 0; i <= 48; i++) {
5780 SCOPED_TRACE(testing::Message() << "i = " << i);
5781 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5782 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005783 string ciphertext = EncryptMessage(message, params);
5784 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5785 string plaintext = DecryptMessage(ciphertext, params);
5786 EXPECT_EQ(message, plaintext);
5787 }
5788}
5789
5790/*
5791 * EncryptionOperationsTest.AesEcbWrongPadding
5792 *
5793 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5794 * specified.
5795 */
5796TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5798 .Authorization(TAG_NO_AUTH_REQUIRED)
5799 .AesEncryptionKey(128)
5800 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5801 .Padding(PaddingMode::NONE)));
5802
5803 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5804
5805 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005806 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005807 string message(i, 'a');
5808 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5809 }
5810}
5811
5812/*
5813 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5814 *
5815 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5816 */
5817TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5819 .Authorization(TAG_NO_AUTH_REQUIRED)
5820 .AesEncryptionKey(128)
5821 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5822 .Padding(PaddingMode::PKCS7)));
5823
5824 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5825
5826 string message = "a";
5827 string ciphertext = EncryptMessage(message, params);
5828 EXPECT_EQ(16U, ciphertext.size());
5829 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005830
Seth Moore7a55ae32021-06-23 14:28:11 -07005831 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5832 ++ciphertext[ciphertext.size() / 2];
5833
5834 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5835 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005836 ErrorCode error = Finish(ciphertext, &plaintext);
5837 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005838 // This is the expected error, we can exit the test now.
5839 return;
5840 } else {
5841 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005842 ASSERT_EQ(error, ErrorCode::OK)
5843 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005844 }
5845 }
5846 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005847}
5848
David Drysdaleb8093292022-04-08 12:22:35 +01005849/*
5850 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5851 *
5852 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5853 */
5854TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5855 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5856 .Authorization(TAG_NO_AUTH_REQUIRED)
5857 .AesEncryptionKey(128)
5858 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5859 .Padding(PaddingMode::PKCS7)));
5860
5861 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5862
5863 string message = "a";
5864 string ciphertext = EncryptMessage(message, params);
5865 EXPECT_EQ(16U, ciphertext.size());
5866 EXPECT_NE(ciphertext, message);
5867
5868 // Shorten the ciphertext.
5869 ciphertext.resize(ciphertext.size() - 1);
5870 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5871 string plaintext;
5872 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5873}
5874
Selene Huang31ab4042020-04-29 04:22:39 -07005875vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5876 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005877 EXPECT_TRUE(iv);
5878 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005879}
5880
5881/*
5882 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5883 *
5884 * Verifies that AES CTR mode works.
5885 */
5886TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5888 .Authorization(TAG_NO_AUTH_REQUIRED)
5889 .AesEncryptionKey(128)
5890 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5891 .Padding(PaddingMode::NONE)));
5892
5893 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5894
5895 string message = "123";
5896 AuthorizationSet out_params;
5897 string ciphertext1 = EncryptMessage(message, params, &out_params);
5898 vector<uint8_t> iv1 = CopyIv(out_params);
5899 EXPECT_EQ(16U, iv1.size());
5900
5901 EXPECT_EQ(message.size(), ciphertext1.size());
5902
5903 out_params.Clear();
5904 string ciphertext2 = EncryptMessage(message, params, &out_params);
5905 vector<uint8_t> iv2 = CopyIv(out_params);
5906 EXPECT_EQ(16U, iv2.size());
5907
5908 // IVs should be random, so ciphertexts should differ.
5909 EXPECT_NE(ciphertext1, ciphertext2);
5910
5911 auto params_iv1 =
5912 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5913 auto params_iv2 =
5914 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5915
5916 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5917 EXPECT_EQ(message, plaintext);
5918 plaintext = DecryptMessage(ciphertext2, params_iv2);
5919 EXPECT_EQ(message, plaintext);
5920
5921 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5922 plaintext = DecryptMessage(ciphertext1, params_iv2);
5923 EXPECT_NE(message, plaintext);
5924 plaintext = DecryptMessage(ciphertext2, params_iv1);
5925 EXPECT_NE(message, plaintext);
5926}
5927
5928/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305929 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005930 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305931 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005932 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305933TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5934 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5935}
Selene Huang31ab4042020-04-29 04:22:39 -07005936
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305937/*
5938 * EncryptionOperationsTest.AesCbcIncremental
5939 *
5940 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5941 */
5942TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5943 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5944}
Selene Huang31ab4042020-04-29 04:22:39 -07005945
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305946/*
5947 * EncryptionOperationsTest.AesCtrIncremental
5948 *
5949 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5950 */
5951TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5952 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5953}
Selene Huang31ab4042020-04-29 04:22:39 -07005954
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305955/*
5956 * EncryptionOperationsTest.AesGcmIncremental
5957 *
5958 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5959 */
5960TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5961 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005962}
5963
Prashant Patildd5f7f02022-07-06 18:58:07 +00005964/*
5965 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5966 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5967 */
5968TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5969 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5970 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5971 string kat_plaintext =
5972 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5973 "809FFF37081C22EF278F896AB213A2A631");
5974 string kat_ciphertext =
5975 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5976 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5977 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5978 kat_ciphertext);
5979}
5980
5981/*
5982 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5983 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5984 */
5985TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5986 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5987 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5988 string kat_plaintext =
5989 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5990 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5991 string kat_ciphertext =
5992 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5993 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5994 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5995 kat_plaintext, kat_ciphertext);
5996}
5997
5998/*
5999 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6000 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6001 */
6002TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6003 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6004 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6005 string kat_plaintext =
6006 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6007 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6008 string kat_ciphertext =
6009 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6010 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6011 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6012 kat_ciphertext);
6013}
6014
6015/*
6016 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6017 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6018 */
6019TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6020 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6021 string kat_plaintext =
6022 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6023 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6024 string kat_ciphertext =
6025 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6026 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6027 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6028 kat_ciphertext);
6029}
6030
6031/*
6032 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6033 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6034 */
6035TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6036 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6037 string kat_plaintext =
6038 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6039 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6040 string kat_ciphertext =
6041 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6042 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6043 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6044 kat_ciphertext);
6045}
6046
6047/*
6048 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6049 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6050 */
6051TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6052 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6053 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6054 string kat_plaintext =
6055 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6056 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6057 string kat_ciphertext =
6058 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6059 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6060 "bdfcc0cba0");
6061
6062 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6063 kat_ciphertext);
6064}
6065
6066/*
6067 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6068 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6069 */
6070TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6071 if (SecLevel() == SecurityLevel::STRONGBOX) {
6072 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6073 }
6074 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6075 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6076 string kat_plaintext =
6077 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6078 "167f2497c994bd496eb80bfb2ba2c9d5af");
6079 string kat_ciphertext =
6080 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6081 "72c134552f3a138e726fbe493b3a839598");
6082 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6083 kat_ciphertext);
6084}
6085
6086/*
6087 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6088 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6089 */
6090TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6091 if (SecLevel() == SecurityLevel::STRONGBOX) {
6092 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6093 }
6094 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6095 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6096 string kat_plaintext =
6097 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6098 "b170");
6099 string kat_ciphertext =
6100 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6101 "4e3884138ff403a41fd99818708ada301c");
6102 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6103 kat_plaintext, kat_ciphertext);
6104}
6105
6106/*
6107 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6108 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6109 */
6110TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6111 if (SecLevel() == SecurityLevel::STRONGBOX) {
6112 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6113 }
6114 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6115 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6116 string kat_plaintext =
6117 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6118 "28091e09cdbbd3b42b");
6119 string kat_ciphertext =
6120 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6121 "2ae0f90f0c19f42b4a");
6122 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6123 kat_ciphertext);
6124}
6125
6126/*
6127 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6128 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6129 */
6130TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6131 if (SecLevel() == SecurityLevel::STRONGBOX) {
6132 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6133 }
6134 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6135 string kat_plaintext =
6136 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6137 "44ab");
6138 string kat_ciphertext =
6139 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6140 "2453");
6141 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6142 kat_ciphertext);
6143}
6144
6145/*
6146 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6147 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6148 */
6149TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6150 if (SecLevel() == SecurityLevel::STRONGBOX) {
6151 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6152 }
6153 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6154 string kat_plaintext =
6155 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6156 "e2c7");
6157 string kat_ciphertext =
6158 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6159 "bb7e3a889dd4a9589098b44acf1056e7aa");
6160 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6161 kat_ciphertext);
6162}
6163
6164/*
6165 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6166 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6167 */
6168TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6169 if (SecLevel() == SecurityLevel::STRONGBOX) {
6170 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6171 }
6172 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6173 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6174 string kat_plaintext =
6175 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6176 "ff52");
6177 string kat_ciphertext =
6178 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6179 "1413ad70fb0e1970669095ad77ebb5974ae8");
6180
6181 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6182 kat_ciphertext);
6183}
6184
6185/*
6186 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6187 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6188 */
6189TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6190 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6191 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6192 string kat_plaintext =
6193 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6194 "494cb53caca353e4b637ba05687be20f8d");
6195 string kat_ciphertext =
6196 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6197 "6047da1e4fd7c4e1cf2656097f75ae8685");
6198 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6199 kat_ciphertext);
6200}
6201
6202/*
6203 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6204 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6205 */
6206TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6207 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6208 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6209 string kat_plaintext =
6210 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6211 "2545a82b73c48078b9dae62261c65909");
6212 string kat_ciphertext =
6213 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6214 "9403a71987b95124073d69f2a3cb95b0ab");
6215 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6216 kat_plaintext, kat_ciphertext);
6217}
6218
6219/*
6220 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6221 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6222 */
6223TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6224 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6225 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6226 string kat_plaintext =
6227 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6228 "1f6db3c884");
6229 string kat_ciphertext =
6230 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6231 "a7be30d4c3");
6232 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6233 kat_ciphertext);
6234}
6235
6236/*
6237 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6238 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6239 */
6240TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6241 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6242 string kat_plaintext =
6243 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6244 "31a476d6806b8116089c6ec50bb543200f");
6245 string kat_ciphertext =
6246 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6247 "c83e377faf246288931136bef2a07c0be4");
6248 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6249 kat_ciphertext);
6250}
6251
6252/*
6253 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6254 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6255 */
6256TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6257 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6258 string kat_plaintext =
6259 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6260 "6f");
6261 string kat_ciphertext =
6262 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6263 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6264 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6265 kat_ciphertext);
6266}
6267
6268/*
6269 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6270 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6271 */
6272TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6273 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6274 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6275 string kat_plaintext =
6276 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6277 "f0");
6278 string kat_ciphertext =
6279 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6280 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6281
6282 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6283 kat_ciphertext);
6284}
6285
Selene Huang31ab4042020-04-29 04:22:39 -07006286struct AesCtrSp80038aTestVector {
6287 const char* key;
6288 const char* nonce;
6289 const char* plaintext;
6290 const char* ciphertext;
6291};
6292
6293// These test vectors are taken from
6294// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6295static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6296 // AES-128
6297 {
6298 "2b7e151628aed2a6abf7158809cf4f3c",
6299 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6300 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6301 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6302 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6303 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6304 },
6305 // AES-192
6306 {
6307 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6308 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6309 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6310 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6311 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6312 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6313 },
6314 // AES-256
6315 {
6316 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6317 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6318 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6319 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6320 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6321 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6322 },
6323};
6324
6325/*
6326 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6327 *
6328 * Verifies AES CTR implementation against SP800-38A test vectors.
6329 */
6330TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6331 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6332 for (size_t i = 0; i < 3; i++) {
6333 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6334 const string key = hex2str(test.key);
6335 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6336 InvalidSizes.end())
6337 continue;
6338 const string nonce = hex2str(test.nonce);
6339 const string plaintext = hex2str(test.plaintext);
6340 const string ciphertext = hex2str(test.ciphertext);
6341 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6342 }
6343}
6344
6345/*
6346 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6347 *
6348 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6349 */
6350TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6352 .Authorization(TAG_NO_AUTH_REQUIRED)
6353 .AesEncryptionKey(128)
6354 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6355 .Padding(PaddingMode::PKCS7)));
6356 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6357 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6358}
6359
6360/*
6361 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6362 *
6363 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6364 */
6365TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6366 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6367 .Authorization(TAG_NO_AUTH_REQUIRED)
6368 .AesEncryptionKey(128)
6369 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6370 .Authorization(TAG_CALLER_NONCE)
6371 .Padding(PaddingMode::NONE)));
6372
6373 auto params = AuthorizationSetBuilder()
6374 .BlockMode(BlockMode::CTR)
6375 .Padding(PaddingMode::NONE)
6376 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6377 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6378
6379 params = AuthorizationSetBuilder()
6380 .BlockMode(BlockMode::CTR)
6381 .Padding(PaddingMode::NONE)
6382 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6383 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6384
6385 params = AuthorizationSetBuilder()
6386 .BlockMode(BlockMode::CTR)
6387 .Padding(PaddingMode::NONE)
6388 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6389 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6390}
6391
6392/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006393 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006394 *
6395 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6396 */
6397TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6399 .Authorization(TAG_NO_AUTH_REQUIRED)
6400 .AesEncryptionKey(128)
6401 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6402 .Padding(PaddingMode::NONE)));
6403 // Two-block message.
6404 string message = "12345678901234567890123456789012";
6405 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6406 AuthorizationSet out_params;
6407 string ciphertext1 = EncryptMessage(message, params, &out_params);
6408 vector<uint8_t> iv1 = CopyIv(out_params);
6409 EXPECT_EQ(message.size(), ciphertext1.size());
6410
6411 out_params.Clear();
6412
6413 string ciphertext2 = EncryptMessage(message, params, &out_params);
6414 vector<uint8_t> iv2 = CopyIv(out_params);
6415 EXPECT_EQ(message.size(), ciphertext2.size());
6416
6417 // IVs should be random, so ciphertexts should differ.
6418 EXPECT_NE(ciphertext1, ciphertext2);
6419
6420 params.push_back(TAG_NONCE, iv1);
6421 string plaintext = DecryptMessage(ciphertext1, params);
6422 EXPECT_EQ(message, plaintext);
6423}
6424
6425/*
Tommy Chiuee705692021-09-23 20:09:13 +08006426 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6427 *
6428 * Verifies that keymaster generates correct output on zero-input with
6429 * NonePadding mode
6430 */
6431TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6433 .Authorization(TAG_NO_AUTH_REQUIRED)
6434 .AesEncryptionKey(128)
6435 .BlockMode(BlockMode::CBC)
6436 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6437
6438 // Zero input message
6439 string message = "";
6440 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006441 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006442 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6443 AuthorizationSet out_params;
6444 string ciphertext1 = EncryptMessage(message, params, &out_params);
6445 vector<uint8_t> iv1 = CopyIv(out_params);
6446 if (padding == PaddingMode::NONE)
6447 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6448 else
6449 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6450
6451 out_params.Clear();
6452
6453 string ciphertext2 = EncryptMessage(message, params, &out_params);
6454 vector<uint8_t> iv2 = CopyIv(out_params);
6455 if (padding == PaddingMode::NONE)
6456 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6457 else
6458 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6459
6460 // IVs should be random
6461 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6462
6463 params.push_back(TAG_NONCE, iv1);
6464 string plaintext = DecryptMessage(ciphertext1, params);
6465 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6466 }
6467}
6468
6469/*
Selene Huang31ab4042020-04-29 04:22:39 -07006470 * EncryptionOperationsTest.AesCallerNonce
6471 *
6472 * Verifies that AES caller-provided nonces work correctly.
6473 */
6474TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6475 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6476 .Authorization(TAG_NO_AUTH_REQUIRED)
6477 .AesEncryptionKey(128)
6478 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6479 .Authorization(TAG_CALLER_NONCE)
6480 .Padding(PaddingMode::NONE)));
6481
6482 string message = "12345678901234567890123456789012";
6483
6484 // Don't specify nonce, should get a random one.
6485 AuthorizationSetBuilder params =
6486 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6487 AuthorizationSet out_params;
6488 string ciphertext = EncryptMessage(message, params, &out_params);
6489 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006490 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006491
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006492 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006493 string plaintext = DecryptMessage(ciphertext, params);
6494 EXPECT_EQ(message, plaintext);
6495
6496 // Now specify a nonce, should also work.
6497 params = AuthorizationSetBuilder()
6498 .BlockMode(BlockMode::CBC)
6499 .Padding(PaddingMode::NONE)
6500 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6501 out_params.Clear();
6502 ciphertext = EncryptMessage(message, params, &out_params);
6503
6504 // Decrypt with correct nonce.
6505 plaintext = DecryptMessage(ciphertext, params);
6506 EXPECT_EQ(message, plaintext);
6507
6508 // Try with wrong nonce.
6509 params = AuthorizationSetBuilder()
6510 .BlockMode(BlockMode::CBC)
6511 .Padding(PaddingMode::NONE)
6512 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6513 plaintext = DecryptMessage(ciphertext, params);
6514 EXPECT_NE(message, plaintext);
6515}
6516
6517/*
6518 * EncryptionOperationsTest.AesCallerNonceProhibited
6519 *
6520 * Verifies that caller-provided nonces are not permitted when not specified in the key
6521 * authorizations.
6522 */
6523TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6525 .Authorization(TAG_NO_AUTH_REQUIRED)
6526 .AesEncryptionKey(128)
6527 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6528 .Padding(PaddingMode::NONE)));
6529
6530 string message = "12345678901234567890123456789012";
6531
6532 // Don't specify nonce, should get a random one.
6533 AuthorizationSetBuilder params =
6534 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6535 AuthorizationSet out_params;
6536 string ciphertext = EncryptMessage(message, params, &out_params);
6537 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006538 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006539
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006540 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006541 string plaintext = DecryptMessage(ciphertext, params);
6542 EXPECT_EQ(message, plaintext);
6543
6544 // Now specify a nonce, should fail
6545 params = AuthorizationSetBuilder()
6546 .BlockMode(BlockMode::CBC)
6547 .Padding(PaddingMode::NONE)
6548 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6549 out_params.Clear();
6550 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6551}
6552
6553/*
6554 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6555 *
6556 * Verifies that AES GCM mode works.
6557 */
6558TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6560 .Authorization(TAG_NO_AUTH_REQUIRED)
6561 .AesEncryptionKey(128)
6562 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6563 .Padding(PaddingMode::NONE)
6564 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6565
6566 string aad = "foobar";
6567 string message = "123456789012345678901234567890123456";
6568
6569 auto begin_params = AuthorizationSetBuilder()
6570 .BlockMode(BlockMode::GCM)
6571 .Padding(PaddingMode::NONE)
6572 .Authorization(TAG_MAC_LENGTH, 128);
6573
Selene Huang31ab4042020-04-29 04:22:39 -07006574 // Encrypt
6575 AuthorizationSet begin_out_params;
6576 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6577 << "Begin encrypt";
6578 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006579 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6580 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006581 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6582
6583 // Grab nonce
6584 begin_params.push_back(begin_out_params);
6585
6586 // Decrypt.
6587 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006588 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006589 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006590 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006591 EXPECT_EQ(message.length(), plaintext.length());
6592 EXPECT_EQ(message, plaintext);
6593}
6594
6595/*
6596 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6597 *
6598 * Verifies that AES GCM mode works, even when there's a long delay
6599 * between operations.
6600 */
6601TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6603 .Authorization(TAG_NO_AUTH_REQUIRED)
6604 .AesEncryptionKey(128)
6605 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6606 .Padding(PaddingMode::NONE)
6607 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6608
6609 string aad = "foobar";
6610 string message = "123456789012345678901234567890123456";
6611
6612 auto begin_params = AuthorizationSetBuilder()
6613 .BlockMode(BlockMode::GCM)
6614 .Padding(PaddingMode::NONE)
6615 .Authorization(TAG_MAC_LENGTH, 128);
6616
Selene Huang31ab4042020-04-29 04:22:39 -07006617 // Encrypt
6618 AuthorizationSet begin_out_params;
6619 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6620 << "Begin encrypt";
6621 string ciphertext;
6622 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006623 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006624 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006625 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006626
6627 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6628
6629 // Grab nonce
6630 begin_params.push_back(begin_out_params);
6631
6632 // Decrypt.
6633 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6634 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006635 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006636 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006637 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006638 sleep(5);
6639 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6640 EXPECT_EQ(message.length(), plaintext.length());
6641 EXPECT_EQ(message, plaintext);
6642}
6643
6644/*
6645 * EncryptionOperationsTest.AesGcmDifferentNonces
6646 *
6647 * Verifies that encrypting the same data with different nonces produces different outputs.
6648 */
6649TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6651 .Authorization(TAG_NO_AUTH_REQUIRED)
6652 .AesEncryptionKey(128)
6653 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6654 .Padding(PaddingMode::NONE)
6655 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6656 .Authorization(TAG_CALLER_NONCE)));
6657
6658 string aad = "foobar";
6659 string message = "123456789012345678901234567890123456";
6660 string nonce1 = "000000000000";
6661 string nonce2 = "111111111111";
6662 string nonce3 = "222222222222";
6663
6664 string ciphertext1 =
6665 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6666 string ciphertext2 =
6667 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6668 string ciphertext3 =
6669 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6670
6671 ASSERT_NE(ciphertext1, ciphertext2);
6672 ASSERT_NE(ciphertext1, ciphertext3);
6673 ASSERT_NE(ciphertext2, ciphertext3);
6674}
6675
6676/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006677 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6678 *
6679 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6680 */
6681TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6682 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6683 .Authorization(TAG_NO_AUTH_REQUIRED)
6684 .AesEncryptionKey(128)
6685 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6686 .Padding(PaddingMode::NONE)
6687 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6688
6689 string aad = "foobar";
6690 string message = "123456789012345678901234567890123456";
6691
6692 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6693 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6694 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6695
6696 ASSERT_NE(ciphertext1, ciphertext2);
6697 ASSERT_NE(ciphertext1, ciphertext3);
6698 ASSERT_NE(ciphertext2, ciphertext3);
6699}
6700
6701/*
Selene Huang31ab4042020-04-29 04:22:39 -07006702 * EncryptionOperationsTest.AesGcmTooShortTag
6703 *
6704 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6705 */
6706TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6708 .Authorization(TAG_NO_AUTH_REQUIRED)
6709 .AesEncryptionKey(128)
6710 .BlockMode(BlockMode::GCM)
6711 .Padding(PaddingMode::NONE)
6712 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6713 string message = "123456789012345678901234567890123456";
6714 auto params = AuthorizationSetBuilder()
6715 .BlockMode(BlockMode::GCM)
6716 .Padding(PaddingMode::NONE)
6717 .Authorization(TAG_MAC_LENGTH, 96);
6718
6719 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6720}
6721
6722/*
6723 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6724 *
6725 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6726 */
6727TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6729 .Authorization(TAG_NO_AUTH_REQUIRED)
6730 .AesEncryptionKey(128)
6731 .BlockMode(BlockMode::GCM)
6732 .Padding(PaddingMode::NONE)
6733 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6734 string aad = "foobar";
6735 string message = "123456789012345678901234567890123456";
6736 auto params = AuthorizationSetBuilder()
6737 .BlockMode(BlockMode::GCM)
6738 .Padding(PaddingMode::NONE)
6739 .Authorization(TAG_MAC_LENGTH, 128);
6740
Selene Huang31ab4042020-04-29 04:22:39 -07006741 // Encrypt
6742 AuthorizationSet begin_out_params;
6743 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6744 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006745 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006746
6747 AuthorizationSet finish_out_params;
6748 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006749 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6750 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006751
6752 params = AuthorizationSetBuilder()
6753 .Authorizations(begin_out_params)
6754 .BlockMode(BlockMode::GCM)
6755 .Padding(PaddingMode::NONE)
6756 .Authorization(TAG_MAC_LENGTH, 96);
6757
6758 // Decrypt.
6759 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6760}
6761
6762/*
6763 * EncryptionOperationsTest.AesGcmCorruptKey
6764 *
6765 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6766 */
6767TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6768 const uint8_t nonce_bytes[] = {
6769 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6770 };
6771 string nonce = make_string(nonce_bytes);
6772 const uint8_t ciphertext_bytes[] = {
6773 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6774 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6775 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6776 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6777 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6778 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6779 };
6780 string ciphertext = make_string(ciphertext_bytes);
6781
6782 auto params = AuthorizationSetBuilder()
6783 .BlockMode(BlockMode::GCM)
6784 .Padding(PaddingMode::NONE)
6785 .Authorization(TAG_MAC_LENGTH, 128)
6786 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6787
6788 auto import_params = AuthorizationSetBuilder()
6789 .Authorization(TAG_NO_AUTH_REQUIRED)
6790 .AesEncryptionKey(128)
6791 .BlockMode(BlockMode::GCM)
6792 .Padding(PaddingMode::NONE)
6793 .Authorization(TAG_CALLER_NONCE)
6794 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6795
6796 // Import correct key and decrypt
6797 const uint8_t key_bytes[] = {
6798 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6799 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6800 };
6801 string key = make_string(key_bytes);
6802 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6803 string plaintext = DecryptMessage(ciphertext, params);
6804 CheckedDeleteKey();
6805
6806 // Corrupt key and attempt to decrypt
6807 key[0] = 0;
6808 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6809 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6810 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6811 CheckedDeleteKey();
6812}
6813
6814/*
6815 * EncryptionOperationsTest.AesGcmAadNoData
6816 *
6817 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6818 * encrypt.
6819 */
6820TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6821 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6822 .Authorization(TAG_NO_AUTH_REQUIRED)
6823 .AesEncryptionKey(128)
6824 .BlockMode(BlockMode::GCM)
6825 .Padding(PaddingMode::NONE)
6826 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6827
6828 string aad = "1234567890123456";
6829 auto params = AuthorizationSetBuilder()
6830 .BlockMode(BlockMode::GCM)
6831 .Padding(PaddingMode::NONE)
6832 .Authorization(TAG_MAC_LENGTH, 128);
6833
Selene Huang31ab4042020-04-29 04:22:39 -07006834 // Encrypt
6835 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006836 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006837 string ciphertext;
6838 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006839 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6840 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006841 EXPECT_TRUE(finish_out_params.empty());
6842
6843 // Grab nonce
6844 params.push_back(begin_out_params);
6845
6846 // Decrypt.
6847 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006848 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006849 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006850 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006851
6852 EXPECT_TRUE(finish_out_params.empty());
6853
6854 EXPECT_EQ("", plaintext);
6855}
6856
6857/*
6858 * EncryptionOperationsTest.AesGcmMultiPartAad
6859 *
6860 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6861 * chunks.
6862 */
6863TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6864 const size_t tag_bits = 128;
6865 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6866 .Authorization(TAG_NO_AUTH_REQUIRED)
6867 .AesEncryptionKey(128)
6868 .BlockMode(BlockMode::GCM)
6869 .Padding(PaddingMode::NONE)
6870 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6871
6872 string message = "123456789012345678901234567890123456";
6873 auto begin_params = AuthorizationSetBuilder()
6874 .BlockMode(BlockMode::GCM)
6875 .Padding(PaddingMode::NONE)
6876 .Authorization(TAG_MAC_LENGTH, tag_bits);
6877 AuthorizationSet begin_out_params;
6878
David Drysdale7fc26b92022-05-13 09:54:24 +01006879 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006880
6881 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006882 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6883 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006884 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006885 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6886 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006887
Selene Huang31ab4042020-04-29 04:22:39 -07006888 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006889 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006890
6891 // Grab nonce.
6892 begin_params.push_back(begin_out_params);
6893
6894 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006895 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006896 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006897 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006898 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006899 EXPECT_EQ(message, plaintext);
6900}
6901
6902/*
6903 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6904 *
6905 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6906 */
6907TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6908 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6909 .Authorization(TAG_NO_AUTH_REQUIRED)
6910 .AesEncryptionKey(128)
6911 .BlockMode(BlockMode::GCM)
6912 .Padding(PaddingMode::NONE)
6913 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6914
6915 string message = "123456789012345678901234567890123456";
6916 auto begin_params = AuthorizationSetBuilder()
6917 .BlockMode(BlockMode::GCM)
6918 .Padding(PaddingMode::NONE)
6919 .Authorization(TAG_MAC_LENGTH, 128);
6920 AuthorizationSet begin_out_params;
6921
David Drysdale7fc26b92022-05-13 09:54:24 +01006922 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006923
Shawn Willden92d79c02021-02-19 07:31:55 -07006924 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006925 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006926 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6927 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006928
David Drysdaled2cc8c22021-04-15 13:29:45 +01006929 // The failure should have already cancelled the operation.
6930 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6931
Shawn Willden92d79c02021-02-19 07:31:55 -07006932 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006933}
6934
6935/*
6936 * EncryptionOperationsTest.AesGcmBadAad
6937 *
6938 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6939 */
6940TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6942 .Authorization(TAG_NO_AUTH_REQUIRED)
6943 .AesEncryptionKey(128)
6944 .BlockMode(BlockMode::GCM)
6945 .Padding(PaddingMode::NONE)
6946 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6947
6948 string message = "12345678901234567890123456789012";
6949 auto begin_params = AuthorizationSetBuilder()
6950 .BlockMode(BlockMode::GCM)
6951 .Padding(PaddingMode::NONE)
6952 .Authorization(TAG_MAC_LENGTH, 128);
6953
Selene Huang31ab4042020-04-29 04:22:39 -07006954 // Encrypt
6955 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006956 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006957 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006958 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006959 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006960
6961 // Grab nonce
6962 begin_params.push_back(begin_out_params);
6963
Selene Huang31ab4042020-04-29 04:22:39 -07006964 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006965 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006966 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006967 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006968 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006969}
6970
6971/*
6972 * EncryptionOperationsTest.AesGcmWrongNonce
6973 *
6974 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6975 */
6976TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6977 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6978 .Authorization(TAG_NO_AUTH_REQUIRED)
6979 .AesEncryptionKey(128)
6980 .BlockMode(BlockMode::GCM)
6981 .Padding(PaddingMode::NONE)
6982 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6983
6984 string message = "12345678901234567890123456789012";
6985 auto begin_params = AuthorizationSetBuilder()
6986 .BlockMode(BlockMode::GCM)
6987 .Padding(PaddingMode::NONE)
6988 .Authorization(TAG_MAC_LENGTH, 128);
6989
Selene Huang31ab4042020-04-29 04:22:39 -07006990 // Encrypt
6991 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006992 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006993 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006994 string ciphertext;
6995 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006996 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006997
6998 // Wrong nonce
6999 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7000
7001 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007002 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007003 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007004 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007005 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007006
7007 // With wrong nonce, should have gotten garbage plaintext (or none).
7008 EXPECT_NE(message, plaintext);
7009}
7010
7011/*
7012 * EncryptionOperationsTest.AesGcmCorruptTag
7013 *
7014 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7015 */
7016TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7017 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7018 .Authorization(TAG_NO_AUTH_REQUIRED)
7019 .AesEncryptionKey(128)
7020 .BlockMode(BlockMode::GCM)
7021 .Padding(PaddingMode::NONE)
7022 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7023
7024 string aad = "1234567890123456";
7025 string message = "123456789012345678901234567890123456";
7026
7027 auto params = AuthorizationSetBuilder()
7028 .BlockMode(BlockMode::GCM)
7029 .Padding(PaddingMode::NONE)
7030 .Authorization(TAG_MAC_LENGTH, 128);
7031
Selene Huang31ab4042020-04-29 04:22:39 -07007032 // Encrypt
7033 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007034 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007035 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007036 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007037 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007038
7039 // Corrupt tag
7040 ++(*ciphertext.rbegin());
7041
7042 // Grab nonce
7043 params.push_back(begin_out_params);
7044
7045 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007046 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007047 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007048 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007049 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007050}
7051
7052/*
7053 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7054 *
7055 * Verifies that 3DES is basically functional.
7056 */
7057TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7058 auto auths = AuthorizationSetBuilder()
7059 .TripleDesEncryptionKey(168)
7060 .BlockMode(BlockMode::ECB)
7061 .Authorization(TAG_NO_AUTH_REQUIRED)
7062 .Padding(PaddingMode::NONE);
7063
7064 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7065 // Two-block message.
7066 string message = "1234567890123456";
7067 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7068 string ciphertext1 = EncryptMessage(message, inParams);
7069 EXPECT_EQ(message.size(), ciphertext1.size());
7070
7071 string ciphertext2 = EncryptMessage(string(message), inParams);
7072 EXPECT_EQ(message.size(), ciphertext2.size());
7073
7074 // ECB is deterministic.
7075 EXPECT_EQ(ciphertext1, ciphertext2);
7076
7077 string plaintext = DecryptMessage(ciphertext1, inParams);
7078 EXPECT_EQ(message, plaintext);
7079}
7080
7081/*
7082 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7083 *
7084 * Verifies that CBC keys reject ECB usage.
7085 */
7086TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7087 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7088 .TripleDesEncryptionKey(168)
7089 .BlockMode(BlockMode::CBC)
7090 .Authorization(TAG_NO_AUTH_REQUIRED)
7091 .Padding(PaddingMode::NONE)));
7092
7093 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7094 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7095}
7096
7097/*
7098 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7099 *
7100 * Tests ECB mode with PKCS#7 padding, various message sizes.
7101 */
7102TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7104 .TripleDesEncryptionKey(168)
7105 .BlockMode(BlockMode::ECB)
7106 .Authorization(TAG_NO_AUTH_REQUIRED)
7107 .Padding(PaddingMode::PKCS7)));
7108
7109 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007110 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007111 string message(i, 'a');
7112 auto inParams =
7113 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7114 string ciphertext = EncryptMessage(message, inParams);
7115 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7116 string plaintext = DecryptMessage(ciphertext, inParams);
7117 EXPECT_EQ(message, plaintext);
7118 }
7119}
7120
7121/*
7122 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7123 *
7124 * Verifies that keys configured for no padding reject PKCS7 padding
7125 */
7126TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7127 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7128 .TripleDesEncryptionKey(168)
7129 .BlockMode(BlockMode::ECB)
7130 .Authorization(TAG_NO_AUTH_REQUIRED)
7131 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007132 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7133 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007134}
7135
7136/*
7137 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7138 *
7139 * Verifies that corrupted padding is detected.
7140 */
7141TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7143 .TripleDesEncryptionKey(168)
7144 .BlockMode(BlockMode::ECB)
7145 .Authorization(TAG_NO_AUTH_REQUIRED)
7146 .Padding(PaddingMode::PKCS7)));
7147
7148 string message = "a";
7149 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7150 EXPECT_EQ(8U, ciphertext.size());
7151 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007152
7153 AuthorizationSetBuilder begin_params;
7154 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7155 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007156
7157 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7158 ++ciphertext[ciphertext.size() / 2];
7159
David Drysdale7fc26b92022-05-13 09:54:24 +01007160 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007161 string plaintext;
7162 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7163 ErrorCode error = Finish(&plaintext);
7164 if (error == ErrorCode::INVALID_ARGUMENT) {
7165 // This is the expected error, we can exit the test now.
7166 return;
7167 } else {
7168 // Very small chance we got valid decryption, so try again.
7169 ASSERT_EQ(error, ErrorCode::OK);
7170 }
7171 }
7172 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007173}
7174
7175struct TripleDesTestVector {
7176 const char* name;
7177 const KeyPurpose purpose;
7178 const BlockMode block_mode;
7179 const PaddingMode padding_mode;
7180 const char* key;
7181 const char* iv;
7182 const char* input;
7183 const char* output;
7184};
7185
7186// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7187// of the NIST vectors are multiples of the block size.
7188static const TripleDesTestVector kTripleDesTestVectors[] = {
7189 {
7190 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7191 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7192 "", // IV
7193 "329d86bdf1bc5af4", // input
7194 "d946c2756d78633f", // output
7195 },
7196 {
7197 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7198 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7199 "", // IV
7200 "6b1540781b01ce1997adae102dbf3c5b", // input
7201 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7202 },
7203 {
7204 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7205 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7206 "", // IV
7207 "6daad94ce08acfe7", // input
7208 "660e7d32dcc90e79", // output
7209 },
7210 {
7211 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7212 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7213 "", // IV
7214 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7215 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7216 },
7217 {
7218 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7219 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7220 "43f791134c5647ba", // IV
7221 "dcc153cef81d6f24", // input
7222 "92538bd8af18d3ba", // output
7223 },
7224 {
7225 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7226 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7227 "c2e999cb6249023c", // IV
7228 "c689aee38a301bb316da75db36f110b5", // input
7229 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7230 },
7231 {
7232 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7233 PaddingMode::PKCS7,
7234 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7235 "c2e999cb6249023c", // IV
7236 "c689aee38a301bb316da75db36f110b500", // input
7237 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7238 },
7239 {
7240 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7241 PaddingMode::PKCS7,
7242 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7243 "c2e999cb6249023c", // IV
7244 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7245 "c689aee38a301bb316da75db36f110b500", // output
7246 },
7247 {
7248 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7249 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7250 "41746c7e442d3681", // IV
7251 "c53a7b0ec40600fe", // input
7252 "d4f00eb455de1034", // output
7253 },
7254 {
7255 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7256 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7257 "3982bc02c3727d45", // IV
7258 "6006f10adef52991fcc777a1238bbb65", // input
7259 "edae09288e9e3bc05746d872b48e3b29", // output
7260 },
7261};
7262
7263/*
7264 * EncryptionOperationsTest.TripleDesTestVector
7265 *
7266 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7267 */
7268TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7269 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7270 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7271 SCOPED_TRACE(test->name);
7272 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7273 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7274 hex2str(test->output));
7275 }
7276}
7277
7278/*
7279 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7280 *
7281 * Validates CBC mode functionality.
7282 */
7283TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7285 .TripleDesEncryptionKey(168)
7286 .BlockMode(BlockMode::CBC)
7287 .Authorization(TAG_NO_AUTH_REQUIRED)
7288 .Padding(PaddingMode::NONE)));
7289
7290 ASSERT_GT(key_blob_.size(), 0U);
7291
Brian J Murray734c8412022-01-13 14:55:30 -08007292 // Four-block message.
7293 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007294 vector<uint8_t> iv1;
7295 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7296 EXPECT_EQ(message.size(), ciphertext1.size());
7297
7298 vector<uint8_t> iv2;
7299 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7300 EXPECT_EQ(message.size(), ciphertext2.size());
7301
7302 // IVs should be random, so ciphertexts should differ.
7303 EXPECT_NE(iv1, iv2);
7304 EXPECT_NE(ciphertext1, ciphertext2);
7305
7306 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7307 EXPECT_EQ(message, plaintext);
7308}
7309
7310/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007311 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7312 *
7313 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7314 */
7315TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7317 .TripleDesEncryptionKey(168)
7318 .BlockMode(BlockMode::CBC)
7319 .Authorization(TAG_NO_AUTH_REQUIRED)
7320 .Authorization(TAG_CALLER_NONCE)
7321 .Padding(PaddingMode::NONE)));
7322 auto params = AuthorizationSetBuilder()
7323 .BlockMode(BlockMode::CBC)
7324 .Padding(PaddingMode::NONE)
7325 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7326 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7327}
7328
7329/*
Selene Huang31ab4042020-04-29 04:22:39 -07007330 * EncryptionOperationsTest.TripleDesCallerIv
7331 *
7332 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7333 */
7334TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7335 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7336 .TripleDesEncryptionKey(168)
7337 .BlockMode(BlockMode::CBC)
7338 .Authorization(TAG_NO_AUTH_REQUIRED)
7339 .Authorization(TAG_CALLER_NONCE)
7340 .Padding(PaddingMode::NONE)));
7341 string message = "1234567890123456";
7342 vector<uint8_t> iv;
7343 // Don't specify IV, should get a random one.
7344 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7345 EXPECT_EQ(message.size(), ciphertext1.size());
7346 EXPECT_EQ(8U, iv.size());
7347
7348 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7349 EXPECT_EQ(message, plaintext);
7350
7351 // Now specify an IV, should also work.
7352 iv = AidlBuf("abcdefgh");
7353 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7354
7355 // Decrypt with correct IV.
7356 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7357 EXPECT_EQ(message, plaintext);
7358
7359 // Now try with wrong IV.
7360 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7361 EXPECT_NE(message, plaintext);
7362}
7363
7364/*
7365 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7366 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007367 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007368 */
7369TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7371 .TripleDesEncryptionKey(168)
7372 .BlockMode(BlockMode::CBC)
7373 .Authorization(TAG_NO_AUTH_REQUIRED)
7374 .Padding(PaddingMode::NONE)));
7375
7376 string message = "12345678901234567890123456789012";
7377 vector<uint8_t> iv;
7378 // Don't specify nonce, should get a random one.
7379 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7380 EXPECT_EQ(message.size(), ciphertext1.size());
7381 EXPECT_EQ(8U, iv.size());
7382
7383 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7384 EXPECT_EQ(message, plaintext);
7385
7386 // Now specify a nonce, should fail.
7387 auto input_params = AuthorizationSetBuilder()
7388 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7389 .BlockMode(BlockMode::CBC)
7390 .Padding(PaddingMode::NONE);
7391 AuthorizationSet output_params;
7392 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7393 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7394}
7395
7396/*
7397 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7398 *
7399 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7400 */
7401TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7402 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7403 .TripleDesEncryptionKey(168)
7404 .BlockMode(BlockMode::ECB)
7405 .Authorization(TAG_NO_AUTH_REQUIRED)
7406 .Padding(PaddingMode::NONE)));
7407 // Two-block message.
7408 string message = "1234567890123456";
7409 auto begin_params =
7410 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7411 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7412}
7413
7414/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007415 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007416 *
7417 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7418 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007419TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7420 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007421 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7423 .TripleDesEncryptionKey(168)
7424 .BlockMode(blockMode)
7425 .Authorization(TAG_NO_AUTH_REQUIRED)
7426 .Padding(PaddingMode::NONE)));
7427 // Message is slightly shorter than two blocks.
7428 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007429
David Drysdaled2cc8c22021-04-15 13:29:45 +01007430 auto begin_params =
7431 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7432 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007433 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007434 string ciphertext;
7435 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7436
7437 CheckedDeleteKey();
7438 }
Selene Huang31ab4042020-04-29 04:22:39 -07007439}
7440
7441/*
7442 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7443 *
7444 * Verifies that PKCS7 padding works correctly in CBC mode.
7445 */
7446TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7447 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7448 .TripleDesEncryptionKey(168)
7449 .BlockMode(BlockMode::CBC)
7450 .Authorization(TAG_NO_AUTH_REQUIRED)
7451 .Padding(PaddingMode::PKCS7)));
7452
7453 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007454 for (size_t i = 0; i <= 32; i++) {
7455 SCOPED_TRACE(testing::Message() << "i = " << i);
7456 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7457 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007458 vector<uint8_t> iv;
7459 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7460 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7461 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7462 EXPECT_EQ(message, plaintext);
7463 }
7464}
7465
7466/*
7467 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7468 *
7469 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7470 */
7471TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7472 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7473 .TripleDesEncryptionKey(168)
7474 .BlockMode(BlockMode::CBC)
7475 .Authorization(TAG_NO_AUTH_REQUIRED)
7476 .Padding(PaddingMode::NONE)));
7477
7478 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007479 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007480 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007481 auto begin_params =
7482 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7483 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7484 }
7485}
7486
7487/*
7488 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7489 *
7490 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7491 */
7492TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7494 .TripleDesEncryptionKey(168)
7495 .BlockMode(BlockMode::CBC)
7496 .Authorization(TAG_NO_AUTH_REQUIRED)
7497 .Padding(PaddingMode::PKCS7)));
7498
7499 string message = "a";
7500 vector<uint8_t> iv;
7501 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7502 EXPECT_EQ(8U, ciphertext.size());
7503 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007504
7505 auto begin_params = AuthorizationSetBuilder()
7506 .BlockMode(BlockMode::CBC)
7507 .Padding(PaddingMode::PKCS7)
7508 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007509
7510 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007511 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007512 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007513 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007514 string plaintext;
7515 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7516 ErrorCode error = Finish(&plaintext);
7517 if (error == ErrorCode::INVALID_ARGUMENT) {
7518 // This is the expected error, we can exit the test now.
7519 return;
7520 } else {
7521 // Very small chance we got valid decryption, so try again.
7522 ASSERT_EQ(error, ErrorCode::OK);
7523 }
7524 }
7525 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007526}
7527
7528/*
7529 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7530 *
7531 * Verifies that 3DES CBC works with many different input sizes.
7532 */
7533TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7534 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7535 .TripleDesEncryptionKey(168)
7536 .BlockMode(BlockMode::CBC)
7537 .Authorization(TAG_NO_AUTH_REQUIRED)
7538 .Padding(PaddingMode::NONE)));
7539
7540 int increment = 7;
7541 string message(240, 'a');
7542 AuthorizationSet input_params =
7543 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7544 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007545 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007546
7547 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007548 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007549 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007550 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7551 EXPECT_EQ(message.size(), ciphertext.size());
7552
7553 // Move TAG_NONCE into input_params
7554 input_params = output_params;
7555 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7556 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7557 output_params.Clear();
7558
David Drysdale7fc26b92022-05-13 09:54:24 +01007559 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007560 string plaintext;
7561 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007562 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007563 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7564 EXPECT_EQ(ciphertext.size(), plaintext.size());
7565 EXPECT_EQ(message, plaintext);
7566}
7567
7568INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7569
7570typedef KeyMintAidlTestBase MaxOperationsTest;
7571
7572/*
7573 * MaxOperationsTest.TestLimitAes
7574 *
7575 * Verifies that the max uses per boot tag works correctly with AES keys.
7576 */
7577TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007578 if (SecLevel() == SecurityLevel::STRONGBOX) {
7579 GTEST_SKIP() << "Test not applicable to StrongBox device";
7580 }
Selene Huang31ab4042020-04-29 04:22:39 -07007581
7582 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7583 .Authorization(TAG_NO_AUTH_REQUIRED)
7584 .AesEncryptionKey(128)
7585 .EcbMode()
7586 .Padding(PaddingMode::NONE)
7587 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7588
7589 string message = "1234567890123456";
7590
7591 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7592
7593 EncryptMessage(message, params);
7594 EncryptMessage(message, params);
7595 EncryptMessage(message, params);
7596
7597 // Fourth time should fail.
7598 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7599}
7600
7601/*
Qi Wud22ec842020-11-26 13:27:53 +08007602 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007603 *
7604 * Verifies that the max uses per boot tag works correctly with RSA keys.
7605 */
7606TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007607 if (SecLevel() == SecurityLevel::STRONGBOX) {
7608 GTEST_SKIP() << "Test not applicable to StrongBox device";
7609 }
Selene Huang31ab4042020-04-29 04:22:39 -07007610
7611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7612 .Authorization(TAG_NO_AUTH_REQUIRED)
7613 .RsaSigningKey(1024, 65537)
7614 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007615 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7616 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007617
7618 string message = "1234567890123456";
7619
7620 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7621
7622 SignMessage(message, params);
7623 SignMessage(message, params);
7624 SignMessage(message, params);
7625
7626 // Fourth time should fail.
7627 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7628}
7629
7630INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7631
Qi Wud22ec842020-11-26 13:27:53 +08007632typedef KeyMintAidlTestBase UsageCountLimitTest;
7633
7634/*
Qi Wubeefae42021-01-28 23:16:37 +08007635 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007636 *
Qi Wubeefae42021-01-28 23:16:37 +08007637 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007638 */
Qi Wubeefae42021-01-28 23:16:37 +08007639TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007640 if (SecLevel() == SecurityLevel::STRONGBOX) {
7641 GTEST_SKIP() << "Test not applicable to StrongBox device";
7642 }
Qi Wud22ec842020-11-26 13:27:53 +08007643
7644 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7645 .Authorization(TAG_NO_AUTH_REQUIRED)
7646 .AesEncryptionKey(128)
7647 .EcbMode()
7648 .Padding(PaddingMode::NONE)
7649 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7650
7651 // Check the usage count limit tag appears in the authorizations.
7652 AuthorizationSet auths;
7653 for (auto& entry : key_characteristics_) {
7654 auths.push_back(AuthorizationSet(entry.authorizations));
7655 }
7656 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7657 << "key usage count limit " << 1U << " missing";
7658
7659 string message = "1234567890123456";
7660 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7661
Qi Wubeefae42021-01-28 23:16:37 +08007662 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7663 AuthorizationSet keystore_auths =
7664 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7665
Qi Wud22ec842020-11-26 13:27:53 +08007666 // First usage of AES key should work.
7667 EncryptMessage(message, params);
7668
Qi Wud22ec842020-11-26 13:27:53 +08007669 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7670 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7671 // must be invalidated from secure storage (such as RPMB partition).
7672 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7673 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007674 // Usage count limit tag is enforced by keystore, keymint does nothing.
7675 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007676 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007677 }
7678}
7679
7680/*
Qi Wubeefae42021-01-28 23:16:37 +08007681 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007682 *
Qi Wubeefae42021-01-28 23:16:37 +08007683 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007684 */
Qi Wubeefae42021-01-28 23:16:37 +08007685TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007686 if (SecLevel() == SecurityLevel::STRONGBOX) {
7687 GTEST_SKIP() << "Test not applicable to StrongBox device";
7688 }
Qi Wubeefae42021-01-28 23:16:37 +08007689
7690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7691 .Authorization(TAG_NO_AUTH_REQUIRED)
7692 .AesEncryptionKey(128)
7693 .EcbMode()
7694 .Padding(PaddingMode::NONE)
7695 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7696
7697 // Check the usage count limit tag appears in the authorizations.
7698 AuthorizationSet auths;
7699 for (auto& entry : key_characteristics_) {
7700 auths.push_back(AuthorizationSet(entry.authorizations));
7701 }
7702 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7703 << "key usage count limit " << 3U << " missing";
7704
7705 string message = "1234567890123456";
7706 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7707
7708 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7709 AuthorizationSet keystore_auths =
7710 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7711
7712 EncryptMessage(message, params);
7713 EncryptMessage(message, params);
7714 EncryptMessage(message, params);
7715
7716 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7717 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7718 // must be invalidated from secure storage (such as RPMB partition).
7719 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7720 } else {
7721 // Usage count limit tag is enforced by keystore, keymint does nothing.
7722 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007723 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007724 }
7725}
7726
7727/*
7728 * UsageCountLimitTest.TestSingleUseRsa
7729 *
7730 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7731 */
7732TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007733 if (SecLevel() == SecurityLevel::STRONGBOX) {
7734 GTEST_SKIP() << "Test not applicable to StrongBox device";
7735 }
Qi Wud22ec842020-11-26 13:27:53 +08007736
7737 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7738 .Authorization(TAG_NO_AUTH_REQUIRED)
7739 .RsaSigningKey(1024, 65537)
7740 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007741 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7742 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007743
7744 // Check the usage count limit tag appears in the authorizations.
7745 AuthorizationSet auths;
7746 for (auto& entry : key_characteristics_) {
7747 auths.push_back(AuthorizationSet(entry.authorizations));
7748 }
7749 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7750 << "key usage count limit " << 1U << " missing";
7751
7752 string message = "1234567890123456";
7753 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7754
Qi Wubeefae42021-01-28 23:16:37 +08007755 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7756 AuthorizationSet keystore_auths =
7757 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7758
Qi Wud22ec842020-11-26 13:27:53 +08007759 // First usage of RSA key should work.
7760 SignMessage(message, params);
7761
Qi Wud22ec842020-11-26 13:27:53 +08007762 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7763 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7764 // must be invalidated from secure storage (such as RPMB partition).
7765 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7766 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007767 // Usage count limit tag is enforced by keystore, keymint does nothing.
7768 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007769 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007770 }
7771}
7772
7773/*
7774 * UsageCountLimitTest.TestLimitUseRsa
7775 *
7776 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7777 */
7778TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007779 if (SecLevel() == SecurityLevel::STRONGBOX) {
7780 GTEST_SKIP() << "Test not applicable to StrongBox device";
7781 }
Qi Wubeefae42021-01-28 23:16:37 +08007782
7783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7784 .Authorization(TAG_NO_AUTH_REQUIRED)
7785 .RsaSigningKey(1024, 65537)
7786 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007787 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7788 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007789
7790 // Check the usage count limit tag appears in the authorizations.
7791 AuthorizationSet auths;
7792 for (auto& entry : key_characteristics_) {
7793 auths.push_back(AuthorizationSet(entry.authorizations));
7794 }
7795 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7796 << "key usage count limit " << 3U << " missing";
7797
7798 string message = "1234567890123456";
7799 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7800
7801 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7802 AuthorizationSet keystore_auths =
7803 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7804
7805 SignMessage(message, params);
7806 SignMessage(message, params);
7807 SignMessage(message, params);
7808
7809 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7810 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7811 // must be invalidated from secure storage (such as RPMB partition).
7812 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7813 } else {
7814 // Usage count limit tag is enforced by keystore, keymint does nothing.
7815 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007816 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007817 }
7818}
7819
Qi Wu8e727f72021-02-11 02:49:33 +08007820/*
7821 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7822 *
7823 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7824 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7825 * in hardware.
7826 */
7827TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007828 if (SecLevel() == SecurityLevel::STRONGBOX) {
7829 GTEST_SKIP() << "Test not applicable to StrongBox device";
7830 }
Qi Wu8e727f72021-02-11 02:49:33 +08007831
7832 auto error = GenerateKey(AuthorizationSetBuilder()
7833 .RsaSigningKey(2048, 65537)
7834 .Digest(Digest::NONE)
7835 .Padding(PaddingMode::NONE)
7836 .Authorization(TAG_NO_AUTH_REQUIRED)
7837 .Authorization(TAG_ROLLBACK_RESISTANCE)
7838 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007839 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7840 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007841 }
David Drysdale513bf122021-10-06 11:53:13 +01007842
7843 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7844 ASSERT_EQ(ErrorCode::OK, error);
7845 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7846 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7847 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7848
7849 // The KeyMint should also enforce single use key in hardware when it supports rollback
7850 // resistance.
7851 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7852 .Authorization(TAG_NO_AUTH_REQUIRED)
7853 .RsaSigningKey(1024, 65537)
7854 .NoDigestOrPadding()
7855 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7856 .SetDefaultValidity()));
7857
7858 // Check the usage count limit tag appears in the hardware authorizations.
7859 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7860 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7861 << "key usage count limit " << 1U << " missing";
7862
7863 string message = "1234567890123456";
7864 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7865
7866 // First usage of RSA key should work.
7867 SignMessage(message, params);
7868
7869 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7870 // must be invalidated from secure storage (such as RPMB partition).
7871 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007872}
7873
Qi Wud22ec842020-11-26 13:27:53 +08007874INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7875
David Drysdale7de9feb2021-03-05 14:56:19 +00007876typedef KeyMintAidlTestBase GetHardwareInfoTest;
7877
7878TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7879 // Retrieving hardware info should give the same result each time.
7880 KeyMintHardwareInfo info;
7881 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7882 KeyMintHardwareInfo info2;
7883 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7884 EXPECT_EQ(info, info2);
7885}
7886
7887INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7888
Selene Huang31ab4042020-04-29 04:22:39 -07007889typedef KeyMintAidlTestBase AddEntropyTest;
7890
7891/*
7892 * AddEntropyTest.AddEntropy
7893 *
7894 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7895 * is actually added.
7896 */
7897TEST_P(AddEntropyTest, AddEntropy) {
7898 string data = "foo";
7899 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7900}
7901
7902/*
7903 * AddEntropyTest.AddEmptyEntropy
7904 *
7905 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7906 */
7907TEST_P(AddEntropyTest, AddEmptyEntropy) {
7908 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7909}
7910
7911/*
7912 * AddEntropyTest.AddLargeEntropy
7913 *
7914 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7915 */
7916TEST_P(AddEntropyTest, AddLargeEntropy) {
7917 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7918}
7919
David Drysdalebb3d85e2021-04-13 11:15:51 +01007920/*
7921 * AddEntropyTest.AddTooLargeEntropy
7922 *
7923 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7924 */
7925TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7926 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7927 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7928}
7929
Selene Huang31ab4042020-04-29 04:22:39 -07007930INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7931
Selene Huang31ab4042020-04-29 04:22:39 -07007932typedef KeyMintAidlTestBase KeyDeletionTest;
7933
7934/**
7935 * KeyDeletionTest.DeleteKey
7936 *
7937 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7938 * valid key blob.
7939 */
7940TEST_P(KeyDeletionTest, DeleteKey) {
7941 auto error = GenerateKey(AuthorizationSetBuilder()
7942 .RsaSigningKey(2048, 65537)
7943 .Digest(Digest::NONE)
7944 .Padding(PaddingMode::NONE)
7945 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007946 .Authorization(TAG_ROLLBACK_RESISTANCE)
7947 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007948 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7949 GTEST_SKIP() << "Rollback resistance not supported";
7950 }
Selene Huang31ab4042020-04-29 04:22:39 -07007951
7952 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007953 ASSERT_EQ(ErrorCode::OK, error);
7954 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7955 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007956
David Drysdale513bf122021-10-06 11:53:13 +01007957 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007958
David Drysdale513bf122021-10-06 11:53:13 +01007959 string message = "12345678901234567890123456789012";
7960 AuthorizationSet begin_out_params;
7961 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7962 Begin(KeyPurpose::SIGN, key_blob_,
7963 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7964 &begin_out_params));
7965 AbortIfNeeded();
7966 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007967}
7968
7969/**
7970 * KeyDeletionTest.DeleteInvalidKey
7971 *
7972 * This test checks that the HAL excepts invalid key blobs..
7973 */
7974TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7975 // Generate key just to check if rollback protection is implemented
7976 auto error = GenerateKey(AuthorizationSetBuilder()
7977 .RsaSigningKey(2048, 65537)
7978 .Digest(Digest::NONE)
7979 .Padding(PaddingMode::NONE)
7980 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007981 .Authorization(TAG_ROLLBACK_RESISTANCE)
7982 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007983 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7984 GTEST_SKIP() << "Rollback resistance not supported";
7985 }
Selene Huang31ab4042020-04-29 04:22:39 -07007986
7987 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007988 ASSERT_EQ(ErrorCode::OK, error);
7989 AuthorizationSet enforced(SecLevelAuthorizations());
7990 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007991
David Drysdale513bf122021-10-06 11:53:13 +01007992 // Delete the key we don't care about the result at this point.
7993 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007994
David Drysdale513bf122021-10-06 11:53:13 +01007995 // Now create an invalid key blob and delete it.
7996 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007997
David Drysdale513bf122021-10-06 11:53:13 +01007998 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007999}
8000
8001/**
8002 * KeyDeletionTest.DeleteAllKeys
8003 *
8004 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8005 *
8006 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8007 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8008 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8009 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8010 * credentials stored in Keystore/Keymint.
8011 */
8012TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008013 if (!arm_deleteAllKeys) {
8014 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8015 return;
8016 }
Selene Huang31ab4042020-04-29 04:22:39 -07008017 auto error = GenerateKey(AuthorizationSetBuilder()
8018 .RsaSigningKey(2048, 65537)
8019 .Digest(Digest::NONE)
8020 .Padding(PaddingMode::NONE)
8021 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008022 .Authorization(TAG_ROLLBACK_RESISTANCE)
8023 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008024 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8025 GTEST_SKIP() << "Rollback resistance not supported";
8026 }
Selene Huang31ab4042020-04-29 04:22:39 -07008027
8028 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008029 ASSERT_EQ(ErrorCode::OK, error);
8030 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8031 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008032
David Drysdale513bf122021-10-06 11:53:13 +01008033 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008034
David Drysdale513bf122021-10-06 11:53:13 +01008035 string message = "12345678901234567890123456789012";
8036 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008037
David Drysdale513bf122021-10-06 11:53:13 +01008038 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8039 Begin(KeyPurpose::SIGN, key_blob_,
8040 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8041 &begin_out_params));
8042 AbortIfNeeded();
8043 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008044}
8045
8046INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8047
David Drysdaled2cc8c22021-04-15 13:29:45 +01008048typedef KeyMintAidlTestBase KeyUpgradeTest;
8049
8050/**
8051 * KeyUpgradeTest.UpgradeInvalidKey
8052 *
8053 * This test checks that the HAL excepts invalid key blobs..
8054 */
8055TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8056 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8057
8058 std::vector<uint8_t> new_blob;
8059 Status result = keymint_->upgradeKey(key_blob,
8060 AuthorizationSetBuilder()
8061 .Authorization(TAG_APPLICATION_ID, "clientid")
8062 .Authorization(TAG_APPLICATION_DATA, "appdata")
8063 .vector_data(),
8064 &new_blob);
8065 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8066}
8067
8068INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8069
Selene Huang31ab4042020-04-29 04:22:39 -07008070using UpgradeKeyTest = KeyMintAidlTestBase;
8071
8072/*
8073 * UpgradeKeyTest.UpgradeKey
8074 *
8075 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8076 */
8077TEST_P(UpgradeKeyTest, UpgradeKey) {
8078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8079 .AesEncryptionKey(128)
8080 .Padding(PaddingMode::NONE)
8081 .Authorization(TAG_NO_AUTH_REQUIRED)));
8082
8083 auto result = UpgradeKey(key_blob_);
8084
8085 // Key doesn't need upgrading. Should get okay, but no new key blob.
8086 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8087}
8088
8089INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8090
8091using ClearOperationsTest = KeyMintAidlTestBase;
8092
8093/*
8094 * ClearSlotsTest.TooManyOperations
8095 *
8096 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8097 * operations are started without being finished or aborted. Also verifies
8098 * that aborting the operations clears the operations.
8099 *
8100 */
8101TEST_P(ClearOperationsTest, TooManyOperations) {
8102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8103 .Authorization(TAG_NO_AUTH_REQUIRED)
8104 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008105 .Padding(PaddingMode::NONE)
8106 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008107
8108 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8109 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008110 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008111 AuthorizationSet out_params;
8112 ErrorCode result;
8113 size_t i;
8114
8115 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008116 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008117 if (ErrorCode::OK != result) {
8118 break;
8119 }
8120 }
8121 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8122 // Try again just in case there's a weird overflow bug
8123 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008124 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008125 for (size_t j = 0; j < i; j++) {
8126 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8127 << "Aboort failed for i = " << j << std::endl;
8128 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008129 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008130 AbortIfNeeded();
8131}
8132
8133INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8134
8135typedef KeyMintAidlTestBase TransportLimitTest;
8136
8137/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008138 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008139 *
8140 * Verifies that passing input data to finish succeeds as expected.
8141 */
8142TEST_P(TransportLimitTest, LargeFinishInput) {
8143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8144 .Authorization(TAG_NO_AUTH_REQUIRED)
8145 .AesEncryptionKey(128)
8146 .BlockMode(BlockMode::ECB)
8147 .Padding(PaddingMode::NONE)));
8148
8149 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008150 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008151 auto cipher_params =
8152 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8153
8154 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008155 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008156
8157 string plain_message = std::string(1 << msg_size, 'x');
8158 string encrypted_message;
8159 auto rc = Finish(plain_message, &encrypted_message);
8160
8161 EXPECT_EQ(ErrorCode::OK, rc);
8162 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8163 << "Encrypt finish returned OK, but did not consume all of the given input";
8164 cipher_params.push_back(out_params);
8165
David Drysdale7fc26b92022-05-13 09:54:24 +01008166 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008167
8168 string decrypted_message;
8169 rc = Finish(encrypted_message, &decrypted_message);
8170 EXPECT_EQ(ErrorCode::OK, rc);
8171 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8172 << "Decrypt finish returned OK, did not consume all of the given input";
8173 }
8174}
8175
8176INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8177
Seth Moored79a0ec2021-12-13 20:03:33 +00008178static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008179 switch (curve) {
8180 case EcCurve::P_224:
8181 return NID_secp224r1;
8182 case EcCurve::P_256:
8183 return NID_X9_62_prime256v1;
8184 case EcCurve::P_384:
8185 return NID_secp384r1;
8186 case EcCurve::P_521:
8187 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008188 case EcCurve::CURVE_25519:
8189 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008190 }
8191}
8192
David Drysdale42fe1892021-10-14 14:43:46 +01008193class KeyAgreementTest : public KeyMintAidlTestBase {
8194 protected:
8195 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8196 std::vector<uint8_t>* localPublicKey) {
8197 // Generate EC key locally (with access to private key material)
8198 if (localCurve == EcCurve::CURVE_25519) {
8199 uint8_t privKeyData[32];
8200 uint8_t pubKeyData[32];
8201 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008202 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8203 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8204 } else {
8205 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8206 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8207 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8208 ASSERT_NE(group, nullptr);
8209 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8210 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8211 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8212 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008213 }
David Drysdalea410b772022-05-09 16:44:13 +01008214
8215 // Get encoded form of the public part of the locally generated key...
8216 unsigned char* p = nullptr;
8217 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8218 ASSERT_GT(localPublicKeySize, 0);
8219 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8220 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8221 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008222 }
8223
8224 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8225 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008226 auto builder = AuthorizationSetBuilder()
8227 .Authorization(TAG_NO_AUTH_REQUIRED)
8228 .Authorization(TAG_EC_CURVE, curve)
8229 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8230 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8231 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8232 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8233 .SetDefaultValidity();
8234 ErrorCode result = GenerateKey(builder);
8235
8236 if (SecLevel() == SecurityLevel::STRONGBOX) {
8237 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8238 result = GenerateKeyWithSelfSignedAttestKey(
8239 AuthorizationSetBuilder()
8240 .EcdsaKey(EcCurve::P_256)
8241 .AttestKey()
8242 .SetDefaultValidity(), /* attest key params */
8243 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8244 }
8245 }
David Drysdale42fe1892021-10-14 14:43:46 +01008246 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8247 ASSERT_GT(cert_chain_.size(), 0);
8248 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8249 ASSERT_NE(kmKeyCert, nullptr);
8250 // Check that keyAgreement (bit 4) is set in KeyUsage
8251 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8252 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8253 ASSERT_NE(*kmPubKey, nullptr);
8254 if (dump_Attestations) {
8255 for (size_t n = 0; n < cert_chain_.size(); n++) {
8256 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8257 }
8258 }
8259 }
8260
8261 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8262 const std::vector<uint8_t>& localPublicKey) {
8263 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8264 string ZabFromKeyMintStr;
8265 ASSERT_EQ(ErrorCode::OK,
8266 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8267 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8268 vector<uint8_t> ZabFromTest;
8269
8270 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8271 size_t kmPubKeySize = 32;
8272 uint8_t kmPubKeyData[32];
8273 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8274 ASSERT_EQ(kmPubKeySize, 32);
8275
8276 uint8_t localPrivKeyData[32];
8277 size_t localPrivKeySize = 32;
8278 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8279 &localPrivKeySize));
8280 ASSERT_EQ(localPrivKeySize, 32);
8281
8282 uint8_t sharedKey[32];
8283 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8284 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8285 } else {
8286 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8287 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8288 ASSERT_NE(ctx, nullptr);
8289 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8290 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8291 size_t ZabFromTestLen = 0;
8292 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8293 ZabFromTest.resize(ZabFromTestLen);
8294 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8295 }
8296 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8297 }
8298};
8299
David Zeuthene0c40892021-01-08 12:54:11 -05008300/*
8301 * KeyAgreementTest.Ecdh
8302 *
David Drysdale42fe1892021-10-14 14:43:46 +01008303 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008304 */
8305TEST_P(KeyAgreementTest, Ecdh) {
8306 // Because it's possible to use this API with keys on different curves, we
8307 // check all N^2 combinations where N is the number of supported
8308 // curves.
8309 //
8310 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8311 // lot more curves we can be smart about things and just pick |otherCurve| so
8312 // it's not |curve| and that way we end up with only 2*N runs
8313 //
8314 for (auto curve : ValidCurves()) {
8315 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008316 SCOPED_TRACE(testing::Message()
8317 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8318
David Zeuthene0c40892021-01-08 12:54:11 -05008319 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008320 EVP_PKEY_Ptr localPrivKey;
8321 vector<uint8_t> localPublicKey;
8322 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008323
8324 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008325 EVP_PKEY_Ptr kmPubKey;
8326 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008327
8328 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8329 if (curve != localCurve) {
8330 // If the keys are using different curves KeyMint should fail with
8331 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008332 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008333 string ZabFromKeyMintStr;
8334 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008335 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008336 &ZabFromKeyMintStr));
8337
8338 } else {
8339 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008340 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008341 }
8342
8343 CheckedDeleteKey();
8344 }
8345 }
8346}
8347
David Drysdale42fe1892021-10-14 14:43:46 +01008348/*
8349 * KeyAgreementTest.EcdhCurve25519
8350 *
8351 * Verifies that ECDH works for curve25519. This is also covered by the general
8352 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8353 * KeyMint 1.0.
8354 */
8355TEST_P(KeyAgreementTest, EcdhCurve25519) {
8356 if (!Curve25519Supported()) {
8357 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8358 }
8359
8360 // Generate EC key in KeyMint (only access to public key material)
8361 EcCurve curve = EcCurve::CURVE_25519;
8362 EVP_PKEY_Ptr kmPubKey = nullptr;
8363 GenerateKeyMintEcKey(curve, &kmPubKey);
8364
8365 // Generate EC key on same curve locally (with access to private key material).
8366 EVP_PKEY_Ptr privKey;
8367 vector<uint8_t> encodedPublicKey;
8368 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8369
8370 // Agree on a key between local and KeyMint and check it.
8371 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8372
8373 CheckedDeleteKey();
8374}
8375
8376/*
8377 * KeyAgreementTest.EcdhCurve25519Imported
8378 *
8379 * Verifies that ECDH works for an imported curve25519 key.
8380 */
8381TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8382 if (!Curve25519Supported()) {
8383 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8384 }
8385
8386 // Import x25519 key into KeyMint.
8387 EcCurve curve = EcCurve::CURVE_25519;
8388 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8389 .Authorization(TAG_NO_AUTH_REQUIRED)
8390 .EcdsaKey(EcCurve::CURVE_25519)
8391 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8392 .SetDefaultValidity(),
8393 KeyFormat::PKCS8, x25519_pkcs8_key));
8394 ASSERT_GT(cert_chain_.size(), 0);
8395 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8396 ASSERT_NE(kmKeyCert, nullptr);
8397 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8398 ASSERT_NE(kmPubKey.get(), nullptr);
8399
8400 // Expect the import to emit corresponding public key data.
8401 size_t kmPubKeySize = 32;
8402 uint8_t kmPubKeyData[32];
8403 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8404 ASSERT_EQ(kmPubKeySize, 32);
8405 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8406 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8407
8408 // Generate EC key on same curve locally (with access to private key material).
8409 EVP_PKEY_Ptr privKey;
8410 vector<uint8_t> encodedPublicKey;
8411 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8412
8413 // Agree on a key between local and KeyMint and check it.
8414 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8415
8416 CheckedDeleteKey();
8417}
8418
8419/*
8420 * KeyAgreementTest.EcdhCurve25519InvalidSize
8421 *
8422 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8423 */
8424TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8425 if (!Curve25519Supported()) {
8426 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8427 }
8428
8429 // Generate EC key in KeyMint (only access to public key material)
8430 EcCurve curve = EcCurve::CURVE_25519;
8431 EVP_PKEY_Ptr kmPubKey = nullptr;
8432 GenerateKeyMintEcKey(curve, &kmPubKey);
8433
8434 // Generate EC key on same curve locally (with access to private key material).
8435 EVP_PKEY_Ptr privKey;
8436 vector<uint8_t> encodedPublicKey;
8437 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8438
8439 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8440 string ZabFromKeyMintStr;
8441 // Send in an incomplete public key.
8442 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8443 &ZabFromKeyMintStr));
8444
8445 CheckedDeleteKey();
8446}
8447
8448/*
8449 * KeyAgreementTest.EcdhCurve25519Mismatch
8450 *
8451 * Verifies that ECDH fails between curve25519 and other curves.
8452 */
8453TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8454 if (!Curve25519Supported()) {
8455 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8456 }
8457
8458 // Generate EC key in KeyMint (only access to public key material)
8459 EcCurve curve = EcCurve::CURVE_25519;
8460 EVP_PKEY_Ptr kmPubKey = nullptr;
8461 GenerateKeyMintEcKey(curve, &kmPubKey);
8462
8463 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008464 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008465 if (localCurve == curve) {
8466 continue;
8467 }
8468 // Generate EC key on a different curve locally (with access to private key material).
8469 EVP_PKEY_Ptr privKey;
8470 vector<uint8_t> encodedPublicKey;
8471 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8472
David Drysdale7fc26b92022-05-13 09:54:24 +01008473 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008474 string ZabFromKeyMintStr;
8475 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8476 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8477 &ZabFromKeyMintStr));
8478 }
8479
8480 CheckedDeleteKey();
8481}
8482
David Zeuthene0c40892021-01-08 12:54:11 -05008483INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8484
David Drysdaled2cc8c22021-04-15 13:29:45 +01008485using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8486
8487// This is a problematic test, as it can render the device under test permanently unusable.
8488// Re-enable and run at your own risk.
8489TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8490 auto result = DestroyAttestationIds();
8491 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8492}
8493
8494INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8495
Shawn Willdend659c7c2021-02-19 14:51:51 -07008496using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008497
David Drysdaledb0dcf52021-05-18 11:43:31 +01008498/*
8499 * EarlyBootKeyTest.CreateEarlyBootKeys
8500 *
8501 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8502 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008503TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008504 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008505 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8506 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8507
David Drysdaleadfe6112021-05-27 12:00:53 +01008508 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8509 ASSERT_GT(keyData.blob.size(), 0U);
8510 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8511 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8512 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008513 CheckedDeleteKey(&aesKeyData.blob);
8514 CheckedDeleteKey(&hmacKeyData.blob);
8515 CheckedDeleteKey(&rsaKeyData.blob);
8516 CheckedDeleteKey(&ecdsaKeyData.blob);
8517}
8518
David Drysdaledb0dcf52021-05-18 11:43:31 +01008519/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008520 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8521 *
8522 * Verifies that creating an early boot key with attestation succeeds.
8523 */
8524TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8525 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8526 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8527 builder->AttestationChallenge("challenge");
8528 builder->AttestationApplicationId("app_id");
8529 });
8530
8531 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008532 // Strongbox may not support factory attestation. Key creation might fail with
8533 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8534 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8535 continue;
8536 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008537 ASSERT_GT(keyData.blob.size(), 0U);
8538 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8539 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8540 }
8541 CheckedDeleteKey(&aesKeyData.blob);
8542 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008543 if (rsaKeyData.blob.size() != 0U) {
8544 CheckedDeleteKey(&rsaKeyData.blob);
8545 }
8546 if (ecdsaKeyData.blob.size() != 0U) {
8547 CheckedDeleteKey(&ecdsaKeyData.blob);
8548 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008549}
8550
8551/*
8552 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008553 *
8554 * Verifies that using early boot keys at a later stage fails.
8555 */
8556TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8558 .Authorization(TAG_NO_AUTH_REQUIRED)
8559 .Authorization(TAG_EARLY_BOOT_ONLY)
8560 .HmacKey(128)
8561 .Digest(Digest::SHA_2_256)
8562 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8563 AuthorizationSet output_params;
8564 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8565 AuthorizationSetBuilder()
8566 .Digest(Digest::SHA_2_256)
8567 .Authorization(TAG_MAC_LENGTH, 256),
8568 &output_params));
8569}
8570
8571/*
8572 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8573 *
8574 * Verifies that importing early boot keys fails.
8575 */
8576TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8577 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8578 .Authorization(TAG_NO_AUTH_REQUIRED)
8579 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008580 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008581 .Digest(Digest::SHA_2_256)
8582 .SetDefaultValidity(),
8583 KeyFormat::PKCS8, ec_256_key));
8584}
8585
David Drysdaled2cc8c22021-04-15 13:29:45 +01008586// 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 +00008587// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8588// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8589// early boot, so you'll have to reboot between runs.
8590TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8591 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8592 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8593 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8594 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8595 EXPECT_TRUE(
8596 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8597 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8598 EXPECT_TRUE(
8599 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8600
8601 // Should be able to use keys, since early boot has not ended
8602 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8603 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8604 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8605 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8606
8607 // End early boot
8608 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8609 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8610
8611 // Should not be able to use already-created keys.
8612 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8613 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8614 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8615 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8616
8617 CheckedDeleteKey(&aesKeyData.blob);
8618 CheckedDeleteKey(&hmacKeyData.blob);
8619 CheckedDeleteKey(&rsaKeyData.blob);
8620 CheckedDeleteKey(&ecdsaKeyData.blob);
8621
8622 // Should not be able to create new keys
8623 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8624 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8625
8626 CheckedDeleteKey(&aesKeyData.blob);
8627 CheckedDeleteKey(&hmacKeyData.blob);
8628 CheckedDeleteKey(&rsaKeyData.blob);
8629 CheckedDeleteKey(&ecdsaKeyData.blob);
8630}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008631
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008632INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8633
Shawn Willdend659c7c2021-02-19 14:51:51 -07008634using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008635
8636// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8637// between runs... and on most test devices there are no enrolled credentials so it can't be
8638// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8639// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8640// a manual test process, which includes unlocking between runs, which is why it's included here.
8641// Well, that and the fact that it's the only test we can do without also making calls into the
8642// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8643// implications might be, so that may or may not be a solution.
8644TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8645 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8646 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8647
8648 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8649 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8650 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8651 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8652
8653 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008654 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008655 ASSERT_EQ(ErrorCode::OK, rc);
8656 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8657 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8658 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8659 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8660
8661 CheckedDeleteKey(&aesKeyData.blob);
8662 CheckedDeleteKey(&hmacKeyData.blob);
8663 CheckedDeleteKey(&rsaKeyData.blob);
8664 CheckedDeleteKey(&ecdsaKeyData.blob);
8665}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008666
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008667INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8668
Shawn Willden22fb9c12022-06-02 14:04:33 -06008669using VsrRequirementTest = KeyMintAidlTestBase;
8670
8671TEST_P(VsrRequirementTest, Vsr13Test) {
8672 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008673 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008674 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8675 }
8676 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8677}
8678
Eran Messerib9346f52022-12-15 14:58:34 +00008679TEST_P(VsrRequirementTest, Vsr14Test) {
8680 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008681 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008682 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8683 }
8684 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8685}
8686
Shawn Willden22fb9c12022-06-02 14:04:33 -06008687INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8688
Janis Danisevskis24c04702020-12-16 18:28:39 -08008689} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008690
8691int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008692 std::cout << "Testing ";
8693 auto halInstances =
8694 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8695 std::cout << "HAL instances:\n";
8696 for (auto& entry : halInstances) {
8697 std::cout << " " << entry << '\n';
8698 }
8699
Selene Huang31ab4042020-04-29 04:22:39 -07008700 ::testing::InitGoogleTest(&argc, argv);
8701 for (int i = 1; i < argc; ++i) {
8702 if (argv[i][0] == '-') {
8703 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008704 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8705 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008706 }
8707 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008708 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8709 dump_Attestations = true;
8710 } else {
8711 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008712 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008713 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8714 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8715 // be run in emulated environments that don't have the normal bootloader
8716 // interactions.
8717 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8718 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008719 if (std::string(argv[i]) == "--keyblob_dir") {
8720 if (i + 1 >= argc) {
8721 std::cerr << "Missing argument for --keyblob_dir\n";
8722 return 1;
8723 }
8724 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8725 std::string(argv[i + 1]);
8726 ++i;
8727 }
Selene Huang31ab4042020-04-29 04:22:39 -07008728 }
8729 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008730 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008731}